diff --git a/src/build/aot_snapshot.ts b/src/build/aot_snapshot.ts index 5d6618a9..a17d7fea 100644 --- a/src/build/aot_snapshot.ts +++ b/src/build/aot_snapshot.ts @@ -1,4 +1,7 @@ -import type { BuildSnapshot } from "./mod.ts"; +import { ResolvedFreshConfig } from "../server/types.ts"; +import { colors, join } from "../server/deps.ts"; +import type { BuildSnapshot, BuildSnapshotJson } from "./mod.ts"; +import { setBuildId } from "../server/build_id.ts"; export class AotSnapshot implements BuildSnapshot { #files: Map; @@ -35,3 +38,40 @@ export class AotSnapshot implements BuildSnapshot { return this.#dependencies.get(path) ?? []; } } + +export async function loadAotSnapshot( + config: ResolvedFreshConfig, +): Promise { + const snapshotDirPath = config.build.outDir; + try { + if ((await Deno.stat(snapshotDirPath)).isDirectory) { + console.log( + `Using snapshot found at ${colors.cyan(snapshotDirPath)}`, + ); + + const snapshotPath = join(snapshotDirPath, "snapshot.json"); + const json = JSON.parse( + await Deno.readTextFile(snapshotPath), + ) as BuildSnapshotJson; + setBuildId(json.build_id); + + const dependencies = new Map( + Object.entries(json.files), + ); + + const files = new Map(); + Object.keys(json.files).forEach((name) => { + const filePath = join(snapshotDirPath, name); + files.set(name, filePath); + }); + + return new AotSnapshot(files, dependencies); + } + return null; + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + return null; + } +} diff --git a/src/server/config.ts b/src/server/config.ts index 61278fed..d4b8e53c 100644 --- a/src/server/config.ts +++ b/src/server/config.ts @@ -1,5 +1,6 @@ import { dirname, fromFileUrl, isAbsolute, join, JSONC } from "./deps.ts"; import { FromManifestConfig, Manifest } from "./mod.ts"; +import { DEFAULT_RENDER_FN } from "./render.ts"; import { DenoConfig, InternalFreshState, @@ -54,15 +55,21 @@ export async function getInternalFreshState( ); } + const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true"; + const internalConfig: ResolvedFreshConfig = { - dev: config.dev ?? false, + dev: isLegacyDev || Boolean(config.dev), build: { - outDir: "", + outDir: config.build?.outDir + ? parseFileOrUrl(config.build.outDir, base) + : join(base, "_fresh"), target: config.build?.target ?? ["chrome99", "firefox99", "safari15"], }, plugins: config.plugins ?? [], - staticDir: "", - render: config.render, + staticDir: config.staticDir + ? parseFileOrUrl(config.staticDir, base) + : join(base, "static"), + render: config.render ?? DEFAULT_RENDER_FN, router: config.router, server: config.server ?? {}, }; @@ -92,20 +99,10 @@ export async function getInternalFreshState( internalConfig.server.signal = config.signal; } - internalConfig.build.outDir = config.build?.outDir - ? parseFileOrUrl(config.build.outDir, base) - : join(base, "_fresh"); - - internalConfig.staticDir = config.staticDir - ? parseFileOrUrl(config.staticDir, base) - : join(base, "static"); - return { config: internalConfig, manifest, - loadSnapshot: typeof config.skipSnapshot === "boolean" - ? !config.skipSnapshot - : false, + loadSnapshot: !isLegacyDev, denoJsonPath, denoJson, }; diff --git a/src/server/context.ts b/src/server/context.ts index 7db94f94..ebcd305c 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -1,42 +1,23 @@ -import { - colors, - extname, - join, - Status, - toFileUrl, - typeByExtension, - walk, -} from "./deps.ts"; -import { ComponentType, h } from "preact"; +import { extname, Status, typeByExtension } from "./deps.ts"; import * as router from "./router.ts"; import { FreshConfig, Manifest } from "./mod.ts"; import { ALIVE_URL, DEV_CLIENT_URL, JS_PREFIX } from "./constants.ts"; -import { BUILD_ID, setBuildId } from "./build_id.ts"; -import DefaultErrorHandler from "./default_error_page.tsx"; +import { BUILD_ID } from "./build_id.ts"; + import { - AppModule, ErrorPage, - ErrorPageModule, Handler, InternalFreshState, Island, - LayoutModule, - LayoutRoute, - MiddlewareHandler, - MiddlewareModule, - MiddlewareRoute, Plugin, RenderFunction, RenderOptions, Route, - RouteModule, - RouterOptions, RouterState, ServeHandlerInfo, UnknownPage, - UnknownPageModule, } from "./types.ts"; -import { DEFAULT_RENDER_FN, render as internalRender } from "./render.ts"; +import { render as internalRender } from "./render.ts"; import { ContentSecurityPolicy, ContentSecurityPolicyDirectives, @@ -44,10 +25,8 @@ import { } from "../runtime/csp.ts"; import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts"; import { - AotSnapshot, Builder, BuildSnapshot, - BuildSnapshotJson, EsbuildBuilder, JSXConfig, } from "../build/mod.ts"; @@ -56,78 +35,34 @@ import { getCodeFrame } from "./code_frame.ts"; import { getInternalFreshState } from "./config.ts"; import { composeMiddlewares, + ROOT_BASE_ROUTE, selectSharedRoutes, toBaseRoute, } from "./compose.ts"; +import { extractRoutes, FsExtractResult } from "./fs_extract.ts"; +import { loadAotSnapshot } from "../build/aot_snapshot.ts"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, }; -const ROOT_BASE_ROUTE = toBaseRoute("/"); - -interface StaticFile { - /** The URL to the static file on disk. */ - localUrl: URL; - /** The path to the file as it would be in the incoming request. */ - path: string; - /** The size of the file. */ - size: number; - /** The content-type of the file. */ - contentType: string; - /** Hash of the file contents. */ - etag: string; -} - /** * @deprecated Use {@linkcode FromManifestConfig} instead */ export type FromManifestOptions = FromManifestConfig; export type FromManifestConfig = FreshConfig & { - skipSnapshot?: boolean; dev?: boolean; }; export async function getServerContext(state: InternalFreshState) { - const { manifest, config, denoJson, denoJsonPath: configPath } = state; - // Get the manifest' base URL. - const baseUrl = new URL("./", manifest.baseUrl).href; + const { config, denoJson, denoJsonPath: configPath } = state; // Restore snapshot if available let snapshot: BuildSnapshot | null = null; if (state.loadSnapshot) { - const snapshotDirPath = config.build.outDir; - try { - if ((await Deno.stat(snapshotDirPath)).isDirectory) { - console.log( - `Using snapshot found at ${colors.cyan(snapshotDirPath)}`, - ); - - const snapshotPath = join(snapshotDirPath, "snapshot.json"); - const json = JSON.parse( - await Deno.readTextFile(snapshotPath), - ) as BuildSnapshotJson; - setBuildId(json.build_id); - - const dependencies = new Map( - Object.entries(json.files), - ); - - const files = new Map(); - Object.keys(json.files).forEach((name) => { - const filePath = join(snapshotDirPath, name); - files.set(name, filePath); - }); - - snapshot = new AotSnapshot(files, dependencies); - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - } + snapshot = await loadAotSnapshot(config); } denoJson.compilerOptions ??= {}; @@ -150,232 +85,7 @@ export async function getServerContext(state: InternalFreshState) { jsxImportSource: denoJson.compilerOptions.jsxImportSource, }; - // Extract all routes, and prepare them into the `Page` structure. - const routes: Route[] = []; - const islands: Island[] = []; - const middlewares: MiddlewareRoute[] = []; - let app: AppModule = DEFAULT_APP; - const layouts: LayoutRoute[] = []; - let notFound: UnknownPage = DEFAULT_NOT_FOUND; - let error: ErrorPage = DEFAULT_ERROR; - const allRoutes = [ - ...Object.entries(manifest.routes), - ...(config.plugins ? getMiddlewareRoutesFromPlugins(config.plugins) : []), - ...(config.plugins ? getRoutesFromPlugins(config.plugins) : []), - ]; - - // Presort all routes so that we only need to sort once - allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0])); - - for ( - const [self, module] of allRoutes - ) { - const url = new URL(self, baseUrl).href; - if (!url.startsWith(baseUrl + "routes")) { - throw new TypeError("Page is not a child of the basepath."); - } - const path = url.substring(baseUrl.length + "routes".length); - const baseRoute = path.substring(1, path.length - extname(path).length); - const name = baseRoute.replace("/", "-"); - const isLayout = path.endsWith("/_layout.tsx") || - path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") || - path.endsWith("/_layout.js"); - const isMiddleware = path.endsWith("/_middleware.tsx") || - path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") || - path.endsWith("/_middleware.js"); - if ( - !path.startsWith("/_") && !isLayout && !isMiddleware - ) { - const { default: component, config } = module as RouteModule; - let pattern = pathToPattern(baseRoute); - if (config?.routeOverride) { - pattern = String(config.routeOverride); - } - let { handler } = module as RouteModule; - if (!handler && "handlers" in module) { - throw new Error( - `Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`, - ); - } - handler ??= {}; - if ( - component && typeof handler === "object" && handler.GET === undefined - ) { - handler.GET = (_req, { render }) => render(); - } - if ( - typeof handler === "object" && handler.GET !== undefined && - handler.HEAD === undefined - ) { - const GET = handler.GET; - handler.HEAD = async (req, ctx) => { - const resp = await GET(req, ctx); - resp.body?.cancel(); - return new Response(null, { - headers: resp.headers, - status: resp.status, - statusText: resp.statusText, - }); - }; - } - const route: Route = { - baseRoute: toBaseRoute(baseRoute), - pattern, - url, - name, - component, - handler, - csp: Boolean(config?.csp ?? false), - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }; - routes.push(route); - } else if (isMiddleware) { - middlewares.push({ - baseRoute: toBaseRoute(baseRoute), - module: module as MiddlewareModule, - }); - } else if ( - path === "/_app.tsx" || path === "/_app.ts" || - path === "/_app.jsx" || path === "/_app.js" - ) { - app = module as AppModule; - } else if (isLayout) { - const mod = module as LayoutModule; - const config = mod.config; - layouts.push({ - baseRoute: toBaseRoute(baseRoute), - handler: mod.handler, - component: mod.default, - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }); - } else if ( - path === "/_404.tsx" || path === "/_404.ts" || - path === "/_404.jsx" || path === "/_404.js" - ) { - const { default: component, config } = module as UnknownPageModule; - let { handler } = module as UnknownPageModule; - if (component && handler === undefined) { - handler = (_req, { render }) => render(); - } - - notFound = { - baseRoute: ROOT_BASE_ROUTE, - pattern: pathToPattern(baseRoute), - url, - name, - component, - handler: handler ?? ((req) => router.defaultOtherHandler(req)), - csp: Boolean(config?.csp ?? false), - appWrapper: !config?.skipAppWrapper, - inheritLayouts: !config?.skipInheritedLayouts, - }; - } else if ( - path === "/_500.tsx" || path === "/_500.ts" || - path === "/_500.jsx" || path === "/_500.js" - ) { - const { default: component, config: routeConfig } = - module as ErrorPageModule; - let { handler } = module as ErrorPageModule; - if (component && handler === undefined) { - handler = (_req, { render }) => render(); - } - - error = { - baseRoute: toBaseRoute("/"), - pattern: pathToPattern(baseRoute), - url, - name, - component, - handler: (req, ctx) => { - if (config.dev) { - const prevComp = error.component; - error.component = DefaultErrorHandler; - try { - return ctx.render(); - } finally { - error.component = prevComp; - } - } - - return handler - ? handler(req, ctx) - : router.defaultErrorHandler(req, ctx, ctx.error); - }, - csp: Boolean(routeConfig?.csp ?? false), - appWrapper: !routeConfig?.skipAppWrapper, - inheritLayouts: !routeConfig?.skipInheritedLayouts, - }; - } - } - - for (const [self, module] of Object.entries(manifest.islands)) { - const url = new URL(self, baseUrl).href; - if (!url.startsWith(baseUrl)) { - throw new TypeError("Island is not a child of the basepath."); - } - let path = url.substring(baseUrl.length); - if (path.startsWith("islands")) { - path = path.slice("islands".length + 1); - } - const baseRoute = path.substring(0, path.length - extname(path).length); - - for (const [exportName, exportedFunction] of Object.entries(module)) { - if (typeof exportedFunction !== "function") { - continue; - } - const name = sanitizeIslandName(baseRoute); - const id = `${name}_${exportName}`.toLowerCase(); - islands.push({ - id, - name, - url, - component: exportedFunction, - exportName, - }); - } - } - - const staticFiles: StaticFile[] = []; - try { - const staticDirUrl = toFileUrl(config.staticDir); - const entries = walk(config.staticDir, { - includeFiles: true, - includeDirs: false, - followSymlinks: false, - }); - const encoder = new TextEncoder(); - for await (const entry of entries) { - const localUrl = toFileUrl(entry.path); - const path = localUrl.href.substring(staticDirUrl.href.length); - const stat = await Deno.stat(localUrl); - const contentType = typeByExtension(extname(path)) ?? - "application/octet-stream"; - const etag = await crypto.subtle.digest( - "SHA-1", - encoder.encode(BUILD_ID + path), - ).then((hash) => - Array.from(new Uint8Array(hash)) - .map((byte) => byte.toString(16).padStart(2, "0")) - .join("") - ); - const staticFile: StaticFile = { - localUrl, - path, - size: stat.size, - contentType, - etag, - }; - staticFiles.push(staticFile); - } - } catch (err) { - if (err.cause instanceof Deno.errors.NotFound) { - // Do nothing. - } else { - throw err; - } - } + const extractResult = await extractRoutes(state); if (config.dev) { // Ensure that debugging hooks are set up for SSR rendering @@ -383,79 +93,50 @@ export async function getServerContext(state: InternalFreshState) { } return new ServerContext( - routes, - islands, - staticFiles, - config.render ?? DEFAULT_RENDER_FN, - middlewares, - app, - layouts, - notFound, - error, - config.plugins ?? [], + state, + extractResult, configPath, jsxConfig, - config.dev, - config.router ?? DEFAULT_ROUTER_OPTIONS, - config.build.target, snapshot, ); } export class ServerContext { - #dev: boolean; - #routes: Route[]; - #islands: Island[]; - #staticFiles: StaticFile[]; #renderFn: RenderFunction; - #middlewares: MiddlewareRoute[]; - #app: AppModule; - #layouts: LayoutRoute[]; - #notFound: UnknownPage; - #error: ErrorPage; #plugins: Plugin[]; #builder: Builder | Promise | BuildSnapshot; - #routerOptions: RouterOptions; + #state: InternalFreshState; + #extractResult: FsExtractResult; + #dev: boolean; constructor( - routes: Route[], - islands: Island[], - staticFiles: StaticFile[], - renderfn: RenderFunction, - middlewares: MiddlewareRoute[], - app: AppModule, - layouts: LayoutRoute[], - notFound: UnknownPage, - error: ErrorPage, - plugins: Plugin[], + state: InternalFreshState, + extractResult: FsExtractResult, configPath: string, jsxConfig: JSXConfig, - dev: boolean, - routerOptions: RouterOptions, - target: string | string[], snapshot: BuildSnapshot | null = null, ) { - this.#routes = routes; - this.#islands = islands; - this.#staticFiles = staticFiles; - this.#renderFn = renderfn; - this.#middlewares = middlewares; - this.#app = app; - this.#layouts = layouts; - this.#notFound = notFound; - this.#error = error; - this.#plugins = plugins; + this.#state = state; + this.#extractResult = extractResult; + this.#renderFn = state.config.render; + this.#plugins = state.config.plugins; + + const dev = state.config.dev; this.#dev = dev; + this.#builder = snapshot ?? new EsbuildBuilder({ buildID: BUILD_ID, - entrypoints: collectEntrypoints(this.#dev, this.#islands, this.#plugins), + entrypoints: collectEntrypoints( + dev, + extractResult.islands, + this.#plugins, + ), configPath, - dev: this.#dev, + dev, jsxConfig, - target, + target: state.config.build.target, absoluteWorkingDir: Deno.cwd(), }); - this.#routerOptions = routerOptions; } /** @@ -465,14 +146,6 @@ export class ServerContext { manifest: Manifest, config: FromManifestConfig, ): Promise { - const isLegacyDev = Deno.env.get("__FRSH_LEGACY_DEV") === "true"; - config.dev = isLegacyDev || - Boolean(config.dev); - - if (isLegacyDev) { - config.skipSnapshot = true; - } - const configWithDefaults = await getInternalFreshState( manifest, config, @@ -488,11 +161,11 @@ export class ServerContext { const handlers = this.#handlers(); const inner = router.router(handlers); const withMiddlewares = composeMiddlewares( - this.#middlewares, + this.#extractResult.middlewares, handlers.errorHandler, router.getParamsAndRoute(handlers), ); - const trailingSlashEnabled = this.#routerOptions?.trailingSlash; + const trailingSlashEnabled = this.#state.config.router?.trailingSlash; const isDev = this.#dev; const bundleAssetRoute = this.#bundleAssetRoute(); @@ -605,18 +278,20 @@ export class ServerContext { // - one serving the file at its location without a "cache bursting" mechanism // - one containing the BUILD_ID in the path that can be cached for ( - const { localUrl, path, size, contentType, etag } of this.#staticFiles + const { localUrl, path, size, contentType, etag } of this.#extractResult + .staticFiles ) { const route = sanitizePathToRegex(path); staticRoutes[route] = { baseRoute: toBaseRoute(route), methods: { - "HEAD": this.#staticFileHeadHandler( + "HEAD": this.#staticFileHandler( + localUrl, size, contentType, etag, ), - "GET": this.#staticFileGetHandler( + "GET": this.#staticFileHandler( localUrl, size, contentType, @@ -627,7 +302,7 @@ export class ServerContext { } // Tell renderer about all globally available islands - setAllIslands(this.#islands); + setAllIslands(this.#extractResult.islands); const dependenciesFn = (path: string) => { const snapshot = this.#maybeBuildSnapshot(); @@ -642,7 +317,7 @@ export class ServerContext { data?: Data, error?: unknown, ) => { - const notFound = this.#notFound; + const notFound = this.#extractResult.notFound; if (!notFound.component) { return sendResponse(["Not found.", undefined], { status: Status.NotFound, @@ -652,7 +327,10 @@ export class ServerContext { }); } - const layouts = selectSharedRoutes(ROOT_BASE_ROUTE, this.#layouts); + const layouts = selectSharedRoutes( + ROOT_BASE_ROUTE, + this.#extractResult.layouts, + ); const imports: string[] = []; const resp = await internalRender({ @@ -660,7 +338,7 @@ export class ServerContext { context: ctx, route: notFound, plugins: this.#plugins, - app: this.#app, + app: this.#extractResult.app, layouts, imports, dependenciesFn, @@ -702,7 +380,10 @@ export class ServerContext { if (route.component === undefined) { throw new Error("This page does not have a component to render."); } - const layouts = selectSharedRoutes(route.baseRoute, this.#layouts); + const layouts = selectSharedRoutes( + route.baseRoute, + this.#extractResult.layouts, + ); const resp = await internalRender({ request: req, @@ -714,7 +395,7 @@ export class ServerContext { }, route, plugins: this.#plugins, - app: this.#app, + app: this.#extractResult.app, layouts, imports, dependenciesFn, @@ -741,8 +422,10 @@ export class ServerContext { }; }; - for (const route of this.#routes) { - if (this.#routerOptions.trailingSlash && route.pattern != "/") { + for (const route of this.#extractResult.routes) { + if ( + this.#state.config.router?.trailingSlash && route.pattern != "/" + ) { route.pattern += "/"; } const createRender = genRender(route, Status.OK); @@ -788,7 +471,7 @@ export class ServerContext { req, ctx, ) => - this.#notFound.handler( + this.#extractResult.notFound.handler( req, { ...ctx, @@ -799,7 +482,7 @@ export class ServerContext { ); const errorHandlerRender = genRender( - this.#error, + this.#extractResult.error, Status.InternalServerError, ); const errorHandler: router.ErrorHandler = async ( @@ -822,7 +505,7 @@ export class ServerContext { } console.error(error); - return this.#error.handler( + return this.#extractResult.error.handler( req, { ...ctx, @@ -835,12 +518,13 @@ export class ServerContext { return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler }; } - #staticFileHeadHandler( + #staticFileHandler( + localUrl: URL, size: number, contentType: string, etag: string, ): router.MatchHandler { - return (req: Request) => { + return async (req: Request) => { const url = new URL(req.url); const key = url.searchParams.get(ASSET_CACHE_BUST_KEY); if (key !== null && BUILD_ID !== key) { @@ -864,44 +548,9 @@ export class ServerContext { const ifNoneMatch = req.headers.get("if-none-match"); if (ifNoneMatch === etag || ifNoneMatch === "W/" + etag) { return new Response(null, { status: 304, headers }); - } else { + } else if (req.method === "HEAD") { headers.set("content-length", String(size)); return new Response(null, { status: 200, headers }); - } - }; - } - - #staticFileGetHandler( - localUrl: URL, - size: number, - contentType: string, - etag: string, - ): router.MatchHandler { - return async (req: Request) => { - const url = new URL(req.url); - const key = url.searchParams.get(ASSET_CACHE_BUST_KEY); - if (key !== null && BUILD_ID !== key) { - url.searchParams.delete(ASSET_CACHE_BUST_KEY); - const location = url.pathname + url.search; - return new Response("", { - status: 307, - headers: { - "content-type": "text/plain", - location, - }, - }); - } - const headers = new Headers({ - "content-type": contentType, - etag, - vary: "If-None-Match", - }); - if (key !== null) { - headers.set("Cache-Control", "public, max-age=31536000, immutable"); - } - const ifNoneMatch = req.headers.get("if-none-match"); - if (ifNoneMatch === etag || ifNoneMatch === "W/" + etag) { - return new Response(null, { status: 304, headers }); } else { const file = await Deno.open(localUrl); headers.set("content-length", String(size)); @@ -935,191 +584,6 @@ export class ServerContext { }; } -const DEFAULT_ROUTER_OPTIONS: RouterOptions = { - trailingSlash: false, -}; - -const DEFAULT_APP: AppModule = { - default: ({ Component }: { Component: ComponentType }) => h(Component, {}), -}; - -const DEFAULT_NOT_FOUND: UnknownPage = { - baseRoute: toBaseRoute("/"), - pattern: "", - url: "", - name: "_404", - handler: (req) => router.defaultOtherHandler(req), - csp: false, - appWrapper: true, - inheritLayouts: true, -}; - -const DEFAULT_ERROR: ErrorPage = { - baseRoute: toBaseRoute("/"), - pattern: "", - url: "", - name: "_500", - component: DefaultErrorHandler, - handler: (_req, ctx) => ctx.render(), - csp: false, - appWrapper: true, - inheritLayouts: true, -}; - -const APP_REG = /_app\.[tj]sx?$/; - -/** - * Sort route paths where special Fresh files like `_app`, - * `_layout` and `_middleware` are sorted in front. - */ -export function sortRoutePaths(a: string, b: string) { - // The `_app` route should always be the first - if (APP_REG.test(a)) return -1; - else if (APP_REG.test(b)) return 1; - - let segmentIdx = 0; - const aLen = a.length; - const bLen = b.length; - const maxLen = aLen > bLen ? aLen : bLen; - for (let i = 0; i < maxLen; i++) { - const charA = a.charAt(i); - const charB = b.charAt(i); - const nextA = i + 1 < aLen ? a.charAt(i + 1) : ""; - const nextB = i + 1 < bLen ? b.charAt(i + 1) : ""; - - if (charA === "/" || charB === "/") { - segmentIdx = i; - // If the other path doesn't close the segment - // then we don't need to continue - if (charA !== "/") return -1; - if (charB !== "/") return 1; - continue; - } - - if (i === segmentIdx + 1) { - const scoreA = getRoutePathScore(charA, nextA); - const scoreB = getRoutePathScore(charB, nextB); - if (scoreA === scoreB) continue; - return scoreA > scoreB ? -1 : 1; - } - } - - return 0; -} - -/** - * Assign a score based on the first two characters of a path segment. - * The goal is to sort `_middleware` and `_layout` in front of everything - * and `[` or `[...` last respectively. - */ -function getRoutePathScore(char: string, nextChar: string): number { - if (char === "_") { - if (nextChar === "m") return 4; - return 3; - } else if (char === "[") { - if (nextChar === ".") { - return 0; - } - return 1; - } - return 2; -} - -/** Transform a filesystem URL path to a `path-to-regex` style matcher. */ -export function pathToPattern(path: string): string { - const parts = path.split("/"); - if (parts[parts.length - 1] === "index") { - if (parts.length === 1) { - return "/"; - } - parts.pop(); - } - - let route = ""; - - for (let i = 0; i < parts.length; i++) { - const part = parts[i]; - - // Case: /[...foo].tsx - if (part.startsWith("[...") && part.endsWith("]")) { - route += `/:${part.slice(4, part.length - 1)}*`; - continue; - } - - // Route groups like /foo/(bar) should not be included in URL - // matching. They are transparent and need to be removed here. - // Case: /foo/(bar) -> /foo - // Case: /foo/(bar)/bob -> /foo/bob - // Case: /(foo)/bar -> /bar - if (part.startsWith("(") && part.endsWith(")")) { - continue; - } - - // Disallow neighbouring params like `/[id][bar].tsx` because - // it's ambiguous where the `id` param ends and `bar` begins. - if (part.includes("][")) { - throw new SyntaxError( - `Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`, - ); - } - - // Case: /[[id]].tsx - // Case: /[id].tsx - // Case: /[id]@[bar].tsx - // Case: /[id]-asdf.tsx - // Case: /[id]-asdf[bar].tsx - // Case: /asdf[bar].tsx - let pattern = ""; - let groupOpen = 0; - let optional = false; - for (let j = 0; j < part.length; j++) { - const char = part[j]; - if (char === "[") { - if (part[j + 1] === "[") { - // Disallow optional dynamic params like `foo-[[bar]]` - if (part[j - 1] !== "/" && !!part[j - 1]) { - throw new SyntaxError( - `Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`, - ); - } - groupOpen++; - optional = true; - pattern += "{/"; - j++; - } - pattern += ":"; - groupOpen++; - } else if (char === "]") { - if (part[j + 1] === "]") { - // Disallow optional dynamic params like `[[foo]]-bar` - if (part[j + 2] !== "/" && !!part[j + 2]) { - throw new SyntaxError( - `Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`, - ); - } - groupOpen--; - pattern += "}?"; - j++; - } - if (--groupOpen < 0) { - throw new SyntaxError(`Invalid route pattern: "${path}"`); - } - } else { - pattern += char; - } - } - - route += (optional ? "" : "/") + pattern; - } - - // Case: /(group)/index.tsx - if (route === "") { - route = "/"; - } - - return route; -} - // Normalize a path for use in a URL. Returns null if the path is unparsable. export function normalizeURLPath(path: string): string | null { try { @@ -1143,18 +607,6 @@ function sanitizePathToRegex(path: string): string { .replaceAll("\:", "\\:"); } -function toPascalCase(text: string): string { - return text.replace( - /(^\w|-\w)/g, - (substring) => substring.replace(/-/, "").toUpperCase(), - ); -} - -function sanitizeIslandName(name: string): string { - const fileName = name.replaceAll(/[/\\\\\(\)\[\]]/g, "_"); - return toPascalCase(fileName); -} - function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string { return Object.entries(csp) .filter(([_key, value]) => value !== undefined) @@ -1201,47 +653,6 @@ function collectEntrypoints( return entryPoints; } -function formatMiddlewarePath(path: string): string { - const prefix = !path.startsWith("/") ? "/" : ""; - const suffix = !path.endsWith("/") ? "/" : ""; - return prefix + path + suffix; -} - -function getMiddlewareRoutesFromPlugins( - plugins: Plugin[], -): [string, MiddlewareModule][] { - const middlewares = plugins.flatMap((plugin) => plugin.middlewares ?? []); - - const mws: Record< - string, - [string, { handler: MiddlewareHandler[] }] - > = {}; - for (let i = 0; i < middlewares.length; i++) { - const mw = middlewares[i]; - const handler = mw.middleware.handler; - const key = `./routes${formatMiddlewarePath(mw.path)}_middleware.ts`; - if (!mws[key]) mws[key] = [key, { handler: [] }]; - mws[key][1].handler.push(...Array.isArray(handler) ? handler : [handler]); - } - - return Object.values(mws); -} - -function formatRoutePath(path: string) { - return path.startsWith("/") ? path : "/" + path; -} - -function getRoutesFromPlugins(plugins: Plugin[]): [string, RouteModule][] { - return plugins.flatMap((plugin) => plugin.routes ?? []) - .map((route) => { - return [`./routes${formatRoutePath(route.path)}.ts`, { - // deno-lint-ignore no-explicit-any - default: route.component as any, - handler: route.handler, - }]; - }); -} - function sendResponse( resp: [string, ContentSecurityPolicy | undefined], options: { diff --git a/src/server/fs_extract.ts b/src/server/fs_extract.ts new file mode 100644 index 00000000..3003c82a --- /dev/null +++ b/src/server/fs_extract.ts @@ -0,0 +1,521 @@ +import { ComponentType, h } from "preact"; +import { + AppModule, + ErrorPage, + ErrorPageModule, + InternalFreshState, + Island, + LayoutModule, + LayoutRoute, + MiddlewareHandler, + MiddlewareModule, + MiddlewareRoute, + Plugin, + Route, + RouteModule, + StaticFile, + UnknownPage, + UnknownPageModule, +} from "./types.ts"; +import * as router from "./router.ts"; +import DefaultErrorHandler from "./default_error_page.tsx"; +import { extname, toFileUrl, typeByExtension, walk } from "./deps.ts"; +import { BUILD_ID } from "./build_id.ts"; +import { toBaseRoute } from "./compose.ts"; + +export const ROOT_BASE_ROUTE = toBaseRoute("/"); + +const DEFAULT_APP: AppModule = { + default: ({ Component }: { Component: ComponentType }) => h(Component, {}), +}; + +const DEFAULT_NOT_FOUND: UnknownPage = { + baseRoute: toBaseRoute("/"), + pattern: "", + url: "", + name: "_404", + handler: (req) => router.defaultOtherHandler(req), + csp: false, + appWrapper: true, + inheritLayouts: true, +}; + +const DEFAULT_ERROR: ErrorPage = { + baseRoute: toBaseRoute("/"), + pattern: "", + url: "", + name: "_500", + component: DefaultErrorHandler, + handler: (_req, ctx) => ctx.render(), + csp: false, + appWrapper: true, + inheritLayouts: true, +}; + +export interface FsExtractResult { + app: AppModule; + layouts: LayoutRoute[]; + notFound: UnknownPage; + error: ErrorPage; + middlewares: MiddlewareRoute[]; + islands: Island[]; + routes: Route[]; + staticFiles: StaticFile[]; +} + +/** + * Extract all routes, and prepare them into the `Page` structure. + */ +export async function extractRoutes( + state: InternalFreshState, +): Promise { + const { config, manifest } = state; + + // Get the manifest' base URL. + const baseUrl = new URL("./", manifest.baseUrl).href; + + const routes: Route[] = []; + const islands: Island[] = []; + const middlewares: MiddlewareRoute[] = []; + let app: AppModule = DEFAULT_APP; + const layouts: LayoutRoute[] = []; + let notFound: UnknownPage = DEFAULT_NOT_FOUND; + let error: ErrorPage = DEFAULT_ERROR; + const allRoutes = [ + ...Object.entries(manifest.routes), + ...(config.plugins ? getMiddlewareRoutesFromPlugins(config.plugins) : []), + ...(config.plugins ? getRoutesFromPlugins(config.plugins) : []), + ]; + + // Presort all routes so that we only need to sort once + allRoutes.sort((a, b) => sortRoutePaths(a[0], b[0])); + + for ( + const [self, module] of allRoutes + ) { + const url = new URL(self, baseUrl).href; + if (!url.startsWith(baseUrl + "routes")) { + throw new TypeError("Page is not a child of the basepath."); + } + const path = url.substring(baseUrl.length + "routes".length); + const baseRoute = path.substring(1, path.length - extname(path).length); + const name = baseRoute.replace("/", "-"); + const isLayout = path.endsWith("/_layout.tsx") || + path.endsWith("/_layout.ts") || path.endsWith("/_layout.jsx") || + path.endsWith("/_layout.js"); + const isMiddleware = path.endsWith("/_middleware.tsx") || + path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") || + path.endsWith("/_middleware.js"); + if ( + !path.startsWith("/_") && !isLayout && !isMiddleware + ) { + const { default: component, config } = module as RouteModule; + let pattern = pathToPattern(baseRoute); + if (config?.routeOverride) { + pattern = String(config.routeOverride); + } + let { handler } = module as RouteModule; + if (!handler && "handlers" in module) { + throw new Error( + `Found named export "handlers" in ${self} instead of "handler". Did you mean "handler"?`, + ); + } + handler ??= {}; + if ( + component && typeof handler === "object" && handler.GET === undefined + ) { + handler.GET = (_req, { render }) => render(); + } + if ( + typeof handler === "object" && handler.GET !== undefined && + handler.HEAD === undefined + ) { + const GET = handler.GET; + handler.HEAD = async (req, ctx) => { + const resp = await GET(req, ctx); + resp.body?.cancel(); + return new Response(null, { + headers: resp.headers, + status: resp.status, + statusText: resp.statusText, + }); + }; + } + const route: Route = { + baseRoute: toBaseRoute(baseRoute), + pattern, + url, + name, + component, + handler, + csp: Boolean(config?.csp ?? false), + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }; + routes.push(route); + } else if (isMiddleware) { + middlewares.push({ + baseRoute: toBaseRoute(baseRoute), + module: module as MiddlewareModule, + }); + } else if ( + path === "/_app.tsx" || path === "/_app.ts" || + path === "/_app.jsx" || path === "/_app.js" + ) { + app = module as AppModule; + } else if (isLayout) { + const mod = module as LayoutModule; + const config = mod.config; + layouts.push({ + baseRoute: toBaseRoute(baseRoute), + handler: mod.handler, + component: mod.default, + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }); + } else if ( + path === "/_404.tsx" || path === "/_404.ts" || + path === "/_404.jsx" || path === "/_404.js" + ) { + const { default: component, config } = module as UnknownPageModule; + let { handler } = module as UnknownPageModule; + if (component && handler === undefined) { + handler = (_req, { render }) => render(); + } + + notFound = { + baseRoute: ROOT_BASE_ROUTE, + pattern: pathToPattern(baseRoute), + url, + name, + component, + handler: handler ?? ((req) => router.defaultOtherHandler(req)), + csp: Boolean(config?.csp ?? false), + appWrapper: !config?.skipAppWrapper, + inheritLayouts: !config?.skipInheritedLayouts, + }; + } else if ( + path === "/_500.tsx" || path === "/_500.ts" || + path === "/_500.jsx" || path === "/_500.js" + ) { + const { default: component, config: routeConfig } = + module as ErrorPageModule; + let { handler } = module as ErrorPageModule; + if (component && handler === undefined) { + handler = (_req, { render }) => render(); + } + + error = { + baseRoute: toBaseRoute("/"), + pattern: pathToPattern(baseRoute), + url, + name, + component, + handler: (req, ctx) => { + if (config.dev) { + const prevComp = error.component; + error.component = DefaultErrorHandler; + try { + return ctx.render(); + } finally { + error.component = prevComp; + } + } + + return handler + ? handler(req, ctx) + : router.defaultErrorHandler(req, ctx, ctx.error); + }, + csp: Boolean(routeConfig?.csp ?? false), + appWrapper: !routeConfig?.skipAppWrapper, + inheritLayouts: !routeConfig?.skipInheritedLayouts, + }; + } + } + + for (const [self, module] of Object.entries(manifest.islands)) { + const url = new URL(self, baseUrl).href; + if (!url.startsWith(baseUrl)) { + throw new TypeError("Island is not a child of the basepath."); + } + let path = url.substring(baseUrl.length); + if (path.startsWith("islands")) { + path = path.slice("islands".length + 1); + } + const baseRoute = path.substring(0, path.length - extname(path).length); + + for (const [exportName, exportedFunction] of Object.entries(module)) { + if (typeof exportedFunction !== "function") { + continue; + } + const name = sanitizeIslandName(baseRoute); + const id = `${name}_${exportName}`.toLowerCase(); + islands.push({ + id, + name, + url, + component: exportedFunction, + exportName, + }); + } + } + + const staticFiles: StaticFile[] = []; + try { + const staticDirUrl = toFileUrl(config.staticDir); + const entries = walk(config.staticDir, { + includeFiles: true, + includeDirs: false, + followSymlinks: false, + }); + const encoder = new TextEncoder(); + for await (const entry of entries) { + const localUrl = toFileUrl(entry.path); + const path = localUrl.href.substring(staticDirUrl.href.length); + const stat = await Deno.stat(localUrl); + const contentType = typeByExtension(extname(path)) ?? + "application/octet-stream"; + const etag = await crypto.subtle.digest( + "SHA-1", + encoder.encode(BUILD_ID + path), + ).then((hash) => + Array.from(new Uint8Array(hash)) + .map((byte) => byte.toString(16).padStart(2, "0")) + .join("") + ); + const staticFile: StaticFile = { + localUrl, + path, + size: stat.size, + contentType, + etag, + }; + staticFiles.push(staticFile); + } + } catch (err) { + if (err.cause instanceof Deno.errors.NotFound) { + // Do nothing. + } else { + throw err; + } + } + + return { + app, + error, + islands, + layouts, + middlewares, + notFound, + routes, + staticFiles, + }; +} + +const APP_REG = /_app\.[tj]sx?$/; + +/** + * Sort route paths where special Fresh files like `_app`, + * `_layout` and `_middleware` are sorted in front. + */ +export function sortRoutePaths(a: string, b: string) { + // The `_app` route should always be the first + if (APP_REG.test(a)) return -1; + else if (APP_REG.test(b)) return 1; + + let segmentIdx = 0; + const aLen = a.length; + const bLen = b.length; + const maxLen = aLen > bLen ? aLen : bLen; + for (let i = 0; i < maxLen; i++) { + const charA = a.charAt(i); + const charB = b.charAt(i); + const nextA = i + 1 < aLen ? a.charAt(i + 1) : ""; + const nextB = i + 1 < bLen ? b.charAt(i + 1) : ""; + + if (charA === "/" || charB === "/") { + segmentIdx = i; + // If the other path doesn't close the segment + // then we don't need to continue + if (charA !== "/") return -1; + if (charB !== "/") return 1; + continue; + } + + if (i === segmentIdx + 1) { + const scoreA = getRoutePathScore(charA, nextA); + const scoreB = getRoutePathScore(charB, nextB); + if (scoreA === scoreB) continue; + return scoreA > scoreB ? -1 : 1; + } + } + + return 0; +} + +/** + * Assign a score based on the first two characters of a path segment. + * The goal is to sort `_middleware` and `_layout` in front of everything + * and `[` or `[...` last respectively. + */ +function getRoutePathScore(char: string, nextChar: string): number { + if (char === "_") { + if (nextChar === "m") return 4; + return 3; + } else if (char === "[") { + if (nextChar === ".") { + return 0; + } + return 1; + } + return 2; +} + +/** + * Transform a filesystem URL path to a `path-to-regex` style matcher. */ +export function pathToPattern(path: string): string { + const parts = path.split("/"); + if (parts[parts.length - 1] === "index") { + if (parts.length === 1) { + return "/"; + } + parts.pop(); + } + + let route = ""; + + for (let i = 0; i < parts.length; i++) { + const part = parts[i]; + + // Case: /[...foo].tsx + if (part.startsWith("[...") && part.endsWith("]")) { + route += `/:${part.slice(4, part.length - 1)}*`; + continue; + } + + // Route groups like /foo/(bar) should not be included in URL + // matching. They are transparent and need to be removed here. + // Case: /foo/(bar) -> /foo + // Case: /foo/(bar)/bob -> /foo/bob + // Case: /(foo)/bar -> /bar + if (part.startsWith("(") && part.endsWith(")")) { + continue; + } + + // Disallow neighbouring params like `/[id][bar].tsx` because + // it's ambiguous where the `id` param ends and `bar` begins. + if (part.includes("][")) { + throw new SyntaxError( + `Invalid route pattern: "${path}". A parameter cannot be followed by another parameter without any characters in between.`, + ); + } + + // Case: /[[id]].tsx + // Case: /[id].tsx + // Case: /[id]@[bar].tsx + // Case: /[id]-asdf.tsx + // Case: /[id]-asdf[bar].tsx + // Case: /asdf[bar].tsx + let pattern = ""; + let groupOpen = 0; + let optional = false; + for (let j = 0; j < part.length; j++) { + const char = part[j]; + if (char === "[") { + if (part[j + 1] === "[") { + // Disallow optional dynamic params like `foo-[[bar]]` + if (part[j - 1] !== "/" && !!part[j - 1]) { + throw new SyntaxError( + `Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`, + ); + } + groupOpen++; + optional = true; + pattern += "{/"; + j++; + } + pattern += ":"; + groupOpen++; + } else if (char === "]") { + if (part[j + 1] === "]") { + // Disallow optional dynamic params like `[[foo]]-bar` + if (part[j + 2] !== "/" && !!part[j + 2]) { + throw new SyntaxError( + `Invalid route pattern: "${path}". An optional parameter needs to be a full segment.`, + ); + } + groupOpen--; + pattern += "}?"; + j++; + } + if (--groupOpen < 0) { + throw new SyntaxError(`Invalid route pattern: "${path}"`); + } + } else { + pattern += char; + } + } + + route += (optional ? "" : "/") + pattern; + } + + // Case: /(group)/index.tsx + if (route === "") { + route = "/"; + } + + return route; +} + +function toPascalCase(text: string): string { + return text.replace( + /(^\w|-\w)/g, + (substring) => substring.replace(/-/, "").toUpperCase(), + ); +} + +function sanitizeIslandName(name: string): string { + const fileName = name.replaceAll(/[/\\\\\(\)\[\]]/g, "_"); + return toPascalCase(fileName); +} + +function formatMiddlewarePath(path: string): string { + const prefix = !path.startsWith("/") ? "/" : ""; + const suffix = !path.endsWith("/") ? "/" : ""; + return prefix + path + suffix; +} + +function getMiddlewareRoutesFromPlugins( + plugins: Plugin[], +): [string, MiddlewareModule][] { + const middlewares = plugins.flatMap((plugin) => plugin.middlewares ?? []); + + const mws: Record< + string, + [string, { handler: MiddlewareHandler[] }] + > = {}; + for (let i = 0; i < middlewares.length; i++) { + const mw = middlewares[i]; + const handler = mw.middleware.handler; + const key = `./routes${formatMiddlewarePath(mw.path)}_middleware.ts`; + if (!mws[key]) mws[key] = [key, { handler: [] }]; + mws[key][1].handler.push(...Array.isArray(handler) ? handler : [handler]); + } + + return Object.values(mws); +} + +function formatRoutePath(path: string) { + return path.startsWith("/") ? path : "/" + path; +} + +function getRoutesFromPlugins(plugins: Plugin[]): [string, RouteModule][] { + return plugins.flatMap((plugin) => plugin.routes ?? []) + .map((route) => { + return [`./routes${formatRoutePath(route.path)}.ts`, { + // deno-lint-ignore no-explicit-any + default: route.component as any, + handler: route.handler, + }]; + }); +} diff --git a/src/server/context_test.ts b/src/server/fs_extract_test.ts similarity index 72% rename from src/server/context_test.ts rename to src/server/fs_extract_test.ts index 417b48f9..6127e5f6 100644 --- a/src/server/context_test.ts +++ b/src/server/fs_extract_test.ts @@ -1,5 +1,5 @@ import { assertEquals, assertThrows } from "$std/testing/asserts.ts"; -import { pathToPattern } from "./context.ts"; +import { pathToPattern, sortRoutePaths } from "./fs_extract.ts"; Deno.test("pathToPattern", async (t) => { await t.step("creates pattern", () => { @@ -46,3 +46,34 @@ Deno.test("pathToPattern", async (t) => { assertThrows(() => pathToPattern("foo/[[name]]-bar")); }); }); + +Deno.test("sortRoutePaths", () => { + const routes = [ + "/foo/[id]", + "/foo/[...slug]", + "/foo/bar", + "/foo/_layout", + "/foo/index", + "/foo/_middleware", + "/foo/bar/_middleware", + "/foo/bar/index", + "/foo/bar/[...foo]", + "/foo/bar/baz", + "/foo/bar/_layout", + ]; + const sorted = [ + "/foo/_middleware", + "/foo/_layout", + "/foo/bar", + "/foo/index", + "/foo/bar/_middleware", + "/foo/bar/_layout", + "/foo/bar/index", + "/foo/bar/baz", + "/foo/bar/[...foo]", + "/foo/[id]", + "/foo/[...slug]", + ]; + routes.sort(sortRoutePaths); + assertEquals(routes, sorted); +}); diff --git a/src/server/mod.ts b/src/server/mod.ts index 9dbee912..456cf257 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -103,7 +103,6 @@ export async function createHandler( export async function start(manifest: Manifest, config: FreshConfig = {}) { const ctx = await ServerContext.fromManifest(manifest, { ...config, - skipSnapshot: false, dev: false, }); await startServer(ctx.handler(), config.server ?? config); diff --git a/src/server/route_sorting_test.ts b/src/server/route_sorting_test.ts deleted file mode 100644 index 69a73afa..00000000 --- a/src/server/route_sorting_test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { assertEquals } from "../../tests/deps.ts"; -import { sortRoutePaths } from "./context.ts"; - -Deno.test("sortRoutePaths", () => { - const routes = [ - "/foo/[id]", - "/foo/[...slug]", - "/foo/bar", - "/foo/_layout", - "/foo/index", - "/foo/_middleware", - "/foo/bar/_middleware", - "/foo/bar/index", - "/foo/bar/[...foo]", - "/foo/bar/baz", - "/foo/bar/_layout", - ]; - const sorted = [ - "/foo/_middleware", - "/foo/_layout", - "/foo/bar", - "/foo/index", - "/foo/bar/_middleware", - "/foo/bar/_layout", - "/foo/bar/index", - "/foo/bar/baz", - "/foo/bar/[...foo]", - "/foo/[id]", - "/foo/[...slug]", - ]; - routes.sort(sortRoutePaths); - assertEquals(routes, sorted); -}); diff --git a/src/server/types.ts b/src/server/types.ts index 06624963..e54019e2 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -122,7 +122,7 @@ export interface ResolvedFreshConfig { outDir: string; target: string | string[]; }; - render?: RenderFunction; + render: RenderFunction; plugins: Plugin[]; staticDir: string; router?: RouterOptions; @@ -180,6 +180,19 @@ export interface PageProps> { state: S; } +export interface StaticFile { + /** The URL to the static file on disk. */ + localUrl: URL; + /** The path to the file as it would be in the incoming request. */ + path: string; + /** The size of the file. */ + size: number; + /** The content-type of the file. */ + contentType: string; + /** Hash of the file contents. */ + etag: string; +} + /** * Context passed to async route components. */