@torpor/build 1.4.6 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/{Site-CQ29Opvm.d.mts → Site-Blz32JRD.d.mts} +4 -3
- package/dist/{Site-CQ29Opvm.d.mts.map → Site-Blz32JRD.d.mts.map} +1 -1
- package/dist/bin/index.js +1 -1
- package/dist/clientEntry.mjs +4 -4
- package/dist/clientEntry.mjs.map +1 -1
- package/dist/dataRequest-JosDB_ig.mjs +50 -0
- package/dist/dataRequest-JosDB_ig.mjs.map +1 -0
- package/dist/dev.mjs +1 -1
- package/dist/devPlugin-V689J6l6.mjs +144 -0
- package/dist/devPlugin-V689J6l6.mjs.map +1 -0
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +3 -2
- package/dist/index.mjs.map +1 -1
- package/dist/load-LWQoFWh-.mjs +349 -0
- package/dist/load-LWQoFWh-.mjs.map +1 -0
- package/dist/nav.mjs +1 -1
- package/dist/nodeDev.d.mts +16 -0
- package/dist/nodeDev.d.mts.map +1 -0
- package/dist/nodeDev.mjs +2 -0
- package/dist/openapi.d.mts +1 -1
- package/dist/{response-CuNPcxsY.mjs → response-sth6FQsj.mjs} +33 -3
- package/dist/response-sth6FQsj.mjs.map +1 -0
- package/dist/response.mjs +2 -2
- package/dist/run.d.mts +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runOpenApi-CbbrPi4E.mjs → runOpenApi-tnflDjZV.mjs} +10 -143
- package/dist/runOpenApi-tnflDjZV.mjs.map +1 -0
- package/dist/serverEntry-fj0XfTs4.d.mts.map +1 -1
- package/dist/{serverEntry-D3uwudkX.mjs → serverEntry-o6kk_-Wo.mjs} +2 -2
- package/dist/{serverEntry-D3uwudkX.mjs.map → serverEntry-o6kk_-Wo.mjs.map} +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-C8qzOSX-.mjs → serverHandlers-F1gJ1lrj.mjs} +194 -30
- package/dist/serverHandlers-F1gJ1lrj.mjs.map +1 -0
- package/dist/test.d.mts +1 -1
- package/dist/test.mjs +1 -1
- package/dist/{unprocessable-D6RcYLh6.mjs → unprocessable-CoMN2zFa.mjs} +2 -32
- package/dist/unprocessable-CoMN2zFa.mjs.map +1 -0
- package/package.json +8 -3
- package/dist/load-Uyj9I60p.mjs +0 -246
- package/dist/load-Uyj9I60p.mjs.map +0 -1
- package/dist/response-CuNPcxsY.mjs.map +0 -1
- package/dist/runOpenApi-CbbrPi4E.mjs.map +0 -1
- package/dist/serverHandlers-C8qzOSX-.mjs.map +0 -1
- package/dist/unprocessable-D6RcYLh6.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runOpenApi-CbbrPi4E.mjs","names":["path","path","path","path","path","dependencyNames","path","path","fs","path","fs","asAliasArray","path","fs","path","path","path","createViteServer","path","fs","path","createViteServer","path"],"sources":["../src/utils/tsconfigAliases.ts","../src/site/checkRoutes.ts","../src/site/checkLayoutSlots.ts","../src/site/manifest.ts","../src/utils/torporPackages.ts","../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/runPrerender.ts","../src/run/runBuild.ts","../src/run/devPlugin.ts","../src/run/depCache.ts","../src/run/staleTorpCopies.ts","../src/run/runDev.ts","../src/server/contentType.ts","../src/run/runPreview.ts","../src/run/run.ts","../src/run/runOpenApi.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface AliasEntry {\n\tfind: string | RegExp;\n\treplacement: string;\n}\n\n/**\n * Reads `tsconfig.json` `compilerOptions.paths` (relative to `baseUrl`,\n * defaulting to the tsconfig directory) and converts them to Vite\n * `resolve.alias` entries. Only handles paths declared in the root tsconfig\n * (not inherited via `extends`).\n */\nexport default function tsconfigAliases(root: string): AliasEntry[] {\n\tconst file = path.join(root, \"tsconfig.json\");\n\tlet paths: Record<string, string[]> | undefined;\n\tlet baseUrl: string;\n\ttry {\n\t\tconst tsconfig = JSON.parse(stripJsonc(readFileSync(file, \"utf-8\")));\n\t\tconst compilerOptions = tsconfig.compilerOptions ?? {};\n\t\tbaseUrl = compilerOptions.baseUrl ? path.resolve(root, compilerOptions.baseUrl) : root;\n\t\tpaths = compilerOptions.paths;\n\t} catch {\n\t\treturn [];\n\t}\n\tif (!paths) return [];\n\n\tconst aliases: AliasEntry[] = [];\n\tfor (const [pattern, targets] of Object.entries(paths)) {\n\t\tconst target = targets?.[0];\n\t\tif (!target) continue;\n\t\tif (pattern.endsWith(\"*\")) {\n\t\t\t// `@/*` -> `./src/*`: match the literal prefix (`@/`) and rewrite to\n\t\t\t// the target dir. A string `find` is used (not a RegExp) because\n\t\t\t// Vite applies prefix-string aliases during SSR transform, which is\n\t\t\t// what makes path aliases resolve in the SSR module runner.\n\t\t\tconst find = pattern.slice(0, -1);\n\t\t\tconst targetDir = target.slice(0, -1);\n\t\t\taliases.push({\n\t\t\t\tfind,\n\t\t\t\treplacement: `${path.resolve(baseUrl, targetDir)}/`,\n\t\t\t});\n\t\t} else {\n\t\t\taliases.push({ find: pattern, replacement: path.resolve(baseUrl, target) });\n\t\t}\n\t}\n\treturn aliases;\n}\n\n/**\n * Strips JSONC comments and trailing commas so `tsconfig.json` (which permits\n * both) can be parsed with `JSON.parse`. String contents are preserved.\n */\nexport function stripJsonc(text: string): string {\n\tlet out = \"\";\n\tfor (let i = 0; i < text.length;) {\n\t\tconst c = text[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tout += c;\n\t\t\ti++;\n\t\t\twhile (i < text.length) {\n\t\t\t\tif (text[i] === \"\\\\\") {\n\t\t\t\t\tout += text[i] + (text[i + 1] ?? \"\");\n\t\t\t\t\ti += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst cc = text[i++];\n\t\t\t\tout += cc;\n\t\t\t\tif (cc === quote) break;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"/\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && text[i] !== \"\\n\") i++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"*\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && !(text[i] === \"*\" && text[i + 1] === \"/\")) i++;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tout += c;\n\t\ti++;\n\t}\n\treturn out.replace(/,(\\s*[}\\]])/g, \"$1\");\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type Route from \"../types/Route\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport type Site from \"./Site\";\n\n/**\n * A problem found in a route file's type annotations by `checkRoutes`.\n */\nexport interface RouteCheckIssue {\n\t/** The route file, relative to the site root */\n\tfile: string;\n\t/** 1-based line number of the annotation */\n\tline: number;\n\tseverity: \"error\" | \"warning\";\n\tmessage: string;\n}\n\nconst ENDPOINT_TYPES = [\"PageServerEndPoint\", \"PageEndPoint\", \"ServerEndPoint\", \"ServerHook\"];\n\nconst USAGE_RE = new RegExp(`\\\\b(satisfies|as|:)\\\\s*\\\\b(${ENDPOINT_TYPES.join(\"|\")})\\\\b`, \"g\");\n\nconst TYPE_NAME_RE = new RegExp(`^(?:${ENDPOINT_TYPES.join(\"|\")})\\\\b`);\n\n/**\n * Checks the route files of a site against their type annotations:\n *\n * - Route path annotations (e.g. `PageServerEndPoint<\"/posts/[id]\">`) must\n * match the route derived from the file's location, so types can't silently\n * lie when files move\n * - Exports that widen the endpoint type (`satisfies T as T`, `as T`, or a\n * variable annotation) are flagged, because they destroy `PageData` /\n * `PageForm` / param inference\n * - Routes with dynamic params but no route annotation are flagged, because\n * their params are loosely typed\n *\n * Only `.ts` route files are checked; annotations are matched by the standard\n * type names (renamed imports are not detected). Best-effort, source-level —\n * comments mentioning these patterns may produce false positives.\n */\nexport function checkRoutes(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tissues.push(...checkRoute(site, route));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single route's file. Returns no issues for routes without a `.ts`\n * file (`.torp` components, inline endpoints, `.js` files).\n */\nexport function checkRoute(site: Site, route: Route): RouteCheckIssue[] {\n\tif (!route.file || !route.file.endsWith(\".ts\")) return [];\n\tlet source: string;\n\ttry {\n\t\tsource = readFileSync(path.join(site.root, route.file), \"utf8\");\n\t} catch {\n\t\treturn [];\n\t}\n\treturn checkRouteSource(source, route.file, expectedAnnotationPath(route), typeNameFor(route));\n}\n\n/**\n * Checks a single route file's source. Exported for reuse (e.g. re-checking a\n * changed file during dev).\n * @param source The route file's source code\n * @param file The file path, relative to the site root (used in messages)\n * @param expected The route path derived from the file's location\n * @param typeName The endpoint type name conventionally used by this route\n * type (used in suggestions)\n */\nexport function checkRouteSource(\n\tsource: string,\n\tfile: string,\n\texpected: string,\n\ttypeName: string,\n): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tlet sawAnnotation = false;\n\tUSAGE_RE.lastIndex = 0;\n\tfor (let m = USAGE_RE.exec(source); m; m = USAGE_RE.exec(source)) {\n\t\tsawAnnotation = true;\n\t\tconst kind = m[1];\n\t\tconst usedTypeName = m[2];\n\t\tconst { routePath, end } = parseTypeArgs(source, m.index + m[0].length);\n\t\tconst line = lineOf(source, m.index);\n\t\tif (routePath !== undefined && routePath !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `Route annotation \"${routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t});\n\t\t}\n\t\tif (kind === \"as\" || kind === \":\") {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tmessage:\n\t\t\t\t\tkind === \"as\"\n\t\t\t\t\t\t? `The \\`as ${usedTypeName}\\` cast widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` without a cast instead.`\n\t\t\t\t\t\t: `The variable annotation widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` on the default export instead.`,\n\t\t\t});\n\t\t} else {\n\t\t\tconst cast = parseAsCast(source, end);\n\t\t\tif (cast) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `The \\`as\\` cast after \\`satisfies\\` widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath ?? cast.routePath)}\\` on its own.`,\n\t\t\t\t});\n\t\t\t\tif (cast.routePath !== undefined && cast.routePath !== expected) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tmessage: `Route annotation \"${cast.routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t// Skip the `as T` so it isn't reported again as a separate cast\n\t\t\t\tUSAGE_RE.lastIndex = cast.end;\n\t\t\t} else if (routePath === undefined && expected.includes(\"[\")) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `No route path on the annotation, so params are loosely typed. Use \\`satisfies ${usedTypeName}<\"${expected}\">\\`.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tif (!sawAnnotation && file.endsWith(\".ts\") && expected.includes(\"[\")) {\n\t\tissues.push({\n\t\t\tfile,\n\t\t\tline: 1,\n\t\t\tseverity: \"warning\",\n\t\t\tmessage: `No route annotation, so params are loosely typed. Add \\`satisfies ${typeName}<\"${expected}\">\\` to the default export.`,\n\t\t});\n\t}\n\treturn issues;\n}\n\n/**\n * Prints issues to the console and returns the number of errors.\n */\nexport function reportRouteIssues(issues: RouteCheckIssue[]): number {\n\tfor (const issue of issues) {\n\t\tconsole.error(`[torpor] ${issue.severity}: ${issue.file}:${issue.line} ${issue.message}`);\n\t}\n\treturn issues.filter((i) => i.severity === \"error\").length;\n}\n\nconst MAKE_API_RE = /\\bmakeApi\\s*<\\s*([\"'])([^\"']+)\\1\\s*,\\s*typeof\\s+([A-Za-z_$][\\w$]*)/g;\n\nconst DEFAULT_IMPORT_RE = /\\bimport\\s+(?:type\\s+)?([A-Za-z_$][\\w$]*)\\s+from\\s*([\"'])([^\"']+)\\2/g;\n\nconst SKIP_DIRS = new Set([\"node_modules\", \"dist\", \".git\", \".torpor\", \".vite\", \"coverage\"]);\n\nconst SOURCE_FILE_RE = /\\.(ts|js|torp)$/;\n\n/**\n * Precomputed state for checking `makeApi` calls: the site root, its route\n * files keyed by path, and tsconfig path aliases for resolving imports.\n */\nexport interface ApiCallCheck {\n\troot: string;\n\troutesByFile: Map<string, Route>;\n\taliases: AliasEntry[];\n}\n\n/**\n * Creates the shared state used by `checkApiCallSource`, so per-file checks\n * (e.g. re-checking a changed file during dev) don't rebuild it.\n */\nexport function createApiCallCheck(site: Site): ApiCallCheck {\n\tconst routesByFile = new Map<string, Route>();\n\tfor (const route of site.routes) {\n\t\tif (route.file) routesByFile.set(route.file.replaceAll(\"\\\\\", \"/\"), route);\n\t}\n\treturn { root: site.root, routesByFile, aliases: tsconfigAliases(site.root) };\n}\n\n/**\n * Checks `makeApi<Route, typeof endpoint>` calls across the site's source\n * files: the `Route` argument must match the route derived from the imported\n * endpoint file's location. Calls whose endpoint isn't a type-only import of\n * a known route file are skipped.\n */\nexport function checkApiCalls(site: Site): RouteCheckIssue[] {\n\tconst check = createApiCallCheck(site);\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const file of walkSourceFiles(site.root)) {\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tissues.push(...checkApiCallSource(source, file, check));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks the `makeApi` calls in a single file's source.\n * @param source The file's source code\n * @param file The file's absolute path (used to resolve relative imports and\n * to derive the path shown in messages)\n * @param check Shared state from `createApiCallCheck`\n */\nexport function checkApiCallSource(\n\tsource: string,\n\tfile: string,\n\tcheck: ApiCallCheck,\n): RouteCheckIssue[] {\n\tconst imports = new Map<string, string>();\n\tfor (let m = DEFAULT_IMPORT_RE.exec(source); m; m = DEFAULT_IMPORT_RE.exec(source)) {\n\t\timports.set(m[1], m[3]);\n\t}\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (let m = MAKE_API_RE.exec(source); m; m = MAKE_API_RE.exec(source)) {\n\t\tconst specifier = imports.get(m[3]);\n\t\tif (!specifier) continue;\n\t\tconst resolved = resolveSpecifier(specifier, file, check);\n\t\tif (!resolved) continue;\n\t\tconst relFile = path.relative(check.root, resolved).replaceAll(\"\\\\\", \"/\");\n\t\tconst route = check.routesByFile.get(relFile);\n\t\tif (!route) continue;\n\t\tconst expected = expectedAnnotationPath(route);\n\t\tif (m[2] !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile: path.relative(check.root, file).replaceAll(\"\\\\\", \"/\"),\n\t\t\t\tline: lineOf(source, m.index),\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `makeApi route \"${m[2]}\" doesn't match the endpoint's route \"${expected}\" (derived from ${relFile}). Did the endpoint move?`,\n\t\t\t});\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Resolves an import specifier to an existing file: relative specifiers are\n * resolved against the importing file, others against tsconfig path aliases.\n * Bare module specifiers that match no alias return undefined.\n */\nexport function resolveSpecifier(\n\tspecifier: string,\n\tfromFile: string,\n\tcheck: ApiCallCheck,\n): string | undefined {\n\tlet candidate: string | undefined;\n\tif (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n\t\tcandidate = path.resolve(path.dirname(fromFile), specifier);\n\t} else {\n\t\tfor (const alias of check.aliases) {\n\t\t\tif (typeof alias.find === \"string\") {\n\t\t\t\tif (specifier.startsWith(alias.find)) {\n\t\t\t\t\tcandidate = path.resolve(alias.replacement, specifier.slice(alias.find.length));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (alias.find.test(specifier)) {\n\t\t\t\tcandidate = specifier.replace(alias.find, alias.replacement);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!candidate) return undefined;\n\tconst probes = [\n\t\tcandidate,\n\t\t`${candidate}.ts`,\n\t\t`${candidate}.js`,\n\t\tpath.join(candidate, \"index.ts\"),\n\t\tpath.join(candidate, \"index.js\"),\n\t];\n\tfor (const probe of probes) {\n\t\tif (existsSync(probe) && statSync(probe).isFile()) return probe;\n\t}\n\treturn undefined;\n}\n\nfunction walkSourceFiles(root: string): string[] {\n\tconst files: string[] = [];\n\tconst visit = (dir: string): void => {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (!SKIP_DIRS.has(entry.name)) visit(path.join(dir, entry.name));\n\t\t\t} else if (\n\t\t\t\tentry.isFile() &&\n\t\t\t\tSOURCE_FILE_RE.test(entry.name) &&\n\t\t\t\t!entry.name.endsWith(\".d.ts\")\n\t\t\t) {\n\t\t\t\tfiles.push(path.join(dir, entry.name));\n\t\t\t}\n\t\t}\n\t};\n\tvisit(root);\n\treturn files;\n}\n\n/**\n * The route path a file's annotation should use, derived from its manifest\n * entry: internal suffixes (`/~server`, `/_layout` etc) are stripped so e.g.\n * `posts/[id]/+page.server.ts` expects `\"/posts/[id]\"`.\n */\nexport function expectedAnnotationPath(route: Route): string {\n\tlet p = route.path;\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_ROUTE:\n\t\t\tp = p.replace(/\\/_layout$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_layout\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_ROUTE:\n\t\t\tp = p.replace(/\\/_hook$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_hook\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase ERROR_ROUTE:\n\t\t\tp = p.replace(/\\/_error$/, \"\");\n\t\t\tbreak;\n\t}\n\treturn p === \"\" ? \"/\" : p;\n}\n\nfunction typeNameFor(route: Route): string {\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\treturn \"PageServerEndPoint\";\n\t\tcase SERVER_ROUTE:\n\t\t\treturn \"ServerEndPoint\";\n\t\tcase HOOK_ROUTE:\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\treturn \"ServerHook\";\n\t\tdefault:\n\t\t\treturn \"PageEndPoint\";\n\t}\n}\n\n/**\n * Parses the type arguments that follow an endpoint type name, returning the\n * first argument when it is a string literal (the route path), plus the index\n * after the closing `>` (or after the type name when there are no arguments).\n */\nfunction parseTypeArgs(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (source[i] !== \"<\") return { routePath: undefined, end: i };\n\ti++;\n\tlet depth = 1;\n\tlet routePath: string | undefined;\n\tlet seenComma = false;\n\twhile (i < source.length) {\n\t\tconst c = source[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < source.length && source[j] !== quote) {\n\t\t\t\tif (source[j] === \"\\\\\") j++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (routePath === undefined && !seenComma) routePath = source.slice(i + 1, j);\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"<\") depth++;\n\t\telse if (c === \">\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return { routePath, end: i + 1 };\n\t\t} else if (c === \",\" && routePath === undefined) {\n\t\t\tseenComma = true;\n\t\t}\n\t\ti++;\n\t}\n\treturn { routePath, end: i };\n}\n\n/**\n * Parses an `as T`-style cast that follows a `satisfies T` usage, returning\n * its optional route path argument and the index after the cast.\n */\nfunction parseAsCast(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } | undefined {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!/^as\\b/.test(source.slice(i, i + 3))) return undefined;\n\ti += 2;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!TYPE_NAME_RE.test(source.slice(i))) return undefined;\n\ti = i + source.slice(i).match(TYPE_NAME_RE)![0].length;\n\treturn parseTypeArgs(source, i);\n}\n\nfunction routePathArg(expected: string, actual: string | undefined): string {\n\t// Keep the user's own (correct) path when widening a properly-annotated\n\t// export; otherwise suggest the path derived from the file's location\n\treturn `<\"${actual ?? expected}\">`;\n}\n\nfunction lineOf(source: string, index: number): number {\n\tlet line = 1;\n\tfor (let i = 0; i < index; i++) {\n\t\tif (source[i] === \"\\n\") line++;\n\t}\n\treturn line;\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@torpor/view/compile\";\nimport type Route from \"../types/Route\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport type Site from \"./Site\";\nimport { createApiCallCheck, resolveSpecifier, type RouteCheckIssue } from \"./checkRoutes\";\n\n/**\n * The default import of a `.torp` component from a `.ts`/`.js` route file,\n * e.g. `import component from \"@/views/Layout.torp\"`.\n */\nconst DEFAULT_TORP_IMPORT_RE = /import\\s+[A-Za-z_$][\\w$]*\\s+from\\s*[\"']([^\"']+\\.torp)[\"']/;\n\n/**\n * Checks that every `_layout` route renders its default `<slot />`.\n *\n * The layout engine composes pages by passing each layout (and finally the\n * page) as the default slot of its parent, so a layout that never renders\n * `<slot />` drops its entire content: the server renders the layout's own\n * markup with an empty content area (no error), and the first client-side\n * navigation that reuses the layout fails on a null slot region.\n *\n * Runs at build time (failing the build) and at dev startup. Best-effort and\n * static: a layout that renders `<slot />` conditionally (inside `@if`)\n * passes here, and is caught at request time by the server render warning\n * (see site/layoutSlots.ts).\n */\nexport function checkLayoutSlots(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type === LAYOUT_ROUTE) {\n\t\t\tissues.push(...checkLayoutSlot(site, route));\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single layout route's component (the `.torp` route file itself,\n * or the `.torp` file its `.ts`/`.js` endpoint re-exports as its default\n * import). Routes without a file (inline endpoints) can't hold a component,\n * so they are skipped.\n */\nexport function checkLayoutSlot(site: Site, route: Route): RouteCheckIssue[] {\n\tif (route.type !== LAYOUT_ROUTE || !route.file) return [];\n\n\tconst check = createApiCallCheck(site);\n\n\t// The component is either the route file itself (.torp) or a .ts/.js\n\t// endpoint re-exporting a .torp component as its default export\n\tlet torpFile = path.join(site.root, route.file);\n\tif (!route.file.endsWith(\".torp\")) {\n\t\tconst source = readIfExists(torpFile);\n\t\tif (source === undefined) return [];\n\t\tconst match = DEFAULT_TORP_IMPORT_RE.exec(source);\n\t\tif (!match) return [];\n\t\tconst resolved = resolveSpecifier(match[1], torpFile, check);\n\t\tif (!resolved) return [];\n\t\ttorpFile = resolved;\n\t}\n\n\tconst source = readIfExists(torpFile);\n\tif (source === undefined) return [];\n\n\t// Parse errors are reported when the file is compiled, not here\n\tconst parsed = parse(source);\n\tif (!parsed.ok || !parsed.template) return [];\n\tif (rendersDefaultSlot(parsed.template)) return [];\n\n\treturn [\n\t\t{\n\t\t\tfile: route.file,\n\t\t\tline: 1,\n\t\t\tseverity: \"error\",\n\t\t\tmessage:\n\t\t\t\t\"The layout never renders <slot />, so pages under it render without their content. \" +\n\t\t\t\t\"Every _layout component must render <slot />, or pass it down to a child component \" +\n\t\t\t\t\"it renders.\",\n\t\t},\n\t];\n}\n\nfunction readIfExists(file: string): string | undefined {\n\ttry {\n\t\tif (!existsSync(file) || !statSync(file).isFile()) return undefined;\n\t\treturn readFileSync(file, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks a parsed template looking for a default `<slot />` anywhere in the\n * render tree — including nested inside a child component element, which is\n * how a layout passes the page slot down (e.g. `<Shell><slot /></Shell>`).\n */\n// HACK: no types on the internal parse tree nodes (same as the prettier plugin)\nfunction rendersDefaultSlot(template: any): boolean {\n\tconst component = template.components?.[0];\n\tif (!component) return false;\n\treturn walk(component.markup);\n}\n\nfunction walk(node: any): boolean {\n\tif (\n\t\t(node.type === \"element\" || node.type === \"special\") &&\n\t\tnode.tagName === \"slot\" &&\n\t\t!node.attributes?.some((a: any) => a.name === \"name\")\n\t) {\n\t\treturn true;\n\t}\n\treturn (node.children ?? []).some(walk);\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Plugin } from \"vite\";\nimport type { ResolvedOpenApiOptions } from \"../openapi/types\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport { normalizeBasePath, normalizeOrigin } from \"./basePath\";\nimport Site from \"./Site\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\nconst moduleId = \"@torpor/build/manifest\";\n\nconst LOAD_EXPORT_RE =\n\t/[{,]\\s*load\\s*[:(]|\\bexport\\s+(?:async\\s+)?(?:function|const|let|var)\\s+load\\b|\\bexport\\s*\\{[^}]*\\bload\\b/;\n\nexport function hasLoadExport(source: string): boolean {\n\treturn LOAD_EXPORT_RE.test(source);\n}\n\n/**\n * A Vite plugin that provides information about the app to both clientEntry and\n * serverEntry.\n */\nexport default function manifest(site: Site, server = false): Plugin {\n\treturn {\n\t\tname: \"torpor-manifest\",\n\t\tresolveId: {\n\t\t\torder: \"pre\",\n\t\t\thandler(id) {\n\t\t\t\tif (id === moduleId) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// @ts-ignore\n\t\tload(id, viteOptions) {\n\t\t\tif (id === moduleId) {\n\t\t\t\tlet serverRequest = server && !!viteOptions?.ssr;\n\n\t\t\t\t// Validate here, so bad config fails the build\n\t\t\t\tconst base = normalizeBasePath(site.basePath);\n\t\t\t\tif (site.sitemap && !site.origin) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`site.sitemap requires site.origin to be set (it is the host of the urls)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (site.origin) {\n\t\t\t\t\tnormalizeOrigin(site.origin);\n\t\t\t\t}\n\t\t\t\tif (typeof site.sitemap === \"object\" && site.sitemap !== null) {\n\t\t\t\t\tif (site.sitemap.path !== undefined && !site.sitemap.path.startsWith(\"/\")) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap.path}\"`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof site.sitemap === \"string\" && !site.sitemap.startsWith(\"/\")) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// If there are inline endpoints, site plugins, an OpenAPI\n\t\t\t\t// document or an env schema, and we're building for the server,\n\t\t\t\t// we need to import the config file to access them. On the\n\t\t\t\t// client, the config file is never imported, keeping server\n\t\t\t\t// code out of the client bundle.\n\t\t\t\tconst hasInline = site.routes.some((r) => r.endPoint && !r.file);\n\t\t\t\tconst hasPlugins = site.plugins.length > 0;\n\t\t\t\tconst hasOpenApi = site.pluginState.has(OPEN_API_STATE_KEY);\n\t\t\t\tconst hasEnv = !!site.env;\n\t\t\t\tconst hasMiddleware = site.middleware.length > 0;\n\t\t\t\tconst hasRuntimeSitemap = typeof site.sitemap === \"object\" && site.sitemap !== null;\n\t\t\t\tconst configImport =\n\t\t\t\t\thasInline || hasPlugins || hasOpenApi || hasEnv || hasRuntimeSitemap || hasMiddleware\n\t\t\t\t\t\t? serverRequest && site.configFile\n\t\t\t\t\t\t\t? `import __site from ${JSON.stringify(site.configFile)};`\n\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The env schema is handed to @torpor/build/env at startup, so\n\t\t\t\t// that `env()` calls in route code can validate against it\n\t\t\t\tconst envGlue =\n\t\t\t\t\tserverRequest && hasEnv && site.configFile\n\t\t\t\t\t\t? `import { setEnvSchema } from \"@torpor/build/env\";\nsetEnvSchema(__site.env);`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// Site plugins are run when the server starts up (in dev and in\n\t\t\t\t// production), so that routes they register are available at\n\t\t\t\t// runtime. Top-level await is fine here: this module is only\n\t\t\t\t// loaded through Vite's SSR pipeline\n\t\t\t\tconst pluginLoop =\n\t\t\t\t\tserverRequest && hasPlugins\n\t\t\t\t\t\t? `for (const __plugin of __site.plugins ?? []) { await __plugin(__site); }`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The OpenAPI document endpoint is generated code (rather than an\n\t\t\t\t// inline endpoint) because it must load each route file -- which\n\t\t\t\t// only works from module code that Vite processes/bundles. The\n\t\t\t\t// options live in `site.pluginState` (set by the plugin), so they\n\t\t\t\t// are available both here and in the generated runtime code\n\t\t\t\tconst openApiOptions = site.pluginState.get(OPEN_API_STATE_KEY) as\n\t\t\t\t\t| ResolvedOpenApiOptions\n\t\t\t\t\t| undefined;\n\t\t\t\tconst openApiGlue =\n\t\t\t\t\tserverRequest && openApiOptions && site.configFile\n\t\t\t\t\t\t? openApiGlueCode(site, openApiOptions)\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\tconst openApiRoute =\n\t\t\t\t\tserverRequest && openApiOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(openApiOptions.path)}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __openApiGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// A runtime sitemap, when `site.sitemap` is a `{ get }` config:\n\t\t\t\t// a server endpoint that reads urls and serves the XML\n\t\t\t\tconst sitemapOptions =\n\t\t\t\t\ttypeof site.sitemap === \"object\" && site.sitemap !== null ? site.sitemap : undefined;\n\t\t\t\tconst sitemapGlue =\n\t\t\t\t\tserverRequest && sitemapOptions && site.configFile\n\t\t\t\t\t\t? `\nimport { sitemapResponse } from \"@torpor/build/discovery\";\nasync function __sitemapGet(event) {\n\treturn await sitemapResponse(__site.sitemap, ${JSON.stringify(base)}, event);\n}\n`\n\t\t\t\t\t\t: \"\";\n\t\t\t\tconst sitemapRoute =\n\t\t\t\t\tserverRequest && sitemapOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(sitemapOptions.path ?? \"/sitemap.xml\")}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __sitemapGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\treturn `\n${!serverRequest ? \"const load = { default: { load: true } };\" : \"\"}\n${configImport}\n${envGlue}\n${pluginLoop}\n${openApiGlue}\n${sitemapGlue}\nexport default {\n base: ${JSON.stringify(base)},\n viewTransitions: ${!!site.viewTransitions},\n ${serverRequest && hasMiddleware ? \"middleware: __site.middleware ?? [],\" : \"\"}\n routes: [\n ${site.routes\n\t\t\t.map((r) => {\n\t\t\t\tlet endPoint: string;\n\t\t\t\tif (!r.file) {\n\t\t\t\t\t// Inline endpoint (no file)\n\t\t\t\t\tif (serverRequest) {\n\t\t\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\t\t\tendPoint = `() => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Client-side stub: check if the inline\n\t\t\t\t\t\t// endpoint has a load function\n\t\t\t\t\t\tconst haveLoad =\n\t\t\t\t\t\t\ttypeof (r.endPoint as Record<string, unknown> | undefined)?.load === \"function\";\n\t\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t\t}\n\t\t\t\t} else if (serverRequest || !/server\\.(ts|js)$/.test(r.file)) {\n\t\t\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\t\t\t// NOTE: No `@vite-ignore` here, so that Vite processes the import:\n\t\t\t\t\t// in dev the module runner transforms the file on the fly, and in\n\t\t\t\t\t// a production build Rollup bundles the route into a chunk and\n\t\t\t\t\t// rewrites the import -- leaving the raw source path in place\n\t\t\t\t\t// would hand Node/wrangler `.ts`/`.torp` files it can't load\n\t\t\t\t\tconst importExpr = `() => import(\"${filePath}\")`;\n\t\t\t\t\t// A .torp file's default export is a component, so wrap it\n\t\t\t\t\t// as a PageEndPoint ({ component }) for the entries\n\t\t\t\t\tendPoint = r.file.endsWith(\".torp\")\n\t\t\t\t\t\t? `${importExpr}.then((m) => ({ default: { component: m.default } }))`\n\t\t\t\t\t\t: importExpr;\n\t\t\t\t} else {\n\t\t\t\t\t// On the client, for a server route, we need to check\n\t\t\t\t\t// whether there's a load function and set a dummy endPoint\n\t\t\t\t\t// if so. The correct endpoint will be hit in clientEntry\n\t\t\t\t\tconst haveLoad = hasLoadExport(readFileSync(path.join(site.root, r.file), \"utf8\"));\n\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t}\n\t\t\t\tconst sub = r.subFolder ? `\"${r.subFolder}\"` : \"undefined\";\n\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${endPoint}, subFolder: ${sub} },`;\n\t\t\t})\n\t\t\t.join(\"\\n \")}\n ${openApiRoute}\n ${sitemapRoute}\n ],\n};\n`;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Generates the module code for the OpenAPI document endpoint: a map of\n * route path to endpoint loader, and a cached handler that loads every\n * endpoint and builds the document on first use.\n */\nfunction openApiGlueCode(site: Site, options: ResolvedOpenApiOptions): string {\n\tconst loaders = site.routes\n\t\t.filter((r) => r.type === SERVER_ROUTE)\n\t\t// Don't document the docs page itself\n\t\t.filter((r) => r.path !== options.docs)\n\t\t.map((r) => {\n\t\t\tif (!r.file) {\n\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\treturn `${JSON.stringify(r.path)}: () => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t}\n\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\treturn `${JSON.stringify(r.path)}: () => import(${JSON.stringify(filePath)})`;\n\t\t})\n\t\t.join(\",\\n \");\n\n\treturn `\nimport { buildOpenApiDocument, OPEN_API_STATE_KEY } from \"@torpor/build/openapi\";\nlet __openApiDoc;\nconst __openApiRoutes = {\n ${loaders}\n};\nasync function __openApiGet() {\n if (!__openApiDoc) {\n const __entries = [];\n for (const [__path, __loader] of Object.entries(__openApiRoutes)) {\n __entries.push({ path: __path, endPoint: (await __loader()).default });\n }\n __openApiDoc = buildOpenApiDocument(__entries, __site.pluginState.get(OPEN_API_STATE_KEY));\n }\n return new Response(JSON.stringify(__openApiDoc), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n`;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { UserConfig } from \"vite\";\n\nexport type PackageJson = {\n\tname?: string;\n\ttorpor?: string | boolean;\n\texports?: unknown;\n\tdependencies?: Record<string, string>;\n\tdevDependencies?: Record<string, string>;\n\toptionalDependencies?: Record<string, string>;\n\tpeerDependencies?: Record<string, string>;\n\t[key: string]: unknown;\n};\n\n/**\n * Finds packages installed in the site that ship `.torp` files, e.g. icon\n * libraries like phosphor-torpor. These packages need the torpor compiler, so\n * they can't go through Vite's default pipelines: dep optimization parses\n * their files as plain JavaScript (and fails on torpor syntax like `@render`\n * or `import type` from an uncompiled source), and SSR externalization would\n * leave raw `.torp` imports that neither Node nor workerd can load.\n *\n * A package is a torpor package when it declares a `torpor` entry in its\n * package.json, or when any of its export targets is a `.torp` file. The\n * entry is usually a path (`\"torpor\": \"./lib/index.js\"`, mirroring the\n * `svelte` field convention), but packages that ship compiled output can\n * just mark themselves with `\"torpor\": true`.\n *\n * @param siteRoot The root folder of the site\n * @returns The names of the torpor packages found (may be empty)\n */\nexport default function findTorporPackages(siteRoot: string): string[] {\n\tconst sitePackageJson = path.resolve(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst packages = new Set<string>();\n\tconst visited = new Set<string>();\n\n\tconst rootRequire = createRequire(sitePackageJson);\n\tfor (const name of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(name, rootRequire, packages, visited);\n\t}\n\treturn [...packages];\n}\n\n/**\n * Adds `optimizeDeps.exclude` and `ssr.noExternal` entries for packages that\n * ship `.torp` files, so that they are served/bundled through the torpor\n * compiler instead.\n */\nexport function addTorporPackageConfig(siteRoot: string, config: UserConfig): void {\n\tconst packages = findTorporPackages(siteRoot);\n\tif (packages.length === 0) return;\n\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.exclude = [...(config.optimizeDeps.exclude ?? []), ...packages];\n\n\tconfig.ssr ??= {};\n\tconst noExternal = config.ssr.noExternal;\n\tif (noExternal === undefined) {\n\t\tconfig.ssr.noExternal = packages;\n\t} else if (Array.isArray(noExternal)) {\n\t\tnoExternal.push(...packages);\n\t}\n\t// For `true` (bundle everything) or string/regex values there is nothing\n\t// sensible to merge, and they already bundle more than we need\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [\n\t\t...Object.keys(pkg.dependencies ?? {}),\n\t\t...Object.keys(pkg.devDependencies ?? {}),\n\t\t...Object.keys(pkg.optionalDependencies ?? {}),\n\t\t...Object.keys(pkg.peerDependencies ?? {}),\n\t];\n}\n\nfunction collectTorporPackage(\n\tname: string,\n\trequire: NodeRequire,\n\tpackages: Set<string>,\n\tvisited: Set<string>,\n): void {\n\t// Some packages shadow Node builtins (e.g. a dependency literally named\n\t// \"path\"), and builtins can't contain .torp files\n\tif (isBuiltin(name)) return;\n\n\tconst packageJsonPath = resolvePackageJson(name, require);\n\tif (!packageJsonPath || visited.has(packageJsonPath)) return;\n\tvisited.add(packageJsonPath);\n\n\tlet pkg: PackageJson;\n\ttry {\n\t\tpkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t} catch {\n\t\treturn;\n\t}\n\n\tif (isTorporPackage(pkg)) {\n\t\tpackages.add(pkg.name ?? name);\n\t}\n\n\t// Recurse into the package's own dependencies, resolved relative to it\n\t// (pnpm keeps transitive deps out of the site's top-level node_modules)\n\tconst depRequire = createRequire(packageJsonPath);\n\tfor (const depName of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(depName, depRequire, packages, visited);\n\t}\n}\n\nfunction isTorporPackage(pkg: PackageJson): boolean {\n\tif (pkg.torpor === true || typeof pkg.torpor === \"string\") return true;\n\treturn exportsIncludeTorp(pkg.exports);\n}\n\nfunction exportsIncludeTorp(exports: unknown): boolean {\n\tif (typeof exports === \"string\") return exports.endsWith(\".torp\");\n\tif (Array.isArray(exports)) return exports.some(exportsIncludeTorp);\n\tif (exports && typeof exports === \"object\") {\n\t\treturn Object.values(exports).some(exportsIncludeTorp);\n\t}\n\treturn false;\n}\n\nfunction resolvePackageJson(name: string, require: NodeRequire): string | undefined {\n\t// require.resolve returns the name itself for Node builtins, so guard\n\t// everything below with absolute path checks\n\ttry {\n\t\tconst packageJson = require.resolve(`${name}/package.json`);\n\t\treturn path.isAbsolute(packageJson) ? packageJson : undefined;\n\t} catch {\n\t\tlet entry: string;\n\t\ttry {\n\t\t\tentry = require.resolve(name);\n\t\t} catch {\n\t\t\t// Not resolvable through Node's resolver -- either the package\n\t\t\t// isn't installed (e.g. an optional peer), or its `exports` map\n\t\t\t// has no `.` or `./package.json` entry and both lookups above\n\t\t\t// threw ERR_PACKAGE_PATH_NOT_EXPORTED. Try the standard\n\t\t\t// node_modules lookup paths directly\n\t\t\treturn resolveFromNodeModules(name, require);\n\t\t}\n\t\tif (!path.isAbsolute(entry)) return undefined;\n\t\tlet dir = path.dirname(entry);\n\t\twhile (true) {\n\t\t\tconst packageJson = path.join(dir, \"package.json\");\n\t\t\tif (existsSync(packageJson)) return packageJson;\n\t\t\tconst parent = path.dirname(dir);\n\t\t\tif (parent === dir) return undefined;\n\t\t\tdir = parent;\n\t\t}\n\t}\n}\n\n/**\n * Finds a package's package.json by checking the standard node_modules\n * lookup paths directly, for packages that Node's resolver can't load\n * (`ERR_PACKAGE_PATH_NOT_EXPORTED`).\n */\nfunction resolveFromNodeModules(name: string, require: NodeRequire): string | undefined {\n\tfor (const dir of require.resolve.paths(name) ?? []) {\n\t\tif (!path.isAbsolute(dir)) continue;\n\t\tconst packageJson = path.join(dir, ...name.split(\"/\"), \"package.json\");\n\t\tif (existsSync(packageJson)) return packageJson;\n\t}\n\treturn undefined;\n}\n","import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport ServerEvent from \"../server/ServerEvent\";\nimport { sitemapXml } from \"../discovery/sitemap\";\nimport prepareTemplate from \"./prepareTemplate\";\nimport type Site from \"../site/Site\";\nimport { ERROR_ROUTE, PAGE_ROUTE, PAGE_SERVER_ROUTE, LAYOUT_ROUTE } from \"../types/RouteType\";\n\n/**\n * How a `prerender` flag can appear on an endpoint: `true`/`false` to\n * include/exclude a page, or a `params` entry list for a dynamic route.\n */\nexport type PrerenderFlag = boolean | { params: Record<string, unknown>[] };\n\n/** The route shapes the prerenderer resolves from (Router.routes, Site.routes). */\ntype RouteLike = {\n\tpath: string;\n\ttype: number;\n\tendPoint: () => Promise<any>;\n\tsubFolder?: string;\n};\n\nexport type PrerenderPath = {\n\tpath: string;\n\tparams: Record<string, string> | undefined;\n};\n\n/**\n * Resolves which page paths should be prerendered, from the routes of a\n * built site, testing in order:\n *\n * 1. the page endpoint's own `prerender` flag, or the inferred-params one\n * on the sibling `+page.server` endpoint\n * 2. the nearest ancestor `_layout` endpoint's flag\n * 3. the site-level `site.prerender` setting: a boolean default, or a\n * longest-match map of exact paths (`/about`) and prefixes (`/blog/**`)\n *\n * @param routes The site's routes, including layouts and page server\n * endpoints, with lazy endpoint loaders\n * @param siteFlag The `site.prerender` value\n * @returns The paths to prerender, with route params for dynamic ones\n */\nexport async function resolvePrerenderPaths(\n\troutes: RouteLike[],\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): Promise<PrerenderPath[]> {\n\tconst result: PrerenderPath[] = [];\n\n\tfor (const route of routes.filter((r) => r.type === PAGE_ROUTE)) {\n\t\tconst base = route.path.replace(/\\/$/, \"\");\n\n\t\tconst pageFlag = (await endpointFlag(route.endPoint)) as PrerenderFlag | undefined;\n\t\tconst serverRoute = routes.find(\n\t\t\t(r) => r.type === PAGE_SERVER_ROUTE && r.path === `${base}/~server`,\n\t\t);\n\t\tconst serverFlag = serverRoute\n\t\t\t? ((await endpointFlag(serverRoute.endPoint)) as PrerenderFlag | undefined)\n\t\t\t: undefined;\n\n\t\tconst entries = paramsEntriesOf(pageFlag) ?? paramsEntriesOf(serverFlag);\n\t\tconst ownFlag =\n\t\t\tpageFlag === undefined\n\t\t\t\t? serverFlag === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Boolean(serverFlag)\n\t\t\t\t: Boolean(pageFlag);\n\t\tconst resolved =\n\t\t\townFlag ?? (await nearestLayoutFlag(routes, route)) ?? siteResolve(route.path, siteFlag);\n\t\tif (!resolved) continue;\n\n\t\tif (/\\[[^\\]]+\\]/.test(route.path)) {\n\t\t\tif (!entries?.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The route \"${route.path}\" is marked for prerendering, but it has dynamic ` +\n\t\t\t\t\t\t`segments and no params entries were declared. Set ` +\n\t\t\t\t\t\t`\\`prerender: { params: [...] }\\` on its endpoint.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tresult.push({ path: expandPath(route.path, entry), params: toStringParams(entry) });\n\t\t\t}\n\t\t} else {\n\t\t\tresult.push({ path: route.path || \"/\", params: undefined });\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction paramsEntriesOf(flag: PrerenderFlag | undefined): Record<string, unknown>[] | undefined {\n\treturn typeof flag === \"object\" && flag !== null ? flag.params : undefined;\n}\n\n/**\n * Renders the prerenderable routes to static HTML files in the client\n * output, plus the `_error` page as `404.html` when the site has one.\n *\n * Called by `tb build` after the client and server builds, when the built\n * server entry (with its routes) can be imported directly, and before the\n * adapter's postbuild -- so a prerendered site ships as plain files and\n * any static host can serve it.\n *\n * @param site The loaded site config\n * @returns The number of HTML files written\n */\nexport default async function runPrerender(site: Site): Promise<number> {\n\tconst serverFolder = path.join(site.root, \"dist\", \"server\");\n\tconst clientFolder = path.join(site.root, \"dist\", \"client\");\n\tconst serverEntryPath = path.join(serverFolder, \"serverEntry.js\");\n\n\t// Load the built server entry, with its routes baked in\n\tconst serverEntry = (await import(pathToFileURL(serverEntryPath).href)) as {\n\t\tload: (ev: unknown, template: string | undefined) => Promise<Response>;\n\t\trouter: { routes: { path: string; handler: RouteLike }[] };\n\t};\n\tconst routes = serverEntry.router.routes.map((r) => r.handler);\n\n\t// Deserialize the client entry asset name the same way the Cloudflare\n\t// adapter does, so the template works the same for prerendered output\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tconst assets = path.join(clientFolder, \"assets\");\n\t\tlet clientScript = (await fs.readdir(assets)).find((f) => f.startsWith(\"clientEntry-\"));\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\ttemplate = prepareTemplate(await fs.readFile(siteHtml, \"utf-8\"), `/assets/${clientScript}`);\n\t}\n\n\tconst entries = await resolvePrerenderPaths(routes, site.prerender);\n\n\t// Load functions may read the environment (env() uses globalThis.adapter)\n\t// @ts-ignore\n\tglobalThis.adapter ??= { env: process.env };\n\n\tconst failures: string[] = [];\n\tconst skipped: string[] = [];\n\tlet written = 0;\n\tfor (const entry of entries) {\n\t\tconst url = `http://torpor.build${entry.path}`;\n\t\tconst request = new Request(url);\n\t\tconst serverEvent = new ServerEvent(request, entry.params, new URL(url));\n\t\tconst response = await serverEntry.load(serverEvent, template);\n\n\t\tif (isRedirect(response)) {\n\t\t\t// Load functions redirect for auth and first-run setup, which is\n\t\t\t// expected on a fresh site -- skip the page rather than failing\n\t\t\t// the build, so a site can ship before it's initialized\n\t\t\tskipped.push(`${entry.path} (status ${response.status})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (response.status < 200 || response.status > 299) {\n\t\t\tfailures.push(`${entry.path} (status ${await responseStatus(response)})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tfailures.push(`${entry.path} (not an HTML response)`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait writeFileForPath(clientFolder, entry.path, await response.text());\n\t\twritten++;\n\t}\n\n\t// The error page is useful on every static host, so render it whenever\n\t// the site has one, even when nothing else is prerendered\n\tconst errorRoute = routes.find((r) => r.type === ERROR_ROUTE);\n\tif (errorRoute && template !== undefined) {\n\t\tconst url = \"http://torpor.build/_error?status=404\";\n\t\tconst serverEvent = new ServerEvent(new Request(url), undefined, new URL(url));\n\t\tconst response = await serverEntry.load(serverEvent, template);\n\t\tif (isRedirect(response)) {\n\t\t\t// The layout may redirect before the error page renders (e.g. to\n\t\t\t// a setup page on a fresh site) -- skip it; the host's default\n\t\t\t// 404 page is used instead\n\t\t\tskipped.push(`/_error (status ${response.status})`);\n\t\t} else if (response.ok && response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tawait fs.writeFile(path.join(clientFolder, \"404.html\"), await response.text());\n\t\t} else {\n\t\t\tfailures.push(`/_error (status ${await responseStatus(response)})`);\n\t\t}\n\t}\n\n\tif (skipped.length) {\n\t\tconsole.log(\n\t\t\t`Skipped prerendering ${skipped.length} route${skipped.length === 1 ? \"\" : \"s\"} ` +\n\t\t\t\t`(redirected):\\n` +\n\t\t\t\tskipped.map((s) => ` - ${s}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\tif (failures.length) {\n\t\tthrow new Error(\n\t\t\t`Prerendering failed for ${failures.length} route${failures.length === 1 ? \"\" : \"s\"}:\\n` +\n\t\t\t\tfailures.map((f) => ` - ${f}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The sitemap, if configured, lists the URLs that were just rendered:\n\t// the set of pages that are actually static, which is exactly what a\n\t// build-time sitemap can honestly represent\n\tif (site.sitemap && site.origin && entries.length > 0) {\n\t\tconst base = site.basePath;\n\t\tconst sitemap = sitemapXml(\n\t\t\tsite.origin,\n\t\t\tbase,\n\t\t\tentries.map((entry) => entry.path),\n\t\t);\n\t\tawait fs.writeFile(\n\t\t\tpath.join(\n\t\t\t\tclientFolder,\n\t\t\t\ttypeof site.sitemap === \"string\" ? site.sitemap.slice(1) : \"sitemap.xml\",\n\t\t\t),\n\t\t\tsitemap,\n\t\t);\n\t}\n\n\treturn written;\n}\n\n/**\n * Writes an HTML file for a route path, e.g. `/` into `index.html` and\n * `/about` into `about/index.html`. Guards against route param values\n * escaping the client folder.\n */\nasync function writeFileForPath(\n\tclientFolder: string,\n\troutePath: string,\n\thtml: string,\n): Promise<void> {\n\tconst rel = routePath === \"/\" ? \"index.html\" : routePath.slice(1) + \"/index.html\";\n\tconst out = path.resolve(clientFolder, rel);\n\tconst relSafe = path.relative(clientFolder, out);\n\tif (relSafe.startsWith(\"..\") || path.isAbsolute(relSafe)) {\n\t\tthrow new Error(`The prerendered path \"${routePath}\" escaped ${clientFolder}`);\n\t}\n\tawait fs.mkdir(path.dirname(out), { recursive: true });\n\tawait fs.writeFile(out, html);\n}\n\nasync function endpointFlag(loader: () => Promise<any>): Promise<PrerenderFlag | undefined> {\n\tconst endPoint = (await loader())?.default;\n\treturn (endPoint as { prerender?: PrerenderFlag } | undefined)?.prerender;\n}\n\n/**\n * The nearest ancestor `_layout`'s flag for a page path, or undefined when\n * no layout sets one. Layouts apply within the same subFolder.\n */\nasync function nearestLayoutFlag(\n\troutes: RouteLike[],\n\troute: RouteLike,\n): Promise<boolean | undefined> {\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const candidate of routes) {\n\t\tif (candidate.type !== LAYOUT_ROUTE || candidate.subFolder !== route.subFolder) continue;\n\t\tconst base = candidate.path.replace(/\\/_layout$/, \"\");\n\t\tconst isAncestor = base === \"\" || route.path === base || route.path.startsWith(base + \"/\");\n\t\tif (!isAncestor) continue;\n\t\tconst flagOfLayout = (await endpointFlag(candidate.endPoint)) as boolean | undefined;\n\t\tif (flagOfLayout !== undefined && base.length > flagLength) {\n\t\t\tflag = flagOfLayout;\n\t\t\tflagLength = base.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction siteResolve(\n\troutePath: string,\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): boolean | undefined {\n\tif (siteFlag === undefined) return undefined;\n\tif (typeof siteFlag === \"boolean\") return siteFlag;\n\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const [pattern, value] of Object.entries(siteFlag)) {\n\t\tconst base = pattern.replace(/\\/\\*\\*$/, \"\");\n\t\tconst isPrefixMatch =\n\t\t\tbase !== pattern && (routePath === base || routePath.startsWith(base + \"/\"));\n\t\tif ((pattern === routePath || isPrefixMatch) && pattern.length > flagLength) {\n\t\t\tflag = value;\n\t\t\tflagLength = pattern.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction toStringParams(entry: Record<string, unknown>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tresult[key] = String(value);\n\t}\n\treturn result;\n}\n\n/**\n * Fills a route path's `[param]` and `[...rest]` segments with the values\n * from a params entry.\n */\nexport function expandPath(routePath: string, entry: Record<string, unknown>): string {\n\treturn routePath.replace(/\\[([^\\]]+)\\]/g, (_match, name: string) => {\n\t\tconst key = name.replace(/^\\.\\.\\./, \"\");\n\t\tif (!(key in entry)) {\n\t\t\tthrow new Error(`Missing param \"${key}\" for the route \"${routePath}\" (prerendering)`);\n\t\t}\n\t\treturn String(entry[key]);\n\t});\n}\n\nfunction isRedirect(response: Response): boolean {\n\treturn response.status >= 300 && response.status < 400;\n}\n\nasync function responseStatus(response: Response): Promise<string> {\n\treturn `${response.status}${response.status === 303 ? \" redirect\" : \"\"}`;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { build, defineConfig, type AliasOptions } from \"vite\";\nimport Site from \"../site/Site\";\nimport { checkApiCalls, checkRoutes, reportRouteIssues } from \"../site/checkRoutes\";\nimport { checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport manifest from \"../site/manifest.ts\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport runPrerender from \"./runPrerender\";\n\n// TODO: Don't cache index.html in dev?\n// TODO: Don't reload layouts during client routing\n// TODO: Call the correct +page and +server routes when in the same folder\n\nexport default async function runBuild(site: Site): Promise<void> {\n\t// Load environment variables from a `.env` file, with defaults if not\n\t// set -- prerendering goes through the full load pipeline, so route\n\t// `load` functions can hit the database at build time\n\tconfigDotenv();\n\n\t// Check route type annotations and makeApi calls against the routes\n\t// derived from file locations, and check that layouts render their slot;\n\t// errors fail the build before anything is written\n\tlet errorCount = reportRouteIssues(checkRoutes(site));\n\terrorCount += reportRouteIssues(checkApiCalls(site));\n\terrorCount += reportRouteIssues(checkLayoutSlots(site));\n\tif (errorCount > 0) {\n\t\tthrow new Error(\n\t\t\t`Route type check failed with ${errorCount} error${errorCount === 1 ? \"\" : \"s\"} (see above)`,\n\t\t);\n\t}\n\n\t// Delete the dist folder if it exists\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tif (existsSync(distFolder)) {\n\t\tawait fs.rm(distFolder, { recursive: true });\n\t}\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// HOOK: Prebuild\n\tif (site.adapter.prebuild) {\n\t\tawait site.adapter.prebuild(site);\n\t}\n\n\t// TODO: From a setting\n\t// An endpoints-only site has no site.html, so everything template-related\n\t// is optional\n\tconst siteHtml = path.resolve(site.root, \"src/site.html\");\n\tconst hasSiteHtml = existsSync(siteHtml);\n\n\t// Production always bundles the compiled entry files from the installed\n\t// package, so builds don't depend on (unshipped) framework sources\n\tconst entries = siteEntryPaths(site.root, false);\n\tconst clientScript = entries.clientEntry;\n\tconst serverScript = entries.serverEntry;\n\n\t// Build the client assets, including site.html and the route files\n\t// EXCLUDING anything with `server.js` in the name\n\tconst clientConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\t// for the client, but hardcodes tsconfigPaths:false on the SSR\n\t// externalization path, so mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` to resolve them during transform for both client and SSR\n\tclientConfig.resolve ??= {};\n\tclientConfig.resolve.tsconfigPaths ??= true;\n\tclientConfig.resolve.alias = [\n\t\t...asAliasArray(clientConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\tclientConfig.plugins = [manifest(site), torpor(), ...site.vitePlugins];\n\tclientConfig.build ??= {};\n\tclientConfig.build.outDir = clientFolder;\n\t// Root-level host files (robots.txt, favicon.ico, .well-known/*, etc) in\n\t// src/public are copied verbatim into the client output root, and served\n\t// from the same folder by the dev server\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tclientConfig.publicDir = publicDir;\n\t}\n\tclientConfig.build.rollupOptions ??= {};\n\tclientConfig.build.rollupOptions.input = [\n\t\t...(hasSiteHtml ? [siteHtml] : []),\n\t\tclientScript,\n\t\t...site.routes\n\t\t\t.filter((r) => r.file && !/server\\.(ts|js)$/.test(r.file))\n\t\t\t.map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs.filter((f) => !/server\\.(ts|js)$/.test(f)),\n\t];\n\tclientConfig.build.ssrManifest = true;\n\tawait build(defineConfig(clientConfig));\n\n\t// Build the server assets, including the server entry script and the route\n\t// files\n\tconst serverConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`), as above\n\tserverConfig.resolve ??= {};\n\tserverConfig.resolve.tsconfigPaths ??= true;\n\tserverConfig.resolve.alias = [\n\t\t...asAliasArray(serverConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\tserverConfig.plugins = [manifest(site, true), torpor(), ...site.vitePlugins];\n\tserverConfig.build ??= {};\n\tserverConfig.build.outDir = serverFolder;\n\t// Bundle packages that ship `.torp` files into the server build, as they\n\t// need the torpor compiler (Node/workerd can't load them externalized)\n\taddTorporPackageConfig(site.root, serverConfig);\n\tserverConfig.build.rollupOptions ??= {};\n\tserverConfig.build.rollupOptions.input = [\n\t\tserverScript,\n\t\t...site.routes.filter((r) => r.file).map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs,\n\t];\n\tserverConfig.build.ssr = serverScript;\n\tawait build(defineConfig(serverConfig));\n\n\t// Move the site.html file into /client\n\t// HACK: Should do this in Rollup if possible?\n\tif (hasSiteHtml) {\n\t\tawait fs.rename(\n\t\t\tpath.join(clientFolder, \"src\", \"site.html\"),\n\t\t\tpath.join(clientFolder, \"site.html\"),\n\t\t);\n\t\tawait fs.rm(path.join(clientFolder, \"src\"), { recursive: true });\n\t}\n\n\t// Prerender routes marked with `prerender` -- including everything\n\t// inherited from layouts and site.prerender -- to static HTML files in\n\t// the client output, plus the error page as 404.html. Any static host\n\t// can then serve dist/client directly\n\tconst prerendered = await runPrerender(site);\n\tif (prerendered > 0) {\n\t\tconsole.log(`[torpor] Prerendered ${prerendered} route${prerendered === 1 ? \"\" : \"s\"}`);\n\t}\n\n\t// HOOK: Postbuild\n\tif (site.adapter.postbuild) {\n\t\tawait site.adapter.postbuild(site);\n\t}\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n","import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\treadFileSync,\n\treaddirSync,\n\trealpathSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\n\n/**\n * Vite's dep-optimization cache (node_modules/.vite) keys off the lockfile\n * and config, but not the content of workspace packages. When a workspace\n * package is rebuilt while the cache holds prebundled copies of it, dev SSR\n * keeps executing the stale modules -- producing bizarre errors (missing\n * runtime identifiers, \"$cache must be used in a getter\", ...) that only a\n * manual cache delete fixes.\n *\n * clearStaleDepCache runs at `tb --dev` startup: it fingerprints every\n * workspace package the site depends on (path, size and mtime of each file)\n * and, when the fingerprint differs from the previous run, deletes the cache\n * so Vite re-optimizes from the rebuilt packages.\n *\n * Live rebuilds while the server is up are still not hot-invalidated (that\n * needs a watcher feeding Vite's module graph); this closes the \"restart and\n * hope you remember the trick\" gap.\n */\n\nconst STORE_NAME = \".torpor-dev-cache.json\";\n\n/**\n * Clears site/node_modules/.vite when workspace packages changed since the\n * last dev run. Returns true when the cache was removed.\n */\nexport function clearStaleDepCache(siteRoot: string, log?: (message: string) => void): boolean {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return false;\n\n\t\tconst cacheDir = path.join(siteRoot, \"node_modules\", \".vite\");\n\t\tconst storePath = path.join(siteRoot, \"node_modules\", STORE_NAME);\n\n\t\tconst fingerprint = fingerprintWorkspacePackages(siteRoot, workspaceRoot);\n\t\tif (fingerprint === undefined) return false;\n\n\t\tconst previous = readStore(storePath);\n\n\t\tlet cleared = false;\n\t\tif (existsSync(cacheDir) && previous !== fingerprint) {\n\t\t\trmSync(cacheDir, { recursive: true, force: true });\n\t\t\tcleared = true;\n\t\t\tlog?.(\"Workspace packages changed; clearing the Vite dep cache\");\n\t\t}\n\t\twriteFileSync(storePath, JSON.stringify({ fingerprint }));\n\n\t\treturn cleared;\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t\t// Never break dev startup over cache bookkeeping\n\t\treturn false;\n\t}\n}\n\nexport function findWorkspaceRoot(from: string): string | undefined {\n\tlet dir = path.resolve(from);\n\twhile (true) {\n\t\t// pnpm-style marker, or a root package.json declaring npm workspaces\n\t\tif (existsSync(path.join(dir, \"pnpm-workspace.yaml\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tif (hasWorkspacesField(dir)) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n}\n\nfunction hasWorkspacesField(dir: string): boolean {\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (!existsSync(packageJsonPath)) return false;\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t\treturn Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readStore(storePath: string): string | undefined {\n\tif (!existsSync(storePath)) return undefined;\n\ttry {\n\t\tconst store = JSON.parse(readFileSync(storePath, \"utf8\")) as { fingerprint?: string };\n\t\treturn store.fingerprint;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Resolves every site dependency that lives inside the workspace to its\n * package folder. Shared with the other dev-startup checks (e.g. the stale\n * .torp copy report), which need the same set of packages.\n */\nexport function workspaceDependencyDirs(siteRoot: string, workspaceRoot: string): string[] {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst require = createRequire(sitePackageJson);\n\n\tconst packageDirs = new Set<string>();\n\tfor (const name of dependencyNames(pkg)) {\n\t\tconst dir = resolvePackageDir(name, require);\n\t\tif (dir && insideWorkspace(realpathSync(dir), workspaceRoot)) {\n\t\t\tpackageDirs.add(realpathSync(dir));\n\t\t}\n\t}\n\treturn [...packageDirs].sort();\n}\n\nfunction fingerprintWorkspacePackages(siteRoot: string, workspaceRoot: string): string | undefined {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return undefined;\n\n\tconst packageDirs = workspaceDependencyDirs(siteRoot, workspaceRoot);\n\tif (packageDirs.length === 0) return undefined;\n\n\tconst hash = createHash(\"sha1\");\n\tfor (let dir of packageDirs) {\n\t\thash.update(`package:${dir}\\n`);\n\t\tfingerprintDir(dir, dir, hash);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})];\n}\n\nfunction resolvePackageDir(name: string, require: NodeRequire): string | undefined {\n\ttry {\n\t\tconst packageJsonPath = require.resolve(`${name}/package.json`);\n\t\treturn path.dirname(packageJsonPath);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction insideWorkspace(dir: string, workspaceRoot: string): boolean {\n\tconst relative = path.relative(workspaceRoot, dir);\n\treturn relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction fingerprintDir(dir: string, root: string, hash: import(\"node:crypto\").Hash): void {\n\tfor (let entry of readdirSync(dir, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(dir, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tfingerprintDir(full, root, hash);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile()) continue;\n\t\tconst stats = statSync(full);\n\t\t// NOTE: hash.update takes (data, encoding) -- join into one string\n\t\thash.update(\n\t\t\t`file:${path.relative(root, full).replaceAll(\"\\\\\", \"/\")}:${stats.size}:${Math.floor(stats.mtimeMs)}\\n`,\n\t\t);\n\t}\n}\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\nimport { findWorkspaceRoot, workspaceDependencyDirs } from \"./depCache\";\n\n/**\n * Workspace packages that ship copies of their .torp components (e.g.\n * @torpor/ui copies its src .torp files into dist/ during its build) can go\n * stale: a site resolves the package to its dist folder, so edits to src\n * silently keep serving the OLD components until the package is rebuilt.\n * The symptom is confusing -- e.g. a TypeError about a renamed slot prop\n * after a component's API changed.\n *\n * reportStaleTorpCopies runs at `tb --dev` startup: for every workspace\n * dependency with both src and dist folders, it compares the .torp files and\n * reports anything missing from dist, differing from src, or left over in\n * dist without a src file.\n */\n\n/**\n * Reports stale dist .torp copies in the site's workspace dependencies.\n * Never throws -- a broken check must not break dev startup.\n */\nexport function reportStaleTorpCopies(siteRoot: string, log?: (message: string) => void): void {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return;\n\n\t\tfor (const dir of workspaceDependencyDirs(siteRoot, workspaceRoot)) {\n\t\t\tconst srcFolder = path.join(dir, \"src\");\n\t\t\tconst distFolder = path.join(dir, \"dist\");\n\t\t\t// Only packages that ship dist copies of src .torp files are\n\t\t\t// checked; packages without the folders (or with neither .torp\n\t\t\t// set) are skipped\n\t\t\tif (!existsSync(srcFolder) || !existsSync(distFolder)) continue;\n\t\t\tconst src = collectTorpFiles(srcFolder);\n\t\t\tconst dist = collectTorpFiles(distFolder);\n\t\t\tif (src.size === 0 && dist.size === 0) continue;\n\n\t\t\tconst problems: string[] = [];\n\t\t\tfor (const [rel, content] of src) {\n\t\t\t\tconst distContent = dist.get(rel);\n\t\t\t\tif (distContent === undefined) {\n\t\t\t\t\tproblems.push(`${rel} (not copied to dist)`);\n\t\t\t\t} else if (distContent !== content) {\n\t\t\t\t\tproblems.push(`${rel} (differs from src)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const rel of dist.keys()) {\n\t\t\t\tif (!src.has(rel)) {\n\t\t\t\t\tproblems.push(`${rel} (left over in dist, no src file)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (problems.length === 0) continue;\n\n\t\t\tconst shown = problems\n\t\t\t\t.slice(0, 5)\n\t\t\t\t.map((p) => ` ${p}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst more = problems.length > 5 ? `\\n ... and ${problems.length - 5} more` : \"\";\n\t\t\tlog?.(\n\t\t\t\t`${packageLabel(dir, workspaceRoot)}'s dist .torp copies are stale, so the site is ` +\n\t\t\t\t\t`serving OLD components:\\n${shown}${more}\\n` +\n\t\t\t\t\t`Rebuild the package (e.g. \\`pnpm build\\` in ` +\n\t\t\t\t\t`${path.relative(workspaceRoot, dir) || \".\"}) and restart \\`tb --dev\\`.`,\n\t\t\t);\n\t\t}\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t}\n}\n\nfunction collectTorpFiles(folder: string): Map<string, string> {\n\tconst files = new Map<string, string>();\n\tcollect(folder, folder, files);\n\treturn files;\n}\n\nfunction collect(folder: string, root: string, files: Map<string, string>): void {\n\tfor (const entry of readdirSync(folder, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(folder, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tcollect(full, root, files);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile() || !entry.name.endsWith(\".torp\")) continue;\n\t\tfiles.set(path.relative(root, full).replaceAll(\"\\\\\", \"/\"), readFileSync(full, \"utf8\"));\n\t}\n}\n\nfunction packageLabel(dir: string, workspaceRoot: string): string {\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n\t\tif (pkg.name) return pkg.name;\n\t} catch {\n\t\t// Fall through to the relative path\n\t}\n\treturn path.relative(workspaceRoot, dir) || dir;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n\ttype AliasOptions,\n\tcreateServer as createViteServer,\n\ttype Plugin,\n\ttype ViteDevServer,\n} from \"vite\";\nimport Site from \"../site/Site.ts\";\nimport {\n\tcheckApiCallSource,\n\tcheckApiCalls,\n\tcheckRoute,\n\tcheckRoutes,\n\tcreateApiCallCheck,\n\ttype RouteCheckIssue,\n\treportRouteIssues,\n} from \"../site/checkRoutes\";\nimport manifest from \"../site/manifest.ts\";\nimport { checkLayoutSlot, checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { detectSourceMode, siteEntryPaths } from \"../utils/entryPaths\";\nimport devPlugin from \"./devPlugin.ts\";\nimport { clearStaleDepCache } from \"./depCache\";\nimport { reportStaleTorpCopies } from \"./staleTorpCopies\";\n\nexport default async function runDev(site: Site): Promise<void> {\n\t// Create the Vite dev server. Unlike the previous middleware-mode setup, we\n\t// let Vite own the HTTP server (so HMR/websockets work natively) and let the\n\t// adapter's `dev()` plugin(s) handle SSR via configureServer.\n\tconst config = structuredClone(site.viteConfig ?? {});\n\tconfig.appType = \"custom\";\n\tconfig.server ??= {};\n\tconfig.server.host ??= \"localhost\";\n\t// Root-level host files (robots.txt, favicon.ico, etc) in src/public are\n\t// served by Vite's middleware in dev and copied into the build output\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tconfig.publicDir = publicDir;\n\t}\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\tconfig.resolve ??= {};\n\tconfig.resolve.tsconfigPaths ??= true;\n\t// When the framework itself is linked into the app (workspace/link:\n\t// installs), resolve `@torpor/view` and `@torpor/build/dev` from source via\n\t// their `torpor:source` export conditions, so framework changes take effect\n\t// without rebuilding dist. Registry installs run the compiled dist.\n\t//\n\t// Note: this must be a custom condition, not Vite's built-in `development`\n\t// one — Vite's dev server activates `development` by default, which made\n\t// registry installs resolve the unpublished `src/` files and fail.\n\tconst sourceMode = detectSourceMode(site.root);\n\tif (sourceMode) {\n\t\tconfig.resolve.conditions ??= [];\n\t\tconfig.resolve.conditions.push(\"torpor:source\");\n\t}\n\t// vite-plus' `tsconfigPaths` isn't honored by the SSR module-runner's\n\t// externalization path (it hardcodes tsconfigPaths:false), so dev SSR can't\n\t// resolve path aliases. Mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` so they resolve during transform for both client and SSR.\n\tconfig.resolve.alias = [...asAliasArray(config.resolve.alias), ...tsconfigAliases(site.root)];\n\n\t// The adapter provides the dev-runtime plugin(s); fall back to the\n\t// framework's Node-runtime plugin when it doesn't.\n\tconst adapterDev = site.adapter.dev?.(site);\n\tconst devPlugins = normalizePlugins(adapterDev ?? devPlugin(site, sourceMode));\n\n\tconfig.plugins = [\n\t\tmanifest(site, true),\n\t\ttorpor({ dev: true }),\n\t\t...devPlugins,\n\t\t...site.vitePlugins,\n\t];\n\n\t// HACK: To be able to import `.torp` files from barrel files in\n\t// node_modules, we need to add their libraries to `ssr.noExternal` in\n\t// site.config.ts, and let the dep optimizer know how to compile them\n\t// here. The optimizer is a rolldown build, so it needs a rolldown-shaped\n\t// plugin (the vite export) -- an esbuild-shaped one is silently ignored\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.extensions ??= [];\n\tconfig.optimizeDeps.extensions.push(\".torp\");\n\tconfig.optimizeDeps.rolldownOptions ??= {};\n\tconfig.optimizeDeps.rolldownOptions.plugins ??= [torpor()];\n\n\t// Packages that ship `.torp` files (e.g. icon libraries) need the torpor\n\t// compiler: dep optimization would parse them as plain JavaScript and\n\t// fail, and SSR externalization would leave raw `.torp` imports that\n\t// Node/workerd can't load. Exclude them from optimization and mark them\n\t// for SSR bundling so they go through the torpor plugin\n\taddTorporPackageConfig(site.root, config);\n\n\t// Workspace packages may have been rebuilt since the last dev run; drop\n\t// Vite's dep cache so SSR never executes stale prebundled modules\n\tclearStaleDepCache(site.root, (message) => console.log(`\\n${message}`));\n\n\t// A workspace package with dist .torp copies (e.g. @torpor/ui) whose src\n\t// changed without a rebuild serves OLD components to the site, silently;\n\t// report the drift so it can be fixed with a rebuild\n\treportStaleTorpCopies(site.root, (message) => console.log(`\\n${message}`));\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Honor PORT (env or .env) for the dev server port, matching --preview;\n\t// fall back to the default when it doesn't parse to a number\n\tconst envPort = parseInt(process.env.PORT);\n\tif (!Number.isNaN(envPort)) {\n\t\tconfig.server.port ??= envPort;\n\t}\n\n\tconst connectingUrl = `${process.env.PROTOCOL}//${process.env.HOST}:${process.env.PORT}`;\n\tconsole.log(`\\nConnecting to ${connectingUrl}`);\n\n\tconst vite = await createViteServer(config);\n\n\t// Load the SSR entry once before binding the listener: it triggers Vite's\n\t// first dependency optimization, which otherwise settles down (reloading\n\t// the server) right after \"Listening on ...\" -- dropping any request in\n\t// flight at that moment, so clients see an empty reply\n\tawait warmServerEntry(vite, site, sourceMode);\n\n\tawait vite.listen();\n\n\twatchRouteTypes(site, vite);\n\n\tconst listeningUrl = vite.resolvedUrls?.local?.[0] ?? connectingUrl;\n\tconsole.log(`Listening on ${listeningUrl}\\n`);\n}\n\n/**\n * Loads the SSR entry so the first dependency optimization (and any\n * optimizer-driven server reload) happens before the listener is bound,\n * rather than on the first real request.\n */\nasync function warmServerEntry(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<void> {\n\ttry {\n\t\tconst { serverEntry } = siteEntryPaths(site.root, sourceMode);\n\t\tawait vite.ssrLoadModule(serverEntry);\n\t} catch (e) {\n\t\t// Never block startup over warmup -- the first real request surfaces\n\t\t// errors as before\n\t\tif (process.env.TORPOR_DEBUG_WARMUP) throw e;\n\t}\n}\n\n/**\n * Reports route type issues at startup, then re-checks route files and\n * `makeApi` calls as they change so annotation problems surface during\n * development without failing the dev server.\n */\nfunction watchRouteTypes(site: Site, vite: ViteDevServer): void {\n\treportRouteIssues(checkRoutes(site));\n\treportRouteIssues(checkApiCalls(site));\n\treportRouteIssues(checkLayoutSlots(site));\n\n\t// Map absolute route file paths to their manifest entries, so changed\n\t// files can be re-checked against their derived route. Layout route files\n\t// are included for their slot check (a .torp layout is its own component)\n\tconst routeFiles = new Map(\n\t\tsite.routes\n\t\t\t.filter(\n\t\t\t\t(r) => r.file?.endsWith(\".ts\") || (r.file?.endsWith(\".torp\") && r.type === LAYOUT_ROUTE),\n\t\t\t)\n\t\t\t.map((r) => [path.resolve(site.root, r.file!), r]),\n\t);\n\tconst apiCheck = createApiCallCheck(site);\n\t// Only report when a file's issues change, to avoid repeating the same\n\t// warnings on every save\n\tconst reported = new Map<string, string>();\n\n\tconst report = (file: string, issues: RouteCheckIssue[]) => {\n\t\tconst key = JSON.stringify(issues);\n\t\tif (reported.get(file) === key) return;\n\t\treported.set(file, key);\n\t\treportRouteIssues(issues);\n\t};\n\n\tconst recheck = (file: string): void => {\n\t\tconst route = routeFiles.get(file);\n\t\tif (route) {\n\t\t\treport(\n\t\t\t\tfile,\n\t\t\t\troute.type === LAYOUT_ROUTE ? checkLayoutSlot(site, route) : checkRoute(site, route),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!/\\.(ts|js|torp)$/.test(file)) return;\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\treport(file, checkApiCallSource(source, file, apiCheck));\n\t};\n\n\tvite.watcher.on(\"change\", recheck);\n\tvite.watcher.on(\"add\", recheck);\n}\n\nfunction normalizePlugins(plugins: Plugin | Plugin[] | void): Plugin[] {\n\tif (!plugins) return [];\n\treturn Array.isArray(plugins) ? plugins : [plugins];\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n","// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".abw\": \"application/x-abiword\",\n\t\".apng\": \"image/apng\",\n\t\".arc\": \"application/x-freearc\",\n\t\".avif\": \"image/avif\",\n\t\".avi\": \"video/x-msvideo\",\n\t\".azw\": \"application/vnd.amazon.ebook\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".bz\": \"application/x-bzip\",\n\t\".bz2\": \"application/x-bzip2\",\n\t\".cda\": \"application/x-cdf\",\n\t\".csh\": \"application/x-csh\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".doc\": \"application/msword\",\n\t\".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".epub\": \"application/epub+zip\",\n\t\".gz\": \"application/gzip\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".ics\": \"text/calendar\",\n\t\".jar\": \"application/java-archive\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mid\": \"audio/midi\",\n\t\".midi\": \"audio/midi\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".mpeg\": \"video/mpeg\",\n\t\".mpkg\": \"application/vnd.apple.installer+xml\",\n\t\".odp\": \"application/vnd.oasis.opendocument.presentation\",\n\t\".ods\": \"application/vnd.oasis.opendocument.spreadsheet\",\n\t\".odt\": \"application/vnd.oasis.opendocument.text\",\n\t\".oga\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".ogx\": \"application/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".png\": \"image/png\",\n\t\".pdf\": \"application/pdf\",\n\t\".php\": \"application/x-httpd-php\",\n\t\".ppt\": \"application/vnd.ms-powerpoint\",\n\t\".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n\t\".rar\": \"application/vnd.rar\",\n\t\".rtf\": \"application/rtf\",\n\t\".sh\": \"application/x-sh\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".tif\": \"image/tiff\",\n\t\".tiff\": \"image/tiff\",\n\t\".ts\": \"video/mp2t\",\n\t\".ttf\": \"font/ttf\",\n\t\".txt\": \"text/plain\",\n\t\".vsd\": \"application/vnd.visio\",\n\t\".wav\": \"audio/wav\",\n\t\".weba\": \"audio/webm\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xhtml\": \"application/xhtml+xml\",\n\t\".xls\": \"application/vnd.ms-excel\",\n\t\".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\".xml\": \"application/xml\",\n\t\".xul\": \"application/vnd.mozilla.xul+xml\",\n\t\".zip\": \"application/zip\",\n\t\".3gp\": \"video/3gpp\",\n\t\".3g2\": \"video/3gpp2\",\n\t\".7z\": \"application/x-7z-compressed\",\n};\n","import { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport contentType from \"../server/contentType.ts\";\nimport Site from \"../site/Site\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\nimport runBuild from \"./runBuild\";\n\nexport default async function runPreview(site: Site): Promise<void> {\n\t// Build the site\n\tawait runBuild(site);\n\n\tconst distFolder = path.resolve(site.root, \"dist\");\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// Read site.html if present, and find the client script file in /assets.\n\t// An endpoints-only site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tlet clientScript = (await fs.readdir(path.join(clientFolder, \"assets\"))).find((f) =>\n\t\t\tf.startsWith(\"clientEntry-\"),\n\t\t);\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\tclientScript = `/assets/${clientScript}`;\n\n\t\ttemplate = await fs.readFile(siteHtml, \"utf-8\");\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, clientScript);\n\t}\n\n\t// Configure the server\n\tconst server = new Server();\n\n\t// Serve dist/client/assets statically\n\tserver.add(\"/assets/*\", async (ev) => {\n\t\ttry {\n\t\t\tconst url = new URL(ev.request.url);\n\t\t\tconst file = path.join(site.root, \"dist\", \"client\", url.pathname);\n\t\t\tif (existsSync(file)) {\n\t\t\t\tconst body = await fs.readFile(file);\n\t\t\t\treturn new Response(body, {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": contentType(path.extname(file)),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tconst serverScript = path.resolve(serverFolder, \"serverEntry.js\");\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry\n\t\t\tconst { load } = await import(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tawait site.adapter.serve(server, site);\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { createServer as createViteServer, type ViteDevServer } from \"vite\";\nimport Site from \"../site/Site\";\nimport runBuild from \"./runBuild\";\nimport runDev from \"./runDev\";\nimport runPreview from \"./runPreview\";\n\n/**\n * Looks for and loads a site.config.js/ts file in the working directory,\n * running the site's plugins. The Vite server used to load the config is\n * returned as well, so that (for example) route files can be loaded through\n * it; callers are responsible for closing it.\n */\nexport async function loadSite(folder: string): Promise<{ site: Site; vite: ViteDevServer }> {\n\t// Look for and load a site.config.js/ts file in the working directory\n\tconst jsConfigFile = path.join(folder, \"site.config.js\");\n\tconst tsConfigFile = path.join(folder, \"site.config.ts\");\n\tlet configFile = \"\";\n\tif (fs.existsSync(jsConfigFile)) {\n\t\tconfigFile = jsConfigFile;\n\t} else if (fs.existsSync(tsConfigFile)) {\n\t\tconfigFile = tsConfigFile;\n\t} else {\n\t\tthrow new Error(\"site.config file not found\");\n\t}\n\n\t// Use a temporary Vite server to load the config, so that local TS imports\n\t// (e.g. a routes.ts file) and path aliases are resolved correctly\n\tconst vite = await createViteServer({\n\t\tserver: { middlewareMode: true },\n\t\tappType: \"custom\",\n\t\tresolve: { tsconfigPaths: true },\n\t\toptimizeDeps: { noDiscovery: true },\n\t});\n\ttry {\n\t\tconst site = (await vite.ssrLoadModule(configFile)).default as Site;\n\t\tsite.configFile = configFile;\n\n\t\tif (!site || !site.root || !site.routes) {\n\t\t\tthrow new Error(\"Invalid site in config file\");\n\t\t}\n\n\t\t// Run the site's plugins. The manifest plugin also runs them when the\n\t\t// server starts up (dev SSR and production), so that plugin routes are\n\t\t// registered in the runtime as well\n\t\tfor (const plugin of site.plugins) {\n\t\t\tawait plugin(site);\n\t\t}\n\n\t\treturn { site, vite };\n\t} catch (error) {\n\t\tawait vite.close();\n\t\tthrow error;\n\t}\n}\n\nexport default async function run(\n\tfolder: string,\n\tmode: \"dev\" | \"build\" | \"preview\",\n): Promise<void> {\n\tconst { site, vite } = await loadSite(folder);\n\ttry {\n\t\tswitch (mode) {\n\t\t\tcase \"dev\": {\n\t\t\t\tawait runDev(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"build\": {\n\t\t\t\tawait runBuild(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"preview\": {\n\t\t\t\tawait runPreview(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconsole.log(\"No mode passed, running in dev\");\n\t\t\t\tawait runDev(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait vite.close();\n\t}\n}\n","import { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport buildOpenApiDocument from \"../openapi/document\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport type { OpenApiEndPoint, OpenApiRouteEntry, ResolvedOpenApiOptions } from \"../openapi/types\";\nimport type Site from \"../site/Site\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\n/**\n * Writes an OpenAPI document for the site's +server endpoints to a file.\n * Route files are loaded through the supplied Vite server, so this must be\n * called while the server from `loadSite` is still open.\n */\nexport default async function runOpenApi(\n\tsite: Site,\n\tvite: ViteDevServer,\n\toutFile = \"openapi.json\",\n): Promise<void> {\n\tconst options = site.pluginState.get(OPEN_API_STATE_KEY) as ResolvedOpenApiOptions | undefined;\n\tif (!options) {\n\t\tthrow new Error(\n\t\t\t'No OpenAPI options found. Add the openApi() plugin to site.plugins to use \"tb --openapi\"',\n\t\t);\n\t}\n\n\tconst entries: OpenApiRouteEntry[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type !== SERVER_ROUTE) {\n\t\t\tcontinue;\n\t\t}\n\t\t// Don't document the docs page itself\n\t\tif (options.docs && route.path === options.docs) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (route.endPoint && !route.file) {\n\t\t\t// Inline endpoint\n\t\t\tentries.push({ path: route.path, endPoint: route.endPoint as OpenApiEndPoint });\n\t\t} else if (route.file) {\n\t\t\tconst file = path.resolve(site.root, route.file);\n\t\t\tconst mod = await vite.ssrLoadModule(file);\n\t\t\tentries.push({ path: route.path, endPoint: mod.default });\n\t\t}\n\t}\n\n\tconst doc = buildOpenApiDocument(entries, options);\n\tawait writeFile(path.resolve(site.root, outFile), JSON.stringify(doc, null, 2) + \"\\n\");\n\n\tconsole.log(\n\t\t`OpenAPI document written to ${outFile} (${Object.keys(doc.paths ?? {}).length} paths)`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAwB,gBAAgB,MAA4B;CACnE,MAAM,OAAOA,MAAK,KAAK,MAAM,eAAe;CAC5C,IAAI;CACJ,IAAI;CACJ,IAAI;EAEH,MAAM,kBADW,KAAK,MAAM,WAAW,aAAa,MAAM,OAAO,CAAC,CACnC,CAAC,CAAC,mBAAmB,CAAC;EACrD,UAAU,gBAAgB,UAAUA,MAAK,QAAQ,MAAM,gBAAgB,OAAO,IAAI;EAClF,QAAQ,gBAAgB;CACzB,QAAQ;EACP,OAAO,CAAC;CACT;CACA,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,UAAwB,CAAC;CAC/B,KAAK,MAAM,CAAC,SAAS,YAAY,OAAO,QAAQ,KAAK,GAAG;EACvD,MA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IAAI,MACT,4FACD;CAGD,MAAM,UAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,KAAK,QAAQ;EAChC,IAAI,MAAM,SAAA,GACT;EAGD,IAAI,QAAQ,QAAQ,MAAM,SAAS,QAAQ,MAC1C;EAED,IAAI,MAAM,YAAY,CAAC,MAAM,MAE5B,QAAQ,KAAK;GAAE,MAAM,MAAM;GAAM,UAAU,MAAM;EAA4B,CAAC;OACxE,IAAI,MAAM,MAAM;GACtB,MAAM,OAAOC,MAAK,QAAQ,KAAK,MAAM,MAAM,IAAI;GAC/C,MAAM,MAAM,MAAM,KAAK,cAAc,IAAI;GACzC,QAAQ,KAAK;IAAE,MAAM,MAAM;IAAM,UAAU,IAAI;GAAQ,CAAC;EACzD;CACD;CAEA,MAAM,MAAM,qBAAqB,SAAS,OAAO;CACjD,MAAM,UAAUA,MAAK,QAAQ,KAAK,MAAM,OAAO,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,IAAI;CAErF,QAAQ,IACP,+BAA+B,QAAQ,IAAI,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,QAChF;AACD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"serverHandlers-C8qzOSX-.mjs","names":[],"sources":["../src/form/formDataToRecord.ts","../src/state/$serverPage.ts","../src/utils/searchParamsToRecord.ts","../src/validation/endpoint.ts","../src/site/layoutSlots.ts","../src/site/mergeHead.ts","../src/site/serverHandlers.ts"],"sourcesContent":["import type { FormDataRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts the submitted fields of a form request into a plain record: one\n * value per field, or an array when a field was submitted with multiple\n * values (e.g. a multi select). File inputs pass through as `File` values;\n * coercing them is left to the schema or the action.\n *\n * @param request The request (or FormData directly)\n * @returns The field values\n */\nexport default async function formDataToRecord(\n\trequest: Request | FormData,\n): Promise<FormDataRecord> {\n\tconst formData = request instanceof FormData ? request : await request.formData();\n\tconst result: FormDataRecord = {};\n\tfor (const key of formData.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = formData.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import { $watch } from \"@torpor/view/ssr\";\nimport type PageState from \"../types/PageState\";\n\nconst PAGE_SYMBOL: unique symbol = Symbol.for(\"torp.Page\");\n\n// The server request path has no reactive subscribers, so the state is\n// stored plainly ($watch from `@torpor/view/ssr` is a no-op that returns\n// the object itself) instead of through a reactive proxy. Shares the same\n// `globalThis` slot as the client `$page`, so both variants always see the\n// same state object whichever loads first.\nconst $page: PageState =\n\t// @ts-ignore\n\t(globalThis[PAGE_SYMBOL] ??= $watch({\n\t\tstatus: 404,\n\t\turl: new URL(\"http://localhost\"),\n\t\tform: undefined,\n\t\tflash: undefined,\n\t\terror: {\n\t\t\tmessage: \"\",\n\t\t},\n\t}));\n\nexport default $page;\n","import type { QueryRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts a URL's query string into a plain record: one string per param,\n * or an array when a param was repeated.\n *\n * @param searchParams The URL's search params\n * @returns The param values\n */\nexport default function searchParamsToRecord(searchParams: URLSearchParams): QueryRecord {\n\tconst result: QueryRecord = {};\n\tfor (const key of searchParams.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = searchParams.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport type ServerEndPoint from \"../types/ServerEndPoint\";\nimport type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type ServerEvent from \"../server/ServerEvent\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord\";\nimport unprocessable from \"../response/unprocessable\";\nimport ValidationError from \"./ValidationError\";\nimport validate from \"./validate\";\n\n/**\n * Loose views of an endpoint's schema map, keyed by handler/action name (plus\n * the reserved `params` key). The type-level constraint differs per endpoint\n * type, but the runtime treats them the same.\n */\ntype Schemas = Record<string, StandardSchemaV1 | undefined>;\n\ntype EndPoint = ServerEndPoint | PageServerEndPoint;\n\n/**\n * Gets the standard schema declared for a handler or action, if any. The\n * schemas map is keyed by name; the runtime treats it as a loose record.\n */\nexport function endpointSchema(endPoint: EndPoint, name: string): StandardSchemaV1 | undefined {\n\treturn (endPoint.schema as Schemas | undefined)?.[name];\n}\n\n/**\n * Validates the route params against the endpoint's `params` schema, if it\n * declares one, returning the coerced params. Throws a ValidationError when\n * they don't match, which callers turn into a 404 (params come from the URL,\n * so a failed validation means the resource doesn't exist).\n *\n * @param endPoint The endpoint declaring the (optional) `params` schema\n * @param params The route params from the matched route\n * @returns The validated params\n */\nexport async function validateEndpointParams(\n\tendPoint: EndPoint,\n\tparams: Record<string, any>,\n): Promise<Record<string, any>> {\n\tconst schema = endpointSchema(endPoint, \"params\");\n\treturn schema ? ((await validate(schema, params)) as Record<string, any>) : params;\n}\n\n/**\n * Validates a handler's input against its schema: get/head handlers and load\n * functions validate the URL's query string, other handlers validate the JSON\n * request body. Returns the validated values (an empty object when no schema\n * is declared), which callers pass through to the handler's event.\n *\n * @param schema The handler's (optional) schema\n * @param functionName The handler name (`get`, `post`, `load`, etc)\n * @param url The request URL, for the query string\n * @param ev The server event, for the request body\n * @returns The validated values\n */\nexport async function validateHandlerInput(\n\tschema: StandardSchemaV1 | undefined,\n\tfunctionName: string,\n\turl: URL,\n\tev: ServerEvent,\n): Promise<{ json?: unknown; form?: unknown; query?: unknown }> {\n\tif (!schema) return {};\n\tif (functionName === \"get\" || functionName === \"head\" || functionName === \"load\") {\n\t\treturn { query: await validate(schema, searchParamsToRecord(url.searchParams)) };\n\t}\n\treturn { json: await validate(schema, await ev.json()) };\n}\n\n/**\n * Turns a ValidationError thrown during endpoint validation into a 422\n * response with the schema's issues. Returns undefined for any other error,\n * which callers should rethrow.\n *\n * @param error The error thrown by a handler or validation\n * @returns A 422 response, or undefined when the error isn't a validation failure\n */\nexport function validationErrorResponse(error: unknown): Response | undefined {\n\tif (error instanceof ValidationError) {\n\t\treturn unprocessable({ message: error.message, issues: error.issues });\n\t}\n\treturn undefined;\n}\n","/**\n * Layouts are composed by the layout engine passing each layout (and finally\n * the page) as the default slot of its parent — so every `_layout` component\n * must render `<slot />`, or pass the default slot down to a child component\n * it renders. A layout that doesn't drops its entire content: the server\n * renders the layout's own markup with an empty content area (no error), and\n * the first client-side navigation that reuses the layout crashes on a null\n * slot region.\n *\n * The static `checkLayoutSlots` check catches this at build/dev time; these\n * helpers report it at request time for the cases static analysis can't see\n * (e.g. a `<slot />` rendered conditionally inside `@if`). They are\n * server-side only — nothing here is imported into the client bundle.\n */\n\n/**\n * Returns the path of the outermost layout that never rendered its\n * `<slot />`, or undefined when every level rendered.\n *\n * Slot level j (1-based) is the slot render that layout j - 1 receives: the\n * root layout (layouts[0]) renders level 1, layout i renders level i + 1,\n * and level layouts.length renders the page. A broken level makes every\n * deeper level unreachable, so the first level that never ran identifies\n * the offending layout.\n */\nexport function findMissingSlotLayout(\n\tlayouts: readonly { path: string }[],\n\tinvokedLevels: ReadonlySet<number>,\n): string | undefined {\n\tfor (let level = 1; level <= layouts.length; level++) {\n\t\tif (!invokedLevels.has(level)) {\n\t\t\treturn layouts[level - 1].path;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst warnedLayouts = new Set<string>();\n\n/**\n * Reports a layout that dropped its slot content. The condition is a genuine\n * rendering bug (the page content is missing from the output), so it is not\n * dev-gated — but it warns only once per layout path to avoid per-request\n * noise.\n */ export function warnMissingSlotContent(layoutPath: string): void {\n\tif (warnedLayouts.has(layoutPath)) return;\n\twarnedLayouts.add(layoutPath);\n\tconsole.warn(\n\t\t`[torpor] The layout at \"${layoutPath}\" never rendered <slot />, so the page content ` +\n\t\t\t`was not included in the render. Every _layout component must render <slot /> (or ` +\n\t\t\t`pass the default slot down to a child component it renders).`,\n\t);\n}\n","const TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/g;\nconst FIRST_TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/;\n\n/**\n * Merges the head string rendered by a page (and its layouts) into the site\n * template. The first <title> in the head string -- the page's, since pages\n * render before the layouts around them -- wins, overriding both any later\n * component title (e.g. from a child component) and a static <title> in the\n * template itself. All other head content (styles, meta elements, etc) is\n * appended where %COMPONENT_HEAD% sits in the template, before </head>.\n */\nexport default function mergeHead(template: string, head: string): string {\n\tconst titles = head.match(TITLE_REGEX);\n\tlet html = template;\n\tlet headHtml = head;\n\tif (titles?.length) {\n\t\theadHtml = head.replace(TITLE_REGEX, \"\");\n\t\thtml = html.replace(FIRST_TITLE_REGEX, \"\");\n\t\theadHtml = titles[0] + headHtml;\n\t}\n\treturn html.replace(\"%COMPONENT_HEAD%\", headHtml);\n}\n","import { type ServerComponent, type ServerSlotRender } from \"@torpor/view/ssr\";\nimport formDataToRecord from \"../form/formDataToRecord.ts\";\nimport notFound from \"../response/notFound.ts\";\nimport ok from \"../response/ok.ts\";\nimport seeOther from \"../response/seeOther.ts\";\nimport ServerEvent from \"../server/ServerEvent.ts\";\nimport type MiddlewareFunction from \"../server/types/MiddlewareFunction\";\nimport $page from \"../state/$serverPage.ts\";\nimport type PageEndPoint from \"../types/PageEndPoint.ts\";\nimport type { HeadElement } from \"../types/PageEndPoint.ts\";\nimport type PageLoadEvent from \"../types/PageLoadEvent.ts\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint.ts\";\nimport type RouteHandler from \"../types/RouteHandler.ts\";\nimport type ServerRequest from \"../types/ServerRequest.ts\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport type ServerEndPoint from \"../types/ServerEndPoint.ts\";\nimport type ServerHook from \"../types/ServerHook.ts\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent.ts\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord.ts\";\nimport validate from \"../validation/validate.ts\";\nimport ValidationError from \"../validation/ValidationError.ts\";\nimport {\n\tendpointSchema,\n\tvalidateEndpointParams,\n\tvalidationErrorResponse,\n} from \"../validation/endpoint.ts\";\nimport { findMissingSlotLayout, warnMissingSlotContent } from \"./layoutSlots.ts\";\nimport { getBasePath, rewriteBaseInHtml, setBasePath, stripBaseFromUrl } from \"./basePath.ts\";\nimport mergeHead from \"./mergeHead.ts\";\nimport type Router from \"./Router.ts\";\n\n/**\n * The site's request handler, as created by `createServerLoad`.\n */\nexport type ServerLoad = (ev: ServerEvent, template?: string) => Promise<Response>;\n\n/**\n * Creates the site's request handler for the given router. This is kept\n * separate from serverEntry, which imports the virtual\n * `@torpor/build/manifest` module (it only exists when a site runs or\n * builds), so that tests can exercise the handlers with their own routes.\n *\n * @param router The router, built from the site's routes\n * @param basePath The site's base path, stripped from incoming URLs before\n * routing (see basePath.ts)\n * @param middleware Global middleware (from `site.middleware`), run for\n * every request before routing -- including requests that won't match a\n * route\n * @returns The request handler, which takes the site template\n */\nexport function createServerLoad(\n\trouter: Router,\n\tbasePath = \"\",\n\tmiddleware: MiddlewareFunction[] = [],\n): ServerLoad {\n\t// The base path is shared through module state, so that everything that\n\t// generates URLs (HTML attributes, redirect locations) sees the same\n\t// value the router strips\n\tsetBasePath(basePath);\n\n\tconst handle = async (ev: ServerEvent, template?: string): Promise<Response> => {\n\t\t// The base is stripped before routing, so that everything below (route\n\t\t// matching, params, user code reading `event.url`) is base-free.\n\t\t// Requests that don't carry the base aren't ours\n\t\tconst url = stripBaseFromUrl(ev.url, basePath);\n\t\tif (!url) {\n\t\t\treturn handleResponse(notFound());\n\t\t}\n\t\tconst path = url.pathname;\n\t\tconst query = url.searchParams;\n\n\t\t//console.log(`handling ${ev.request.method} for '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\t\tlet route = router.match(path, query);\n\t\tif (!route) {\n\t\t\t// If the route wasn't found, the user may be posting a form to a\n\t\t\t// +page.server.ts route that doesn't have a corresponding +page.ts\n\t\t\t// route, which is allowed, so check for that as well\n\t\t\tif (ev.request.method === \"POST\" && !path.endsWith(\"/~server\")) {\n\t\t\t\tconst serverPath =\n\t\t\t\t\t(path.endsWith(\"/\") ? path.substring(0, path.length - 1) : path) + \"/~server\";\n\t\t\t\troute = router.match(serverPath, query);\n\t\t\t}\n\t\t}\n\t\tif (!route) {\n\t\t\treturn handleResponse(notFound());\n\t\t}\n\t\tconst handler = route.handler;\n\t\tconst params = route.params || {};\n\n\t\t// Route middleware, declared on the route's server endpoint\n\t\t// (+page.server.ts / +server.ts). Runs after the global middleware and\n\t\t// before folder hooks, so a guard can skip data loading entirely\n\t\tconst routeMiddleware: MiddlewareFunction[] = [];\n\t\tconst endPointModule = handler.serverEndPoint\n\t\t\t? (await handler.serverEndPoint())?.default\n\t\t\t: handler.type === PAGE_SERVER_ROUTE || handler.type === SERVER_ROUTE\n\t\t\t\t? (await resolveModule(handler))?.default\n\t\t\t\t: undefined;\n\t\tif (Array.isArray(endPointModule?.middleware)) {\n\t\t\trouteMiddleware.push(...endPointModule.middleware);\n\t\t}\n\n\t\t// Update $page before building the components\n\t\t$page.url = url;\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t}\n\n\t\t// TODO: Hit the server hook out here\n\t\t// We could maybe set up data loading as middleware on a route??????\n\n\t\t// Run the route's middleware around the handler: enter hooks in order\n\t\t// (a Response short-circuits the request), exit hooks in reverse\n\t\tlet enteredRoute = 0;\n\t\tlet routeResponse: Response | undefined = undefined;\n\t\ttry {\n\t\t\tfor (; enteredRoute < routeMiddleware.length && !routeResponse; enteredRoute++) {\n\t\t\t\tconst result = await routeMiddleware[enteredRoute].enter?.(ev);\n\t\t\t\tif (result) {\n\t\t\t\t\trouteResponse = result;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (routeResponse) {\n\t\t\t\treturn routeResponse;\n\t\t\t}\n\n\t\t\tswitch (handler.type) {\n\t\t\t\tcase PAGE_ROUTE:\n\t\t\t\tcase LAYOUT_ROUTE: {\n\t\t\t\t\t// It's a /+page.ts or /_layout.ts endpoint\n\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\treturn handleResponse(await loadView(ev, url, handler, params, template));\n\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\t// The server end point comes from the sibling /+page.server.ts, if applicable\n\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\t\t\thandler.serverEndPoint && (await handler.serverEndPoint()).default;\n\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase PAGE_SERVER_ROUTE:\n\t\t\t\tcase LAYOUT_SERVER_ROUTE: {\n\t\t\t\t\t// It's a /+page.server.ts or /_layout.server.ts endpoint\n\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\treturn await loadData(ev, url, handler, \"load\", params);\n\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined = (await resolveModule(handler))\n\t\t\t\t\t\t\t.default;\n\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase SERVER_ROUTE: {\n\t\t\t\t\t// It's a /+server.ts endpoint\n\t\t\t\t\tconst functionName = ev.request.method.toLowerCase().replace(\"delete\", \"del\");\n\t\t\t\t\treturn await loadData(ev, url, handler, functionName, params);\n\t\t\t\t}\n\t\t\t\tcase HOOK_ROUTE:\n\t\t\t\tcase HOOK_SERVER_ROUTE: {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase ERROR_ROUTE: {\n\t\t\t\t\treturn await loadView(ev, url, handler, params, template);\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\twhile (enteredRoute > 0) {\n\t\t\t\tenteredRoute--;\n\t\t\t\tawait routeMiddleware[enteredRoute].exit?.(ev);\n\t\t\t}\n\t\t}\n\n\t\treturn notFound();\n\t};\n\n\treturn async function load(ev: ServerEvent, template?: string): Promise<Response> {\n\t\t// Global middleware, from `site.middleware`: runs for every request\n\t\t// before routing, including ones that won't match a route\n\t\t// (maintenance mode, legacy url redirects, etc)\n\t\tlet entered = 0;\n\t\ttry {\n\t\t\tlet response: Response | undefined = undefined;\n\t\t\tfor (; entered < middleware.length && !response; entered++) {\n\t\t\t\tconst result = await middleware[entered].enter?.(ev);\n\t\t\t\tif (result) {\n\t\t\t\t\tresponse = result;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (response) {\n\t\t\t\treturn response;\n\t\t\t}\n\t\t\treturn await handle(ev, template);\n\t\t} catch (error) {\n\t\t\t// Middleware exits can inspect (and replace, in Server.fetch) the\n\t\t\t// error via `ev.error`\n\t\t\tev.error = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\twhile (entered > 0) {\n\t\t\t\tentered--;\n\t\t\t\tawait middleware[entered].exit?.(ev);\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * Resolves the route's endpoint module, caching it on the handler so warm\n * requests don't pay for the loader promise.\n */\nasync function resolveModule(handler: RouteHandler): Promise<any> {\n\treturn (handler.resolvedModule ??= await (handler.modulePromise ??= handler.endPoint()));\n}\n\nasync function loadServerHooks(handler: RouteHandler): Promise<ServerHook[]> {\n\tif (!handler.serverHooks) return [];\n\t// Resolve each hook module once and cache the result on the handler\n\treturn (handler.resolvedHooks ??= Promise.all(\n\t\thandler.serverHooks.map(async (load) => (await load()).default),\n\t));\n}\n\nasync function handleResponse(response: Response, fromForm = false): Promise<Response> {\n\t$page.status = response.status;\n\n\t// Success codes and redirect codes are acceptable\n\tif (response.status >= 200 && response.status <= 399) {\n\t\treturn response;\n\t}\n\n\t// 4xx error codes are acceptable from form actions\n\tif (fromForm && response.status >= 400 && response.status <= 499) {\n\t\treturn response;\n\t}\n\n\t// It's an error, so redirect to the error page\n\t// We're just pushing the status and message in the URL, but maybe there's a\n\t// more sophisticated way to do this?\n\t// TODO: Should be returning loadView rather than redirecting\n\t// TODO: Should be returning the NEAREST error page to this path, including layouts\n\tlet params = new URLSearchParams();\n\tparams.append(\"status\", $page.status.toString());\n\tlet message = await response.text();\n\tif (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\tconst data = JSON.parse(message);\n\t\tmessage = data.message ?? message;\n\t}\n\tif (message) {\n\t\tif ($page.error) {\n\t\t\t$page.error.message = message;\n\t\t} else {\n\t\t\t$page.error = { message };\n\t\t}\n\t\tparams.append(\"message\", message);\n\t}\n\treturn seeOther(`/_error?${params.toString()}`);\n}\n\nasync function loadData(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tfunctionName: string,\n\tparams: Record<string, any>,\n) {\n\t// The endpoint module is cached on the handler, so once warm this is a\n\t// plain property read\n\tconst mod = handler.resolvedModule ?? (await resolveModule(handler));\n\tconst serverEndPoint: ServerEndPoint | undefined = mod?.default;\n\t// `functionName` is computed from the request method, so the handlers are\n\t// accessed through a loose record\n\tconst handlerFn = (\n\t\tserverEndPoint as unknown as Record<string, ServerRequest | undefined> | undefined\n\t)?.[functionName];\n\tif (!serverEndPoint || !handlerFn) {\n\t\treturn notFound();\n\t}\n\n\t// Route params come from the URL, so a failed validation means the\n\t// resource doesn't exist. Only endpoints declaring a params schema pay\n\t// for validation\n\tconst paramsSchema = endpointSchema(serverEndPoint, \"params\");\n\tif (paramsSchema) {\n\t\ttry {\n\t\t\tparams = (await validate(paramsSchema, params)) as Record<string, any>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\ttry {\n\t\t// If the endpoint declares a schema for this handler, validate its\n\t\t// input up front and reject with 422 if it fails. get/head/load\n\t\t// schemas validate the query string; other schemas validate the json\n\t\t// body. Endpoints without a schema skip straight to the handler\n\t\tconst schema = endpointSchema(serverEndPoint, functionName);\n\t\tconst values = schema\n\t\t\t? functionName === \"get\" || functionName === \"head\" || functionName === \"load\"\n\t\t\t\t? { query: await validate(schema, searchParamsToRecord(url.searchParams)) }\n\t\t\t\t: { json: await validate(schema, await ev.json()) }\n\t\t\t: {};\n\n\t\tconst serverParams = buildServerParams(ev, url, params, values);\n\n\t\t// Hooks are resolved once per handler; routes without hooks don't\n\t\t// await anything here\n\t\tconst hooks = handler.serverHooks ? await loadServerHooks(handler) : [];\n\n\t\tlet entered = 0;\n\t\tlet enterResponse: Response | undefined = undefined;\n\t\ttry {\n\t\t\t// Hooks run from the root down; a hook's enter can return a\n\t\t\t// Response to short-circuit the request\n\t\t\tfor (; entered < hooks.length && !enterResponse; entered++) {\n\t\t\t\tconst hookResult = await hooks[entered].enter?.(serverParams);\n\t\t\t\tif (hookResult) {\n\t\t\t\t\tenterResponse = hookResult;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// A hook's enter response short-circuits the request; otherwise, if\n\t\t\t// there was no response returned from load (such as errors or a\n\t\t\t// redirect), send an ok response\n\t\t\treturn enterResponse || (await handlerFn(serverParams)) || ok();\n\t\t} finally {\n\t\t\t// Run exit hooks in reverse order for hooks that were entered\n\t\t\twhile (entered > 0) {\n\t\t\t\tentered--;\n\t\t\t\tawait hooks[entered].exit?.(serverParams);\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tconst response = validationErrorResponse(error);\n\t\tif (response) return response;\n\t\tthrow error;\n\t}\n}\n\nasync function loadView(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, any>,\n\ttemplate: string | undefined,\n\tformStatus?: number,\n\tform?: Record<string, string | number>,\n\tfromForm?: boolean,\n\t// The appData that the server hooks populated around the form action,\n\t// passed through so the re-render's loads see the same data\n\tappData?: Record<string, any>,\n) {\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await resolveModule(handler)).default;\n\tif (!clientEndPoint?.component) {\n\t\treturn notFound();\n\t}\n\n\t// Consume the flash message when a page is rendered (but not for API\n\t// requests), so that the following page -- and only that page -- can show\n\t// it. For a form action that re-renders instead of redirecting, the\n\t// message is set and read within this request\n\t$page.flash = ev.flash.get();\n\n\t// The template comes from site.html, which endpoints-only sites don't have\n\tif (!template) {\n\t\tthrow new Error(\n\t\t\t\"Page routes require a src/site.html file, which was not found; add it, or remove page/layout routes to serve endpoints only\",\n\t\t);\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await handler.serverEndPoint())?.default;\n\n\t// Validate the route params and the load query against the server\n\t// endpoint's schemas, if it declares any. Params come from the URL, so a\n\t// failed validation means the resource doesn't exist; a failed query goes\n\t// to the error page like any other load failure\n\tlet query: unknown;\n\tif (serverEndPoint) {\n\t\ttry {\n\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t\tconst loadSchema = endpointSchema(serverEndPoint, \"load\");\n\t\tif (loadSchema) {\n\t\t\tconst queryRecord = searchParamsToRecord(url.searchParams);\n\t\t\ttry {\n\t\t\t\tquery = await validate(loadSchema, queryRecord);\n\t\t\t} catch (error) {\n\t\t\t\t// A form re-render's url is the POST's, and a form action can\n\t\t\t\t// drop query params that the load schema requires, so failing\n\t\t\t\t// validation here would lose the form errors. Fall back to the\n\t\t\t\t// raw query values instead and let the load make of them what\n\t\t\t\t// it can\n\t\t\t\tif (fromForm) {\n\t\t\t\t\tquery = queryRecord;\n\t\t\t\t} else {\n\t\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\t\tif (response) return response;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Maybe hit the server hooks -- unless they already ran for this request,\n\t// which is the case when the view is re-rendered after a form action. In\n\t// that case the hooks' appData is passed through, so that the loads below\n\t// see the same data (e.g. the user set by an auth hook) as the action did\n\tconst serverParams = buildServerParams(ev, url, params, query ? { query } : {}, appData);\n\tconst serverHooks = fromForm ? [] : await loadServerHooks(handler);\n\tlet entered = 0;\n\tlet enterResponse: Response | undefined = undefined;\n\ttry {\n\t\t// Hooks run from the root down; a hook's enter can return a Response\n\t\t// to short-circuit the request\n\t\tfor (; entered < serverHooks.length && !enterResponse; entered++) {\n\t\t\tconst hookResult = await serverHooks[entered].enter?.(serverParams);\n\t\t\tif (hookResult) {\n\t\t\t\tenterResponse = hookResult;\n\t\t\t}\n\t\t}\n\t\tif (enterResponse) {\n\t\t\treturn enterResponse;\n\t\t}\n\n\t\t// Pass the data into $props\n\t\t// TODO: Promise.all\n\t\t// NOTE: We're loading data from top to bottom, overriding as we go, and I'm\n\t\t// not sure if this is the best way to go\n\t\tlet data = {};\n\t\tif (handler.layouts) {\n\t\t\tfor (let layout of handler.layouts) {\n\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\t\turl,\n\t\t\t\t\tparams,\n\t\t\t\t\tserverParams,\n\t\t\t\t\tdata,\n\t\t\t\t\tlayoutEndPoint,\n\t\t\t\t\tlayoutServerEndPoint,\n\t\t\t\t);\n\t\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\t\treturn layoutResponse;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlet endPointResponse = await loadClientAndServerData(\n\t\t\turl,\n\t\t\tparams,\n\t\t\tserverParams,\n\t\t\tdata,\n\t\t\tclientEndPoint,\n\t\t\tserverEndPoint,\n\t\t);\n\t\tif (endPointResponse?.ok === false) {\n\t\t\treturn endPointResponse;\n\t\t}\n\t\tlet $props: Record<string, any> = { data, form };\n\n\t\tlet styles = \"\";\n\n\t\t// If there are layouts, work our way upwards, pushing each component into\n\t\t// the default slot of its parent\n\t\t// TODO: Also handle layout server data\n\t\t// TODO: There's probably a nicer way to do this with reducers or something\n\t\tlet component = clientEndPoint.component as ServerComponent;\n\t\tlet slots: Record<string, ServerSlotRender> | undefined = undefined;\n\t\t// Which slot levels actually ran during the render below, so a layout\n\t\t// that never rendered its <slot /> (silently dropping the page\n\t\t// content) can be reported (see findMissingSlotLayout)\n\t\tconst invokedLevels = new Set<number>();\n\t\tconst trackSlot = (level: number, slot: ServerSlotRender): ServerSlotRender => {\n\t\t\treturn ($slot, $context) => {\n\t\t\t\tinvokedLevels.add(level);\n\t\t\t\treturn slot($slot, $context);\n\t\t\t};\n\t\t};\n\t\tif (handler.layouts) {\n\t\t\tlet slotFunctions: ServerSlotRender[] = [];\n\t\t\t// The last slot function will render the client component\n\t\t\tslotFunctions[handler.layouts.length] = trackSlot(\n\t\t\t\thandler.layouts.length,\n\t\t\t\tasync (_, $context) => {\n\t\t\t\t\tlet { body, head } = await (clientEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t$props,\n\t\t\t\t\t\t$context,\n\t\t\t\t\t);\n\t\t\t\t\tstyles += head;\n\t\t\t\t\treturn body;\n\t\t\t\t},\n\t\t\t);\n\t\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t\t?.default;\n\t\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\t\tif (i === 0) {\n\t\t\t\t\t\tcomponent = layoutEndPoint.component as ServerComponent;\n\t\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t\t} else {\n\t\t\t\t\t\tslotFunctions[i] = trackSlot(i, async (_, $context) => {\n\t\t\t\t\t\t\tlet { body, head } = await (layoutEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t_: slotFunctions[i + 1],\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tstyles += head;\n\t\t\t\t\t\t\treturn body;\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tlet html;\n\t\ttry {\n\t\t\tlet { body, head } = await component($props, undefined, slots);\n\n\t\t\t// Render the page's (and its layouts') head element data, if the\n\t\t\t// endpoint declared any. Layouts lose to the page (the nearest\n\t\t\t// endpoint wins, as with @head content), and everything loses to\n\t\t\t// the first title in the compiled head -- which mergeHead keeps\n\t\t\tlet headData = \"\";\n\t\t\tconst event = { url, params, data } as PageLoadEvent;\n\t\t\tconst layoutEndPoints = await Promise.all(\n\t\t\t\t(handler.layouts ?? []).map(async (layout) => await layout.endPoint()),\n\t\t\t);\n\t\t\tconst headPoints = [clientEndPoint, ...layoutEndPoints].reverse();\n\t\t\tfor (const endPoint of headPoints) {\n\t\t\t\tconst headElements =\n\t\t\t\t\ttypeof endPoint.head === \"function\" ? await endPoint.head(event) : endPoint.head;\n\t\t\t\tif (headElements) {\n\t\t\t\t\theadData += headElements.map((element: HeadElement) => markupOf(element)).join(\"\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Put the form info in a hidden input so that it can be accessed on the client\n\t\t\tif (form) {\n\t\t\t\tbody += `\\n<input type=\"hidden\" id=\"t-form-data\" value='${JSON.stringify(form).replaceAll(\"'\", \"\\\\'\")}' />`;\n\t\t\t}\n\n\t\t\tstyles += head;\n\t\t\thtml = rewriteBaseInHtml(\n\t\t\t\tmergeHead(template, styles + headData).replace(\"%COMPONENT_BODY%\", body),\n\t\t\t\tgetBasePath(),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\thtml = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\n\t\t// A layout that never rendered <slot /> silently drops the whole page\n\t\t// content from the output; find and report the outermost one\n\t\tif (handler.layouts) {\n\t\t\tconst missingLayout = findMissingSlotLayout(handler.layouts, invokedLevels);\n\t\t\tif (missingLayout !== undefined) {\n\t\t\t\twarnMissingSlotContent(missingLayout);\n\t\t\t}\n\t\t}\n\n\t\treturn new Response(html, {\n\t\t\tstatus: formStatus ?? 200,\n\t\t\theaders: {\n\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t},\n\t\t});\n\t} finally {\n\t\t// Run exit hooks in reverse order for hooks that were entered\n\t\twhile (entered > 0) {\n\t\t\tentered--;\n\t\t\tawait serverHooks[entered].exit?.(serverParams);\n\t\t}\n\t}\n}\n\nasync function runAction(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tparams: Record<string, any>,\n\tquery: URLSearchParams,\n\ttemplate: string | undefined,\n) {\n\t// The action name rides in the query, so look for a `?/name` key rather\n\t// than taking the first key -- the url may carry ordinary load query\n\t// params as well (e.g. `?page=3&/like`, or a default action posted to a\n\t// url that already has a query). A key that names a declared action also\n\t// matches (e.g. `?set`), and a form without an action attribute calls the\n\t// `default` action\n\tconst queryKeys = Array.from(query.keys());\n\tconst actionKey =\n\t\tqueryKeys.find((key) => key.startsWith(\"/\")) ??\n\t\tqueryKeys.find((key) => !!serverEndPoint?.actions?.[key.replace(/^\\//, \"\")]);\n\tconst actionName = (actionKey ?? \"default\").replace(/^\\//, \"\");\n\tif (serverEndPoint?.actions) {\n\t\tconst action = serverEndPoint.actions[actionName];\n\t\tif (action) {\n\t\t\tif (actionName === \"load\" || actionName === \"params\") {\n\t\t\t\t// These names are reserved in the endpoint's schema map: `load`\n\t\t\t\t// validates the query string and `params` the route params, so\n\t\t\t\t// an action with one of these names would get the wrong schema\n\t\t\t\t// applied to its form data\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The action name \"${actionName}\" is reserved. ` +\n\t\t\t\t\t\t`Rename the action (and its schema key, if any), e.g. to \"save\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Route params come from the URL, so a failed validation means the\n\t\t\t// resource doesn't exist\n\t\t\ttry {\n\t\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tlet result: Response | undefined | void;\n\t\t\t// The event that the hooks and action run with. It's kept around so\n\t\t\t// that the view re-render below can pass its appData (populated by\n\t\t\t// the hooks' enter functions) through to the loads\n\t\t\tlet serverParams: ServerLoadEvent | undefined = undefined;\n\t\t\ttry {\n\t\t\t\t// If the endpoint declares a schema for this action, validate the\n\t\t\t\t// submitted form data up front and reject with 422 if it fails\n\t\t\t\tconst schema = endpointSchema(serverEndPoint, actionName);\n\t\t\t\tconst form = schema\n\t\t\t\t\t? await validate(schema, await formDataToRecord(ev.request))\n\t\t\t\t\t: undefined;\n\n\t\t\t\tserverParams = buildServerParams(ev, url, params, form ? { form } : {});\n\n\t\t\t\tconst serverHooks = await loadServerHooks(handler);\n\t\t\t\tlet entered = 0;\n\t\t\t\tlet enterResponse: Response | undefined = undefined;\n\t\t\t\ttry {\n\t\t\t\t\t// Hooks run from the root down; a hook's enter can return a\n\t\t\t\t\t// Response to short-circuit the action\n\t\t\t\t\tfor (; entered < serverHooks.length && !enterResponse; entered++) {\n\t\t\t\t\t\tconst hookResult = await serverHooks[entered].enter?.(serverParams);\n\t\t\t\t\t\tif (hookResult) {\n\t\t\t\t\t\t\tenterResponse = hookResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tresult = enterResponse || (await action(serverParams));\n\t\t\t\t} finally {\n\t\t\t\t\t// Run exit hooks in reverse order for hooks that were entered\n\t\t\t\t\twhile (entered > 0) {\n\t\t\t\t\t\tentered--;\n\t\t\t\t\t\tawait serverHooks[entered].exit?.(serverParams);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\tif (response) return response;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (ev.request.headers.has(\"X-Torpor-Form-Submit\")) {\n\t\t\t\t// If the form was submitted from javascript, just return the\n\t\t\t\t// response and it will be handled on the client\n\t\t\t\t// TODO: Should we make the user return a response??\n\t\t\t\tresult ??= ok();\n\n\t\t\t\t// If it's a redirect, we need to stop the browser handling it\n\t\t\t\tif (result.status >= 300 && result.status <= 399) {\n\t\t\t\t\tconst location = result.headers.get(\"Location\") ?? \"\";\n\t\t\t\t\tresult = ok();\n\t\t\t\t\tresult.headers.set(\"X-Torpor-Form-Redirect\", \"\");\n\t\t\t\t\tresult.headers.set(\"Location\", location);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} else if (\n\t\t\t\t!result ||\n\t\t\t\t(result.status >= 200 && result.status <= 299) ||\n\t\t\t\t(result.status >= 400 && result.status <= 499)\n\t\t\t) {\n\t\t\t\t// If the form was submitted without javascript, and there was\n\t\t\t\t// no result, an ok result, or a 4xx error, re-render the view\n\t\t\t\t// with the form result. The server hooks already ran around the\n\t\t\t\t// action, so they are not run again here -- but their appData\n\t\t\t\t// is passed through, so that loads guarding on it (e.g. an\n\t\t\t\t// auth hook's user) re-render the page instead of erroring\n\t\t\t\t// Keep the query string, so that loads validating the query see\n\t\t\t\t// the same values as the original GET. If the form action\n\t\t\t\t// dropped params that the load schema requires, loadView falls\n\t\t\t\t// back to the raw query instead of failing validation\n\t\t\t\tconst newUrl = new URL(url.pathname + url.search, url);\n\t\t\t\tconst formStatus = result?.status;\n\t\t\t\tlet formMessage = await result?.text();\n\t\t\t\tif (formMessage && result?.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t$page.form = JSON.parse(formMessage);\n\t\t\t\t\tformMessage = undefined;\n\t\t\t\t} else {\n\t\t\t\t\t$page.form = {};\n\t\t\t\t}\n\t\t\t\t// Set status and message if they haven't already been set,\n\t\t\t\t// which means that you can just return e.g. forbidden() or\n\t\t\t\t// forbidden(\"no!\") and there will be something you can work\n\t\t\t\t// with in your component, or you can set a completely custom\n\t\t\t\t// object with whatever info you need\n\t\t\t\t$page.form!.status ??= formStatus ?? 0;\n\t\t\t\t$page.form!.message ??= formMessage ?? \"\";\n\t\t\t\treturn await loadView(\n\t\t\t\t\tev,\n\t\t\t\t\tnewUrl,\n\t\t\t\t\thandler,\n\t\t\t\t\tparams,\n\t\t\t\t\ttemplate,\n\t\t\t\t\tformStatus,\n\t\t\t\t\t$page.form,\n\t\t\t\t\ttrue,\n\t\t\t\t\tserverParams?.appData,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// If the form was submitted without javascript and there was a\n\t\t\t\t// redirect or server error, just return the result to handle it\n\t\t\t\t// as normal\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\nasync function loadClientAndServerData(\n\turl: URL,\n\tparams: Record<string, any>,\n\tserverParams: ServerLoadEvent,\n\tdata: Record<string, any>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n) {\n\tif (clientEndPoint?.load) {\n\t\tconst clientParams = buildClientParams(url, params, data);\n\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\tif (clientResponse) {\n\t\t\tif (clientResponse.ok) {\n\t\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await clientResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn clientResponse;\n\t\t\t}\n\t\t}\n\t}\n\tif (serverEndPoint?.load) {\n\t\tconst serverResponse = await serverEndPoint.load(serverParams);\n\t\tif (serverResponse) {\n\t\t\tif (serverResponse.ok) {\n\t\t\t\tif (serverResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\tObject.assign(data, await serverResponse.json());\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn serverResponse;\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction buildClientParams(url: URL, params: Record<string, any>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n\nfunction buildServerParams(\n\tev: ServerEvent,\n\turl: URL,\n\tparams: Record<string, any>,\n\tvalues: { json?: unknown; form?: unknown; query?: unknown } = {},\n\tappData: Record<string, any> = {},\n): ServerLoadEvent {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tappData,\n\t\trequest: ev.request,\n\t\t// The inputs may have been validated already, in which case the request\n\t\t// body has been consumed and the parsed values are returned instead.\n\t\t// Their types come from the endpoint's schemas, so they are loosely\n\t\t// typed here\n\t\tjson: (): Promise<any> =>\n\t\t\tvalues.json !== undefined ? Promise.resolve(values.json) : ev.json(),\n\t\tform: (): Promise<any> =>\n\t\t\tvalues.form !== undefined ? Promise.resolve(values.form) : formDataToRecord(ev.request),\n\t\tquery: (): Promise<any> =>\n\t\t\tvalues.query !== undefined\n\t\t\t\t? Promise.resolve(values.query)\n\t\t\t\t: Promise.resolve(searchParamsToRecord(url.searchParams)),\n\t\tcookies: ev.cookies,\n\t\theaders: ev.headers,\n\t\tsession: ev.session,\n\t\tflash: ev.flash,\n\t\tadapter: ev.adapter,\n\t};\n}\n\n/**\n * Renders a head element as markup. Attribute values are escaped, since\n * they can come from user data (e.g. a post title passed to `seo()`).\n */\nfunction markupOf(element: HeadElement): string {\n\tif (\"title\" in element) {\n\t\treturn `<title>${escapeHtml(element.title)}</title>`;\n\t}\n\tif (\"name\" in element) {\n\t\treturn `<meta name=\"${escapeHtml(element.name)}\" content=\"${escapeHtml(element.content)}\" />`;\n\t}\n\treturn `<meta property=\"${escapeHtml(element.property)}\" content=\"${escapeHtml(element.content)}\" />`;\n}\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&\")\n\t\t.replaceAll(\"<\", \"<\")\n\t\t.replaceAll(\">\", \">\")\n\t\t.replaceAll('\"', \""\");\n}\n"],"mappings":";;;;;;;;;;;;;;AAWA,eAA8B,iBAC7B,SAC0B;CAC1B,MAAM,WAAW,mBAAmB,WAAW,UAAU,MAAM,QAAQ,SAAS;CAChF,MAAM,SAAyB,CAAC;CAChC,KAAK,MAAM,OAAO,SAAS,KAAK,GAAG;EAClC,IAAI,OAAO,QAAQ;EACnB,MAAM,SAAS,SAAS,OAAO,GAAG;EAClC,OAAO,OAAO,OAAO,SAAS,IAAI,SAAS,OAAO;CACnD;CACA,OAAO;AACR;;;ACnBA,MAAM,cAA6B,OAAO,IAAI,WAAW;AAOzD,MAAM,QAEJ,WAAW,iBAAiB,OAAO;CACnC,QAAQ;CACR,KAAK,IAAI,IAAI,kBAAkB;CAC/B,MAAM,KAAA;CACN,OAAO,KAAA;CACP,OAAO,EACN,SAAS,GACV;AACD,CAAC;;;;;;;;;;ACXF,SAAwB,qBAAqB,cAA4C;CACxF,MAAM,SAAsB,CAAC;CAC7B,KAAK,MAAM,OAAO,aAAa,KAAK,GAAG;EACtC,IAAI,OAAO,QAAQ;EACnB,MAAM,SAAS,aAAa,OAAO,GAAG;EACtC,OAAO,OAAO,OAAO,SAAS,IAAI,SAAS,OAAO;CACnD;CACA,OAAO;AACR;;;;;;;ACKA,SAAgB,eAAe,UAAoB,MAA4C;CAC9F,OAAQ,SAAS,SAAiC;AACnD;;;;;;;;;;;AAYA,eAAsB,uBACrB,UACA,QAC+B;CAC/B,MAAM,SAAS,eAAe,UAAU,QAAQ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F,aACC,OAAO,UAAU,KAAA,IACd,QAAQ,QAAQ,OAAO,KAAK,IAC5B,QAAQ,QAAQ,qBAAqB,IAAI,YAAY,CAAC;EAC1D,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,SAAS,GAAG;EACZ,OAAO,GAAG;EACV,SAAS,GAAG;CACb;AACD;;;;;AAMA,SAAS,SAAS,SAA8B;CAC/C,IAAI,WAAW,SACd,OAAO,UAAU,WAAW,QAAQ,KAAK,EAAE;CAE5C,IAAI,UAAU,SACb,OAAO,eAAe,WAAW,QAAQ,IAAI,EAAE,aAAa,WAAW,QAAQ,OAAO,EAAE;CAEzF,OAAO,mBAAmB,WAAW,QAAQ,QAAQ,EAAE,aAAa,WAAW,QAAQ,OAAO,EAAE;AACjG;AAEA,SAAS,WAAW,OAAuB;CAC1C,OAAO,MACL,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ;AAC3B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"unprocessable-D6RcYLh6.mjs","names":[],"sources":["../src/response/response.ts","../src/response/transfer.ts","../src/response/notFound.ts","../src/response/ok.ts","../src/response/seeOther.ts","../src/response/unprocessable.ts"],"sourcesContent":["/**\n * Creates a response with the supplied status code and optional body.\n *\n * If the body is an object, it will be converted to JSON and the Content-Type\n * header set to \"application/json\". Otherwise, if the body is a string, the\n * Content-Type header will be set to \"text/plain\".\n */\nexport default function response(status: number, body?: object | string): Response {\n\tlet headers: Record<string, string> | undefined = undefined;\n\tif (body) {\n\t\tif (typeof body === \"object\") {\n\t\t\theaders = { \"Content-Type\": \"application/json\" };\n\t\t\tbody = JSON.stringify(body);\n\t\t} else {\n\t\t\theaders = { \"Content-Type\": \"text/plain\" };\n\t\t}\n\t}\n\treturn new Response(body, {\n\t\tstatus,\n\t\theaders,\n\t});\n}\n","/**\n * Creates a redirect response with the supplied status code.\n */\nexport default function transfer(\n\tstatus: 300 | 301 | 302 | 303 | 304 | 307 | 308,\n\tlocation: string,\n): Response {\n\treturn new Response(null, {\n\t\tstatus,\n\t\theaders: {\n\t\t\tlocation,\n\t\t},\n\t});\n}\n","import response from \"./response\";\n\n/**\n * 404 Not Found\n *\n * The HTTP 404 Not Found client error response status code indicates that the\n * server cannot find the requested resource. Links that lead to a 404 page are\n * often called broken or dead links and can be subject to link rot.\n *\n * A 404 status code only indicates that the resource is missing without\n * indicating if this is temporary or permanent. If a resource is permanently\n * removed, servers should send the 410 Gone status instead.\n *\n * 404 errors on a website can lead to a poor user experience for your visitors,\n * so the number of broken links (internal and external) should be minimized to\n * prevent frustration for readers. Common causes of 404 responses are mistyped\n * URLs or pages that are moved or deleted without redirection. For more\n * information, see the Redirections in HTTP guide.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/404\n */\nexport default function notFound(body?: object | string): Response {\n\treturn response(404, body ?? \"Not found\");\n}\n","import type { Jsonify } from \"../types/Jsonify\";\nimport type TypedResponse from \"./TypedResponse\";\nimport response from \"./response\";\n\ntype OkResponse<T extends object | string | undefined> = T extends object\n\t? TypedResponse<Jsonify<T>>\n\t: Response;\n\n/**\n * 200 OK\n *\n * The HTTP 200 OK successful response status code indicates that a request has\n * succeeded. A 200 OK response is cacheable by default.\n *\n * A 200 OK response has a different meaning and format depending on the HTTP\n * request method. Here's how they vary for different methods:\n *\n * - GET: A resource was retrieved by the server and included in the response\n * body.\n * - POST: An action succeeded; the response has a message body describing the\n * result.\n * - HEAD: Identical to GET, except there is no message body.\n * - TRACE: The response has a message body containing the request as received\n * by the server.\n *\n * Although possible, successful PUT or DELETE requests often do not result in\n * a 200 OK response. It is more common to see 201 Created if the resource is\n * uploaded or created for the first time, or 204 No Content upon successful\n * deletion of a resource.\n *\n * An object body is typed: the client sees its JSON form through\n * `makeApi`-created callers.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/200\n */\nexport default function ok<T extends object | string | undefined>(body?: T): OkResponse<T> {\n\treturn response(200, body) as OkResponse<T>;\n}\n","import transfer from \"./transfer\";\n\n/**\n * 303 See Other\n *\n * The HTTP 303 See Other redirection response status code indicates that the\n * browser should redirect to the URL in the Location header instead of\n * rendering the requested resource.\n *\n * This response code is often sent back as a result of PUT or POST methods so\n * the client may retrieve a confirmation, or view a representation of a\n * real-world object (see HTTP range-14). The method to retrieve the redirected\n * resource is always GET.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303\n */\nexport default function seeOther(location: string): Response {\n\treturn transfer(303, location);\n}\n","import response from \"./response\";\nimport type { Jsonify } from \"../types/Jsonify\";\nimport type TypedResponse from \"./TypedResponse\";\n\ntype UnprocessableResponse<T extends object | string | undefined> = T extends object\n\t? TypedResponse<Jsonify<T>>\n\t: Response;\n\n/**\n * 422 Unprocessable Content\n *\n * The HTTP 422 Unprocessable Content client error response status code\n * indicates that the server understood the content type of the request content,\n * and the syntax of the request content was correct, but it was unable to\n * process the contained instructions.\n *\n * Clients that receive a 422 response should expect that repeating the request\n * without modification will fail with the same error.\n *\n * An object body is typed: it becomes the page's `$props.form` (with its JSON\n * form) after a form submit, so validation errors can be surfaced with their\n * field types via `PageForm`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/422\n */\nexport default function unprocessable<T extends object | string | undefined>(\n\tbody?: T,\n): UnprocessableResponse<T> {\n\treturn response(422, body ?? \"Unprocessable\") as UnprocessableResponse<T>;\n}\n"],"mappings":";;;;;;;;AAOA,SAAwB,SAAS,QAAgB,MAAkC;CAClF,IAAI,UAA8C,KAAA;CAClD,IAAI,MAAM;EACT,IAAI,OAAO,SAAS,UAAU;GAC7B,UAAU,EAAE,gBAAgB,mBAAmB;GAC/C,OAAO,KAAK,UAAU,IAAI;EAC3B,OACC,UAAU,EAAE,gBAAgB,aAAa;CAE3C;CACA,OAAO,IAAI,SAAS,MAAM;EACzB;EACA;CACD,CAAC;AACF;;;;;;AClBA,SAAwB,SACvB,QACA,UACW;CACX,OAAO,IAAI,SAAS,MAAM;EACzB;EACA,SAAS,EACR,SACD;CACD,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;ACQA,SAAwB,SAAS,MAAkC;CAClE,OAAO,SAAS,KAAK,QAAQ,WAAW;AACzC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACYA,SAAwB,GAA0C,MAAyB;CAC1F,OAAO,SAAS,KAAK,IAAI;AAC1B;;;;;;;;;;;;;;;;;ACrBA,SAAwB,SAAS,UAA4B;CAC5D,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;;;;;ACOA,SAAwB,cACvB,MAC2B;CAC3B,OAAO,SAAS,KAAK,QAAQ,eAAe;AAC7C"}
|