Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[legacy-framework] (meta) Remove need to build framework code during development 🎉 #2032

Merged
merged 5 commits into from
Mar 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion babel.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ module.exports = {
"babel-plugin-dev-expression",
["@babel/plugin-proposal-class-properties", {loose: true}],
"babel-plugin-macros",
// ["babel-plugin-polyfill-regenerator", {method: "usage-pure"}],
[
"transform-inline-environment-variables",
{
include: ["BLITZ_PROD_BUILD"],
},
],
],
}
34 changes: 18 additions & 16 deletions examples/auth/blitz.config.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
const {sessionMiddleware, simpleRolesIsAuthorized} = require("@blitzjs/server")
const withMonorepoBuildTooling = require("@preconstruct/next")
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
})

// withPreconstruct only needed for our internal monorepo
module.exports = withBundleAnalyzer({
middleware: [
sessionMiddleware({
isAuthorized: simpleRolesIsAuthorized,
// sessionExpiryMinutes: 4,
}),
],
log: {
// level: "trace",
},
experimental: {
isomorphicResolverImports: false,
},
/*
module.exports = withMonorepoBuildTooling(
withBundleAnalyzer({
middleware: [
sessionMiddleware({
isAuthorized: simpleRolesIsAuthorized,
// sessionExpiryMinutes: 4,
}),
],
log: {
// level: "trace",
},
experimental: {
isomorphicResolverImports: false,
},
/*
webpack: (config, {buildId, dev, isServer, defaultLoaders, webpack}) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
Expand All @@ -30,4 +31,5 @@ module.exports = withBundleAnalyzer({
return config
},
*/
})
}),
)
5 changes: 3 additions & 2 deletions examples/custom-server/blitz.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const {sessionMiddleware, simpleRolesIsAuthorized} = require("@blitzjs/server")
const withMonorepoBuildTooling = require("@preconstruct/next")

module.exports = {
module.exports = withMonorepoBuildTooling({
middleware: [
sessionMiddleware({
isAuthorized: simpleRolesIsAuthorized,
Expand All @@ -14,4 +15,4 @@ module.exports = {
return config
},
*/
}
})
5 changes: 3 additions & 2 deletions examples/fauna/blitz.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { sessionMiddleware, simpleRolesIsAuthorized } = require("@blitzjs/server")
const withMonorepoBuildTooling = require("@preconstruct/next")
const { GraphQLClient, gql } = require("graphql-request")

const graphQLClient = new GraphQLClient("https://graphql.fauna.com/graphql", {
Expand All @@ -17,7 +18,7 @@ const normalizeSession = (faunaSession) => {
}
}

module.exports = {
module.exports = withMonorepoBuildTooling({
middleware: [
sessionMiddleware({
isAuthorized: simpleRolesIsAuthorized,
Expand Down Expand Up @@ -158,4 +159,4 @@ module.exports = {
return config
},
*/
}
})
6 changes: 4 additions & 2 deletions examples/no-prisma/blitz.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
module.exports = {
const withMonorepoBuildTooling = require("@preconstruct/next")

module.exports = withMonorepoBuildTooling({
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
Expand All @@ -10,4 +12,4 @@ module.exports = {
// Important: return the modified config
return config
},
}
})
6 changes: 4 additions & 2 deletions examples/store/blitz.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
module.exports = {
const withMonorepoBuildTooling = require("@preconstruct/next")

module.exports = withMonorepoBuildTooling({
middleware: [
(req, res, next) => {
res.blitzCtx.referer = req.headers.referer
Expand All @@ -22,4 +24,4 @@ module.exports = {
// // Important: return the modified config
// return config
// },
}
})
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,11 @@
},
"scripts": {
"postinstall": "npm rebuild husky",
"waitfortypes": "wait-on packages/core/dist/blitzjs-core.esm.js && wait-on packages/server/dist/blitzjs-server.esm.js",
"dev:preconstruct": "preconstruct watch",
"dev:tsc": "yarn waitfortypes && tsc --watch --pretty --preserveWatchOutput",
"dev:cli": "yarn waitfortypes && yarn workspace @blitzjs/cli dev",
"dev:templates": "yarn waitfortypes && yarn workspace @blitzjs/generator dev",
"dev": "concurrently --names \"BUILD,TYPES,CLI,TEMPLATES\" -c \"blue,magenta,yellow,green\" \"npm:dev:preconstruct\" \"npm:dev:tsc\" \"npm:dev:cli\" \"npm:dev:templates\"",
"build": "preconstruct build && lerna run build --scope @blitzjs/* && tsc",
"dev:tsc": "tsc --watch --pretty --preserveWatchOutput",
"dev:cli": "yarn workspace @blitzjs/cli dev",
"dev:templates": "yarn workspace @blitzjs/generator dev",
"dev": "preconstruct dev && concurrently --names \"typecheck,cli,templates\" -c \"blue,green,yellow,magenta\" -p \"{name}\" \"npm:dev:tsc\" \"npm:dev:cli\" \"npm:dev:templates\"",
"build": "cross-env BLITZ_PROD_BUILD=true preconstruct build && lerna run build --scope @blitzjs/* && tsc",
"lint": "eslint --ignore-path .gitignore --ignore-pattern types --ext \".js,.ts,.tsx\" .",
"link-cli": "yarn workspace blitz link",
"unlink-cli": "yarn workspace blitz unlink",
Expand Down Expand Up @@ -59,6 +57,7 @@
"@babel/preset-typescript": "7.13.0",
"@manypkg/cli": "0.17.0",
"@preconstruct/cli": "2.0.5",
"@preconstruct/next": "2.0.0",
"@rollup/pluginutils": "4.1.0",
"@size-limit/preset-small-lib": "4.9.2",
"@testing-library/jest-dom": "5.11.9",
Expand Down Expand Up @@ -113,6 +112,7 @@
"babel-plugin-annotate-pure-calls": "0.4.0",
"babel-plugin-dev-expression": "0.2.2",
"babel-plugin-macros": "3.0.1",
"babel-plugin-transform-inline-environment-variables": "0.4.3",
"concurrently": "6.0.0",
"cpx": "1.5.0",
"cross-env": "7.0.3",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"version": "0.30.6",
"license": "MIT",
"scripts": {
"dev": "rimraf lib && tsc --watch --preserveWatchOutput",
"dev": "rimraf lib && tsc --watch --pretty --preserveWatchOutput",
"build": "rimraf lib && tsc",
"test": "jest --color",
"test:watch": "jest --watch",
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {Command, flags} from "@oclif/command"
import {build as ServerBuild, ServerConfig} from "@blitzjs/server"
import {ServerConfig} from "@blitzjs/server"

export class Build extends Command {
static description = "Creates a production build"
Expand All @@ -17,7 +17,7 @@ export class Build extends Command {
this.parse(Build)

try {
const build: typeof ServerBuild = require("@blitzjs/server").build
const {build} = await import("@blitzjs/server")
await build(config)
} catch (err) {
console.error(err)
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export async function handleRequestWithMiddleware(
} = {},
) {
if (!(res as MiddlewareResponse).blitzCtx) {
;(res as MiddlewareResponse).blitzCtx = {}
;(res as MiddlewareResponse).blitzCtx = {} as Ctx
}
if (!(res as any)._blitz) {
;(res as any)._blitz = {}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/passport-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function passportAuth(config: BlitzPassportConfig) {
log.info(`Starting authentication via ${strategyName}...`)
if (req.query.redirectUrl) {
middleware.push(async (req, res, next) => {
const session = res.blitzCtx.session as SessionContext
const session = (res as any).blitzCtx.session as SessionContext
assert(session, "Missing Blitz sessionMiddleware!")
await session.$setPublicData({[INTERNAL_REDIRECT_URL_KEY]: req.query.redirectUrl} as any)
return next()
Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/public-data-store.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import BadBehavior from "bad-behavior"
import {COOKIE_PUBLIC_DATA_TOKEN, LOCALSTORAGE_PREFIX} from "./constants"
import {PublicData} from "./types"
import {EmptyPublicData, PublicData} from "./types"
import {deleteCookie, readCookie} from "./utils/cookie"
import {parsePublicDataToken} from "./utils/tokens"

class PublicDataStore {
private eventKey = `${LOCALSTORAGE_PREFIX}publicDataUpdated`
readonly emptyPublicData: PublicData = {userId: null}
readonly observable = BadBehavior<PublicData>()
readonly emptyPublicData: EmptyPublicData = {userId: null}
readonly observable = BadBehavior<PublicData | EmptyPublicData>()

constructor() {
if (typeof window !== "undefined") {
Expand All @@ -22,7 +22,7 @@ class PublicDataStore {
}
}

updateState(value?: PublicData, opts?: {suppressEvent: boolean}) {
updateState(value?: PublicData | EmptyPublicData, opts?: {suppressEvent: boolean}) {
// We use localStorage as a message bus between tabs.
// Setting the current time in ms will cause other tabs to receive the `storage` event
if (!opts?.suppressEvent) {
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export interface AuthenticatedMiddlewareCtx extends Omit<Ctx, "session"> {
session: AuthenticatedSessionContext
}

type PipeFn<Prev, Next, PrevCtx extends Ctx, NextCtx = PrevCtx> = (
type PipeFn<Prev, Next, PrevCtx, NextCtx = PrevCtx> = (
i: Await<Prev>,
c: PrevCtx,
) => Next extends ResultWithContext ? never : Next | ResultWithContext<Next, NextCtx>
Expand Down
12 changes: 5 additions & 7 deletions packages/core/src/supertokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {COOKIE_CSRF_TOKEN, COOKIE_LEGACY_CSRF_TOKEN} from "./constants"
import {AuthenticationError} from "./errors"
import {Ctx} from "./middleware"
import {publicDataStore} from "./public-data-store"
import {IsAuthorizedArgs, PublicData} from "./types"
import {EmptyPublicData, IsAuthorizedArgs, PublicData} from "./types"
import {isServer} from "./utils"
import {readCookie} from "./utils/cookie"

Expand Down Expand Up @@ -48,9 +48,8 @@ export interface SessionContextBase {
}

// Could be anonymous
export interface SessionContext extends SessionContextBase, Partial<PublicData> {
userId: PublicData["userId"] | null
$publicData: Partial<PublicData>
export interface SessionContext extends SessionContextBase, EmptyPublicData {
$publicData: Partial<PublicData> | EmptyPublicData
}

export interface AuthenticatedSessionContext extends SessionContextBase, PublicData {
Expand All @@ -61,8 +60,7 @@ export interface AuthenticatedSessionContext extends SessionContextBase, PublicD
export const getAntiCSRFToken = () =>
readCookie(COOKIE_CSRF_TOKEN()) || readCookie(COOKIE_LEGACY_CSRF_TOKEN())

export interface ClientSession extends Partial<PublicData> {
userId: PublicData["userId"] | null
export interface ClientSession extends EmptyPublicData {
isLoading: boolean
}

Expand Down Expand Up @@ -109,7 +107,7 @@ export const useAuthenticatedSession = (
options: UseSessionOptions = {},
): AuthenticatedClientSession => {
useAuthorize()
return useSession(options)
return useSession(options) as AuthenticatedClientSession
}

export const useAuthorize = () => {
Expand Down
12 changes: 9 additions & 3 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import {AuthenticateOptions, Strategy} from "passport"
import {MutateOptions, MutationResult} from "react-query"
import {BlitzRuntimeData} from "./blitz-data"
import {Ctx} from "./middleware"
import {useParams} from "./use-params"
import {useRouterQuery} from "./use-router-query"

Expand Down Expand Up @@ -54,7 +55,12 @@ export interface Session {
// PublicData can be injected here (see supertokens.ts)
}

export type PublicData = "PublicData" extends keyof Session ? Session["PublicData"] : {userId: any}
export type PublicData = "PublicData" extends keyof Session
? Session["PublicData"]
: {userId: unknown}
export interface EmptyPublicData extends Partial<Omit<PublicData, "userId">> {
userId: PublicData["userId"] | null
}

export type IsAuthorizedArgs = "isAuthorized" extends keyof Session
? "args" extends keyof Parameters<Session["isAuthorized"]>[0]
Expand All @@ -65,13 +71,13 @@ export type IsAuthorizedArgs = "isAuthorized" extends keyof Session
export interface MiddlewareRequest extends BlitzApiRequest {
protocol?: string
}
export interface MiddlewareResponse extends BlitzApiResponse {
export interface MiddlewareResponse<C = Ctx> extends BlitzApiResponse {
/**
* This will be passed as the second argument to Blitz queries/mutations.
*
* You must set blitzCtx BEFORE calling next()
*/
blitzCtx: Record<string, unknown>
blitzCtx: C
/**
* This is the exact result returned from the Blitz query/mutation
*
Expand Down
6 changes: 4 additions & 2 deletions packages/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ export * from "./supertokens"
import next from "next"

// Support commonjs `require('blitz')`
module.exports = next
exports = module.exports
if (process.env.BLITZ_PROD_BUILD) {
module.exports = next
exports = module.exports
}

// eslint-disable-next-line import/no-default-export
export default next
4 changes: 2 additions & 2 deletions packages/server/src/supertokens.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe("supertokens", () => {
}) as unknown) as EnhancedResolver<unknown, unknown>
resolverModule.middleware = [
(_req, res, next) => {
expect(typeof (res.blitzCtx.session as SessionContext).$create).toBe("function")
expect(typeof ((res as any).blitzCtx.session as SessionContext).$create).toBe("function")
return next()
},
]
Expand Down Expand Up @@ -89,7 +89,7 @@ describe("supertokens", () => {
}) as unknown) as EnhancedResolver<unknown, unknown>
resolverModule.middleware = [
(_req, res, next) => {
expect(typeof (res.blitzCtx.session as SessionContext).$create).toBe("function")
expect(typeof ((res as any).blitzCtx.session as SessionContext).$create).toBe("function")
return next()
},
]
Expand Down
Loading