@torpor/build 1.2.0 → 1.4.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.
Files changed (94) hide show
  1. package/dist/MiddlewareFunction-BZilnEei.d.mts +50 -0
  2. package/dist/MiddlewareFunction-BZilnEei.d.mts.map +1 -0
  3. package/dist/{Router-COdQuVUi.d.mts → Router-dAu_5PlG.d.mts} +2 -2
  4. package/dist/{Router-COdQuVUi.d.mts.map → Router-dAu_5PlG.d.mts.map} +1 -1
  5. package/dist/{Server-Dr6yqVa5.mjs → Server-CSti9cvM.mjs} +2 -2
  6. package/dist/Server-CSti9cvM.mjs.map +1 -0
  7. package/dist/{Server-Cler2w5O.d.mts → Server-qn5Ws_d0.d.mts} +3 -23
  8. package/dist/Server-qn5Ws_d0.d.mts.map +1 -0
  9. package/dist/ServerEvent-Bh9cEpro.mjs +335 -0
  10. package/dist/ServerEvent-Bh9cEpro.mjs.map +1 -0
  11. package/dist/ServerHook-BTSGfLiJ.d.mts +21 -0
  12. package/dist/ServerHook-BTSGfLiJ.d.mts.map +1 -0
  13. package/dist/{ServerHook-BlLArueW.d.mts → ServerLoadEvent-DzbxxkF8.d.mts} +13 -21
  14. package/dist/ServerLoadEvent-DzbxxkF8.d.mts.map +1 -0
  15. package/dist/SessionHelper-MaodMaLU.d.mts +148 -0
  16. package/dist/SessionHelper-MaodMaLU.d.mts.map +1 -0
  17. package/dist/{Site-CTADVh7d.d.mts → Site-CQ29Opvm.d.mts} +96 -75
  18. package/dist/Site-CQ29Opvm.d.mts.map +1 -0
  19. package/dist/{_page-4cQKs_Dn.mjs → _page-CW6SLuT4.mjs} +2 -1
  20. package/dist/{_page-4cQKs_Dn.mjs.map → _page-CW6SLuT4.mjs.map} +1 -1
  21. package/dist/basePath-DQnbHc7o.mjs +99 -0
  22. package/dist/basePath-DQnbHc7o.mjs.map +1 -0
  23. package/dist/bin/index.js +1 -1
  24. package/dist/clientEntry.mjs +17 -5
  25. package/dist/clientEntry.mjs.map +1 -1
  26. package/dist/dev.d.mts +2 -2
  27. package/dist/dev.mjs +2 -2
  28. package/dist/discovery.d.mts +43 -0
  29. package/dist/discovery.d.mts.map +1 -0
  30. package/dist/discovery.mjs +72 -0
  31. package/dist/discovery.mjs.map +1 -0
  32. package/dist/env-C2SUAwAq.mjs +49 -0
  33. package/dist/env-C2SUAwAq.mjs.map +1 -0
  34. package/dist/env.d.mts +84 -0
  35. package/dist/env.d.mts.map +1 -0
  36. package/dist/env.mjs +2 -0
  37. package/dist/form.d.mts +14 -5
  38. package/dist/form.d.mts.map +1 -1
  39. package/dist/form.mjs +14 -4
  40. package/dist/form.mjs.map +1 -1
  41. package/dist/index.d.mts +5 -3
  42. package/dist/index.d.mts.map +1 -1
  43. package/dist/index.mjs +61 -0
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/{load-C9RpS_4j.mjs → load-Uyj9I60p.mjs} +33 -21
  46. package/dist/load-Uyj9I60p.mjs.map +1 -0
  47. package/dist/nav.d.mts.map +1 -1
  48. package/dist/nav.mjs +4 -2
  49. package/dist/nav.mjs.map +1 -1
  50. package/dist/openapi.d.mts +1 -1
  51. package/dist/run.d.mts +1 -1
  52. package/dist/run.d.mts.map +1 -1
  53. package/dist/run.mjs +1 -1
  54. package/dist/{runOpenApi-yIzYasNN.mjs → runOpenApi-DWfPiAv0.mjs} +239 -30
  55. package/dist/runOpenApi-DWfPiAv0.mjs.map +1 -0
  56. package/dist/server/Server.d.mts +1 -1
  57. package/dist/server/Server.mjs +1 -1
  58. package/dist/server.d.mts +19 -3
  59. package/dist/server.d.mts.map +1 -1
  60. package/dist/server.mjs +18 -3
  61. package/dist/server.mjs.map +1 -1
  62. package/dist/serverEntry-CnCVNNjp.mjs +13 -0
  63. package/dist/serverEntry-CnCVNNjp.mjs.map +1 -0
  64. package/dist/{serverEntry-DVv9YI3I.d.mts → serverEntry-fj0XfTs4.d.mts} +5 -4
  65. package/dist/serverEntry-fj0XfTs4.d.mts.map +1 -0
  66. package/dist/serverEntry.d.mts +2 -2
  67. package/dist/serverEntry.mjs +2 -2
  68. package/dist/{serverHandlers-fzIlmvX-.mjs → serverHandlers-B6EcNfBP.mjs} +95 -23
  69. package/dist/serverHandlers-B6EcNfBP.mjs.map +1 -0
  70. package/dist/sitemap-4imxJVrG.mjs +30 -0
  71. package/dist/sitemap-4imxJVrG.mjs.map +1 -0
  72. package/dist/sitemap-BjqN4d4W.d.mts +112 -0
  73. package/dist/sitemap-BjqN4d4W.d.mts.map +1 -0
  74. package/dist/state.d.mts +6 -0
  75. package/dist/state.d.mts.map +1 -1
  76. package/dist/state.mjs +1 -1
  77. package/dist/test.d.mts +2 -2
  78. package/dist/test.mjs +2 -2
  79. package/package.json +9 -1
  80. package/src/types/manifest.d.ts +4 -0
  81. package/dist/Server-Cler2w5O.d.mts.map +0 -1
  82. package/dist/Server-Dr6yqVa5.mjs.map +0 -1
  83. package/dist/ServerEvent-CTx3Q-hk.d.mts +0 -48
  84. package/dist/ServerEvent-CTx3Q-hk.d.mts.map +0 -1
  85. package/dist/ServerEvent-gmOvC_Yf.mjs +0 -100
  86. package/dist/ServerEvent-gmOvC_Yf.mjs.map +0 -1
  87. package/dist/ServerHook-BlLArueW.d.mts.map +0 -1
  88. package/dist/Site-CTADVh7d.d.mts.map +0 -1
  89. package/dist/load-C9RpS_4j.mjs.map +0 -1
  90. package/dist/runOpenApi-yIzYasNN.mjs.map +0 -1
  91. package/dist/serverEntry-CUXFQ07g.mjs +0 -11
  92. package/dist/serverEntry-CUXFQ07g.mjs.map +0 -1
  93. package/dist/serverEntry-DVv9YI3I.d.mts.map +0 -1
  94. package/dist/serverHandlers-fzIlmvX-.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runOpenApi-DWfPiAv0.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 from here (e.g. an optional peer), skip it\n\t\t\treturn undefined;\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","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\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 (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 (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 (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\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 } 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\tconfig.server.port ??= 7059;\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\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\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 * 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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IAAI;IACjB;GAED,KAAK;IACJ,MAAM,SAAS,IAAI;IACnB;GAED,KAAK;IACJ,MAAM,WAAW,IAAI;IACrB;GAED;IACC,QAAQ,IAAI,gCAAgC;IAC5C,MAAM,OAAO,IAAI;EAGnB;CACD,UAAU;EACT,MAAM,KAAK,MAAM;CAClB;AACD;;;;;;;;ACvEA,eAA8B,WAC7B,MACA,MACA,UAAU,gBACM;CAChB,MAAM,UAAU,KAAK,YAAY,IAAI,kBAAkB;CACvD,IAAI,CAAC,SACJ,MAAM,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,2 +1,2 @@
1
- import { t as Server } from "../Server-Cler2w5O.mjs";
1
+ import { t as Server } from "../Server-qn5Ws_d0.mjs";
2
2
  export { Server as default };
@@ -1,2 +1,2 @@
1
- import { t as Server } from "../Server-Dr6yqVa5.mjs";
1
+ import { t as Server } from "../Server-CSti9cvM.mjs";
2
2
  export { Server as default };
package/dist/server.d.mts CHANGED
@@ -1,6 +1,22 @@
1
- import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-CTx3Q-hk.mjs";
2
- import { n as MiddlewareFunction, t as Server } from "./Server-Cler2w5O.mjs";
1
+ import { i as CookieHelper, n as HeaderHelper } from "./SessionHelper-MaodMaLU.mjs";
2
+ import { n as ServerEvent, t as MiddlewareFunction } from "./MiddlewareFunction-BZilnEei.mjs";
3
+ import { t as Server } from "./Server-qn5Ws_d0.mjs";
4
+ import { r as ServerLoadEvent } from "./ServerLoadEvent-DzbxxkF8.mjs";
5
+ import { t as ServerHook } from "./ServerHook-BTSGfLiJ.mjs";
3
6
  import { IncomingMessage, ServerResponse } from "node:http";
7
+ //#region src/server/invokeHook.d.ts
8
+ /**
9
+ * Invokes a server hook's `enter` function and returns its `Response`, so
10
+ * in-process callers can short-circuit when the hook returns one (a redirect
11
+ * for unauthenticated users, etc).
12
+ *
13
+ * This exists because a hook declared with
14
+ * `export default { ... } satisfies ServerHook<"/api">` keeps the
15
+ * implementation's inferred return type -- usually `void` -- so calling
16
+ * `hook.enter(event)` directly doesn't type the result as `Response | void`.
17
+ */
18
+ declare function invokeHook<Route extends string | undefined = undefined>(hook: ServerHook<Route>, event: ServerLoadEvent<Route>): Promise<Response | undefined>;
19
+ //#endregion
4
20
  //#region src/server/connect/connectMiddleware.d.ts
5
21
  /**
6
22
  * Converts a Connect-style middleware to a torpor middleware.
@@ -17,5 +33,5 @@ type NextFunction = (err?: unknown) => void;
17
33
  type ConnectMiddleware<PlatformRequest extends IncomingMessage = IncomingMessage, PlatformResponse extends ServerResponse = ServerResponse> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;
18
34
  type ConnectMiddlewareBoolean<PlatformRequest extends IncomingMessage = IncomingMessage, PlatformResponse extends ServerResponse = ServerResponse> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;
19
35
  //#endregion
20
- export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware };
36
+ export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, invokeHook };
21
37
  //# sourceMappingURL=server.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/connect/connectMiddleware.ts"],"mappings":";;;;;;;;;;;;;;iBAmBwB,kBACvB,SAAS,oBAAoB,2BAC3B;KAuDE,gBAAgB;KAChB,kBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,wBAAwB;KAC3E,yBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,2BAA2B"}
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../src/server/invokeHook.ts","../src/server/connect/connectMiddleware.ts"],"mappings":";;;;;;;;;;;;;;;;;iBAa8B,WAAW,8CACxC,MAAM,WAAW,QACjB,OAAO,gBAAgB,SACrB,QAAQ;;;;;;;;;;;;;iBCGa,kBACvB,SAAS,oBAAoB,2BAC3B;KAuDE,gBAAgB;KAChB,kBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,wBAAwB;KAC3E,yBACJ,wBAAwB,kBAAkB,iBAC1C,yBAAyB,iBAAiB,mBACtC,KAAK,iBAAiB,KAAK,kBAAkB,MAAM,2BAA2B"}
package/dist/server.mjs CHANGED
@@ -1,8 +1,23 @@
1
- import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-gmOvC_Yf.mjs";
2
- import { t as Server } from "./Server-Dr6yqVa5.mjs";
1
+ import { n as HeaderHelper, r as CookieHelper, t as ServerEvent } from "./ServerEvent-Bh9cEpro.mjs";
2
+ import { t as Server } from "./Server-CSti9cvM.mjs";
3
3
  import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
4
4
  import { PassThrough, Readable } from "node:stream";
5
5
  import { ServerResponse } from "node:http";
6
+ //#region src/server/invokeHook.ts
7
+ /**
8
+ * Invokes a server hook's `enter` function and returns its `Response`, so
9
+ * in-process callers can short-circuit when the hook returns one (a redirect
10
+ * for unauthenticated users, etc).
11
+ *
12
+ * This exists because a hook declared with
13
+ * `export default { ... } satisfies ServerHook<"/api">` keeps the
14
+ * implementation's inferred return type -- usually `void` -- so calling
15
+ * `hook.enter(event)` directly doesn't type the result as `Response | void`.
16
+ */
17
+ async function invokeHook(hook, event) {
18
+ return await hook.enter?.(event) ?? void 0;
19
+ }
20
+ //#endregion
6
21
  //#region src/server/connect/nodeMessageToNodeResponse.ts
7
22
  /**
8
23
  * Creates a custom ServerResponse object that allows for intercepting and
@@ -129,6 +144,6 @@ const statusCodesWithoutBody = [
129
144
  304
130
145
  ];
131
146
  //#endregion
132
- export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware };
147
+ export { CookieHelper, HeaderHelper, Server, ServerEvent, connectMiddleware, invokeHook };
133
148
 
134
149
  //# sourceMappingURL=server.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/server/connect/nodeMessageToNodeResponse.ts","../src/server/connect/requestToNodeMessage.ts","../src/server/connect/connectMiddleware.ts"],"sourcesContent":["import {\n\ttype IncomingMessage,\n\ttype OutgoingHttpHeader,\n\ttype OutgoingHttpHeaders,\n\tServerResponse,\n} from \"node:http\";\nimport { PassThrough, Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/createServerResponse.ts\n\n/**\n * Creates a custom ServerResponse object that allows for intercepting and\n * streaming the response.\n *\n * @param incomingMessage The incoming HTTP request message.\n * @returns An object containing the custom ServerResponse and a function that\n * takes a callback to invoke when the response is readable, providing an object\n * with the readable stream, headers and status code.\n */\nexport default function nodeMessageToNodeResponse(\n\tincomingMessage: IncomingMessage,\n): ServerResponseResponse {\n\tconst res = new ServerResponse(incomingMessage);\n\tconst passThrough = new PassThrough();\n\tlet handled = false;\n\n\tconst onReadable = (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => {\n\t\tconst handleReadable = () => {\n\t\t\tif (handled) return;\n\t\t\thandled = true;\n\t\t\tcb({\n\t\t\t\treadable: Readable.from(passThrough),\n\t\t\t\theaders: res.getHeaders(),\n\t\t\t\tstatus: res.statusCode,\n\t\t\t});\n\t\t};\n\n\t\tpassThrough.once(\"readable\", handleReadable);\n\t\tpassThrough.once(\"end\", handleReadable);\n\t};\n\n\tpassThrough.once(\"finish\", () => {\n\t\tres.emit(\"finish\");\n\t});\n\tpassThrough.once(\"close\", () => {\n\t\tres.destroy();\n\t\tres.emit(\"close\");\n\t});\n\tpassThrough.on(\"drain\", () => {\n\t\tres.emit(\"drain\");\n\t});\n\n\tres.write = passThrough.write.bind(passThrough);\n\tres.end = passThrough.end.bind(passThrough) as any;\n\n\tres.writeHead = function writeHead(\n\t\tstatusCode: number,\n\t\tstatusMessage?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\theaders?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t): ServerResponse {\n\t\tres.statusCode = statusCode;\n\t\tif (typeof statusMessage === \"object\") {\n\t\t\theaders = statusMessage;\n\t\t\tstatusMessage = undefined;\n\t\t}\n\t\tif (headers) {\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tres.setHeader(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t};\n\n\treturn {\n\t\tres,\n\t\tonReadable,\n\t};\n}\n\ninterface ServerResponseResponse {\n\tres: ServerResponse;\n\tonReadable: (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => void;\n}\n","import { type IncomingMessage } from \"node:http\";\nimport { Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\nconst DUMMY_BASE_URL = \"http://localhost\";\n\n/**\n * Creates an IncomingMessage object from a web Request.\n *\n * The request body is intentionally not forwarded: this is only used to wrap\n * Connect-style middlewares (e.g. Vite's dev middleware), which don't read\n * the body. The actual route handler later reads `ev.request.body` directly,\n * and forwarding the body here would consume it and break the handler.\n *\n * @param {Request} request - The web Request object.\n * @returns {IncomingMessage} An IncomingMessage-like object compatible with Node.js HTTP module.\n */\nexport default function requestToNodeMessage(request: Request): IncomingMessage {\n\tconst parsedUrl = new URL(request.url, DUMMY_BASE_URL);\n\tconst pathAndQuery = (parsedUrl.pathname || \"\") + (parsedUrl.search || \"\");\n\tconst body = Readable.from([]);\n\n\treturn Object.assign(body, {\n\t\turl: pathAndQuery,\n\t\tmethod: request.method,\n\t\theaders: Object.fromEntries(request.headers),\n\t}) as IncomingMessage;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type MiddlewareFunction from \"../types/MiddlewareFunction\";\nimport flattenHeaders from \"./flattenHeaders\";\nimport nodeMessageToNodeResponse from \"./nodeMessageToNodeResponse\";\nimport requestToNodeMessage from \"./requestToNodeMessage\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\n/**\n * Converts a Connect-style middleware to a torpor middleware.\n *\n * If the Connect handler writes a response, it is returned from the `enter`\n * hook and the middleware chain is short-circuited. If the handler calls\n * `next()`, the rest of the chain runs after this middleware completes.\n *\n * @param handler - The Connect-style middleware function to be converted.\n * @returns A middleware whose `enter` hook handles the web request.\n */\nexport default function connectMiddleware(\n\thandler: ConnectMiddleware | ConnectMiddlewareBoolean,\n): MiddlewareFunction {\n\treturn {\n\t\tenter: (ev) =>\n\t\t\tnew Promise<Response | void>((resolve, reject) => {\n\t\t\t\tconst req = requestToNodeMessage(ev.request);\n\t\t\t\tconst { res, onReadable } = nodeMessageToNodeResponse(req);\n\n\t\t\t\tonReadable(({ readable, headers, status }) => {\n\t\t\t\t\tconst responseBody: ReadableStream | null = statusCodesWithoutBody.includes(status)\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: (Readable.toWeb(readable) as unknown as ReadableStream);\n\t\t\t\t\tresolve(\n\t\t\t\t\t\tnew Response(responseBody, {\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\theaders: flattenHeaders(headers),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tconst cnext = (error?: unknown) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\t// eslint-disable-next-line no-base-to-string\n\t\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// The Connect handler is passing the request on\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tPromise.resolve(handler(req, res, cnext))\n\t\t\t\t\t.then((handled) => {\n\t\t\t\t\t\tif (handled === false) {\n\t\t\t\t\t\t\tres.destroy();\n\t\t\t\t\t\t\t// Returning false signals that the request was handled,\n\t\t\t\t\t\t\t// so return an empty response to stop the chain\n\t\t\t\t\t\t\tresolve(new Response(null, { status: 200 }));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\tcnext(e);\n\t\t\t\t\t});\n\t\t\t}),\n\t};\n}\n\nconst statusCodesWithoutBody = [\n\t100, // Continue\n\t101, // Switching Protocols\n\t102, // Processing (WebDAV)\n\t103, // Early Hints\n\t204, // No Content\n\t205, // Reset Content\n\t304, // Not Modified\n];\n\ntype NextFunction = (err?: unknown) => void;\ntype ConnectMiddleware<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;\ntype ConnectMiddlewareBoolean<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;\n"],"mappings":";;;;;;;;;;;;;;;AAmBA,SAAwB,0BACvB,iBACyB;CACzB,MAAM,MAAM,IAAI,eAAe,eAAe;CAC9C,MAAM,cAAc,IAAI,YAAY;CACpC,IAAI,UAAU;CAEd,MAAM,cACL,OACI;EACJ,MAAM,uBAAuB;GAC5B,IAAI,SAAS;GACb,UAAU;GACV,GAAG;IACF,UAAU,SAAS,KAAK,WAAW;IACnC,SAAS,IAAI,WAAW;IACxB,QAAQ,IAAI;GACb,CAAC;EACF;EAEA,YAAY,KAAK,YAAY,cAAc;EAC3C,YAAY,KAAK,OAAO,cAAc;CACvC;CAEA,YAAY,KAAK,gBAAgB;EAChC,IAAI,KAAK,QAAQ;CAClB,CAAC;CACD,YAAY,KAAK,eAAe;EAC/B,IAAI,QAAQ;EACZ,IAAI,KAAK,OAAO;CACjB,CAAC;CACD,YAAY,GAAG,eAAe;EAC7B,IAAI,KAAK,OAAO;CACjB,CAAC;CAED,IAAI,QAAQ,YAAY,MAAM,KAAK,WAAW;CAC9C,IAAI,MAAM,YAAY,IAAI,KAAK,WAAW;CAE1C,IAAI,YAAY,SAAS,UACxB,YACA,eACA,SACiB;EACjB,IAAI,aAAa;EACjB,IAAI,OAAO,kBAAkB,UAAU;GACtC,UAAU;GACV,gBAAgB,KAAA;EACjB;EACA,IAAI,SACE;QAAA,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAChD,IAAI,UAAU,KAAA,GACb,IAAI,UAAU,KAAK,KAAK;EAAA;EAI3B,OAAO;CACR;CAEA,OAAO;EACN;EACA;CACD;AACD;;;AC5EA,MAAM,iBAAiB;;;;;;;;;;;;AAavB,SAAwB,qBAAqB,SAAmC;CAC/E,MAAM,YAAY,IAAI,IAAI,QAAQ,KAAK,cAAc;CACrD,MAAM,gBAAgB,UAAU,YAAY,OAAO,UAAU,UAAU;CACvE,MAAM,OAAO,SAAS,KAAK,CAAC,CAAC;CAE7B,OAAO,OAAO,OAAO,MAAM;EAC1B,KAAK;EACL,QAAQ,QAAQ;EAChB,SAAS,OAAO,YAAY,QAAQ,OAAO;CAC5C,CAAC;AACF;;;;;;;;;;;;;ACTA,SAAwB,kBACvB,SACqB;CACrB,OAAO,EACN,QAAQ,OACP,IAAI,SAA0B,SAAS,WAAW;EACjD,MAAM,MAAM,qBAAqB,GAAG,OAAO;EAC3C,MAAM,EAAE,KAAK,eAAe,0BAA0B,GAAG;EAEzD,YAAY,EAAE,UAAU,SAAS,aAAa;GAC7C,MAAM,eAAsC,uBAAuB,SAAS,MAAM,IAC/E,OACC,SAAS,MAAM,QAAQ;GAC3B,QACC,IAAI,SAAS,cAAc;IAC1B;IACA,SAAS,eAAe,OAAO;GAChC,CAAC,CACF;EACD,CAAC;EAED,MAAM,SAAS,UAAoB;GAClC,IAAI,OAEH,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;QAGhE,QAAQ;EAEV;EAEA,QAAQ,QAAQ,QAAQ,KAAK,KAAK,KAAK,CAAC,CAAC,CACvC,MAAM,YAAY;GAClB,IAAI,YAAY,OAAO;IACtB,IAAI,QAAQ;IAGZ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC;GAC5C;EACD,CAAC,CAAC,CACD,OAAO,MAAe;GACtB,MAAM,CAAC;EACR,CAAC;CACH,CAAC,EACH;AACD;AAEA,MAAM,yBAAyB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/server/invokeHook.ts","../src/server/connect/nodeMessageToNodeResponse.ts","../src/server/connect/requestToNodeMessage.ts","../src/server/connect/connectMiddleware.ts"],"sourcesContent":["import type ServerHook from \"../types/ServerHook\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent\";\n\n/**\n * Invokes a server hook's `enter` function and returns its `Response`, so\n * in-process callers can short-circuit when the hook returns one (a redirect\n * for unauthenticated users, etc).\n *\n * This exists because a hook declared with\n * `export default { ... } satisfies ServerHook<\"/api\">` keeps the\n * implementation's inferred return type -- usually `void` -- so calling\n * `hook.enter(event)` directly doesn't type the result as `Response | void`.\n */\nexport default async function invokeHook<Route extends string | undefined = undefined>(\n\thook: ServerHook<Route>,\n\tevent: ServerLoadEvent<Route>,\n): Promise<Response | undefined> {\n\treturn (await hook.enter?.(event)) ?? undefined;\n}\n","import {\n\ttype IncomingMessage,\n\ttype OutgoingHttpHeader,\n\ttype OutgoingHttpHeaders,\n\tServerResponse,\n} from \"node:http\";\nimport { PassThrough, Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/createServerResponse.ts\n\n/**\n * Creates a custom ServerResponse object that allows for intercepting and\n * streaming the response.\n *\n * @param incomingMessage The incoming HTTP request message.\n * @returns An object containing the custom ServerResponse and a function that\n * takes a callback to invoke when the response is readable, providing an object\n * with the readable stream, headers and status code.\n */\nexport default function nodeMessageToNodeResponse(\n\tincomingMessage: IncomingMessage,\n): ServerResponseResponse {\n\tconst res = new ServerResponse(incomingMessage);\n\tconst passThrough = new PassThrough();\n\tlet handled = false;\n\n\tconst onReadable = (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => {\n\t\tconst handleReadable = () => {\n\t\t\tif (handled) return;\n\t\t\thandled = true;\n\t\t\tcb({\n\t\t\t\treadable: Readable.from(passThrough),\n\t\t\t\theaders: res.getHeaders(),\n\t\t\t\tstatus: res.statusCode,\n\t\t\t});\n\t\t};\n\n\t\tpassThrough.once(\"readable\", handleReadable);\n\t\tpassThrough.once(\"end\", handleReadable);\n\t};\n\n\tpassThrough.once(\"finish\", () => {\n\t\tres.emit(\"finish\");\n\t});\n\tpassThrough.once(\"close\", () => {\n\t\tres.destroy();\n\t\tres.emit(\"close\");\n\t});\n\tpassThrough.on(\"drain\", () => {\n\t\tres.emit(\"drain\");\n\t});\n\n\tres.write = passThrough.write.bind(passThrough);\n\tres.end = passThrough.end.bind(passThrough) as any;\n\n\tres.writeHead = function writeHead(\n\t\tstatusCode: number,\n\t\tstatusMessage?: string | OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t\theaders?: OutgoingHttpHeaders | OutgoingHttpHeader[],\n\t): ServerResponse {\n\t\tres.statusCode = statusCode;\n\t\tif (typeof statusMessage === \"object\") {\n\t\t\theaders = statusMessage;\n\t\t\tstatusMessage = undefined;\n\t\t}\n\t\tif (headers) {\n\t\t\tfor (const [key, value] of Object.entries(headers)) {\n\t\t\t\tif (value !== undefined) {\n\t\t\t\t\tres.setHeader(key, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t};\n\n\treturn {\n\t\tres,\n\t\tonReadable,\n\t};\n}\n\ninterface ServerResponseResponse {\n\tres: ServerResponse;\n\tonReadable: (\n\t\tcb: (result: { readable: Readable; headers: OutgoingHttpHeaders; status: number }) => void,\n\t) => void;\n}\n","import { type IncomingMessage } from \"node:http\";\nimport { Readable } from \"node:stream\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\nconst DUMMY_BASE_URL = \"http://localhost\";\n\n/**\n * Creates an IncomingMessage object from a web Request.\n *\n * The request body is intentionally not forwarded: this is only used to wrap\n * Connect-style middlewares (e.g. Vite's dev middleware), which don't read\n * the body. The actual route handler later reads `ev.request.body` directly,\n * and forwarding the body here would consume it and break the handler.\n *\n * @param {Request} request - The web Request object.\n * @returns {IncomingMessage} An IncomingMessage-like object compatible with Node.js HTTP module.\n */\nexport default function requestToNodeMessage(request: Request): IncomingMessage {\n\tconst parsedUrl = new URL(request.url, DUMMY_BASE_URL);\n\tconst pathAndQuery = (parsedUrl.pathname || \"\") + (parsedUrl.search || \"\");\n\tconst body = Readable.from([]);\n\n\treturn Object.assign(body, {\n\t\turl: pathAndQuery,\n\t\tmethod: request.method,\n\t\theaders: Object.fromEntries(request.headers),\n\t}) as IncomingMessage;\n}\n","import { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport type MiddlewareFunction from \"../types/MiddlewareFunction\";\nimport flattenHeaders from \"./flattenHeaders\";\nimport nodeMessageToNodeResponse from \"./nodeMessageToNodeResponse\";\nimport requestToNodeMessage from \"./requestToNodeMessage\";\n\n// From https://github.com/vikejs/vike-node/blob/main/packages/vike-node/src/runtime/adapters/connectToWeb.ts\n\n/**\n * Converts a Connect-style middleware to a torpor middleware.\n *\n * If the Connect handler writes a response, it is returned from the `enter`\n * hook and the middleware chain is short-circuited. If the handler calls\n * `next()`, the rest of the chain runs after this middleware completes.\n *\n * @param handler - The Connect-style middleware function to be converted.\n * @returns A middleware whose `enter` hook handles the web request.\n */\nexport default function connectMiddleware(\n\thandler: ConnectMiddleware | ConnectMiddlewareBoolean,\n): MiddlewareFunction {\n\treturn {\n\t\tenter: (ev) =>\n\t\t\tnew Promise<Response | void>((resolve, reject) => {\n\t\t\t\tconst req = requestToNodeMessage(ev.request);\n\t\t\t\tconst { res, onReadable } = nodeMessageToNodeResponse(req);\n\n\t\t\t\tonReadable(({ readable, headers, status }) => {\n\t\t\t\t\tconst responseBody: ReadableStream | null = statusCodesWithoutBody.includes(status)\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: (Readable.toWeb(readable) as unknown as ReadableStream);\n\t\t\t\t\tresolve(\n\t\t\t\t\t\tnew Response(responseBody, {\n\t\t\t\t\t\t\tstatus,\n\t\t\t\t\t\t\theaders: flattenHeaders(headers),\n\t\t\t\t\t\t}),\n\t\t\t\t\t);\n\t\t\t\t});\n\n\t\t\t\tconst cnext = (error?: unknown) => {\n\t\t\t\t\tif (error) {\n\t\t\t\t\t\t// eslint-disable-next-line no-base-to-string\n\t\t\t\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// The Connect handler is passing the request on\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tPromise.resolve(handler(req, res, cnext))\n\t\t\t\t\t.then((handled) => {\n\t\t\t\t\t\tif (handled === false) {\n\t\t\t\t\t\t\tres.destroy();\n\t\t\t\t\t\t\t// Returning false signals that the request was handled,\n\t\t\t\t\t\t\t// so return an empty response to stop the chain\n\t\t\t\t\t\t\tresolve(new Response(null, { status: 200 }));\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.catch((e: unknown) => {\n\t\t\t\t\t\tcnext(e);\n\t\t\t\t\t});\n\t\t\t}),\n\t};\n}\n\nconst statusCodesWithoutBody = [\n\t100, // Continue\n\t101, // Switching Protocols\n\t102, // Processing (WebDAV)\n\t103, // Early Hints\n\t204, // No Content\n\t205, // Reset Content\n\t304, // Not Modified\n];\n\ntype NextFunction = (err?: unknown) => void;\ntype ConnectMiddleware<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => void | Promise<void>;\ntype ConnectMiddlewareBoolean<\n\tPlatformRequest extends IncomingMessage = IncomingMessage,\n\tPlatformResponse extends ServerResponse = ServerResponse,\n> = (req: PlatformRequest, res: PlatformResponse, next: NextFunction) => boolean | Promise<boolean>;\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,eAA8B,WAC7B,MACA,OACgC;CAChC,OAAQ,MAAM,KAAK,QAAQ,KAAK,KAAM,KAAA;AACvC;;;;;;;;;;;;ACCA,SAAwB,0BACvB,iBACyB;CACzB,MAAM,MAAM,IAAI,eAAe,eAAe;CAC9C,MAAM,cAAc,IAAI,YAAY;CACpC,IAAI,UAAU;CAEd,MAAM,cACL,OACI;EACJ,MAAM,uBAAuB;GAC5B,IAAI,SAAS;GACb,UAAU;GACV,GA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AAE,KAAK,eAAe,0BAA0B,GAAG;EAEzD,YAAY,EAAE,UAAU,SAAS,aAAa;GAC7C,MAAM,eAAsC,uBAAuB,SAAS,MAAM,IAC/E,OACC,SAAS,MAAM,QAAQ;GAC3B,QACC,IAAI,SAAS,cAAc;IAC1B;IACA,SAAS,eAAe,OAAO;GAChC,CAAC,CACF;EACD,CAAC;EAED,MAAM,SAAS,UAAoB;GAClC,IAAI,OAEH,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC,CAAC;QAGhE,QAAQ;EAEV;EAEA,QAAQ,QAAQ,QAAQ,KAAK,KAAK,KAAK,CAAC,CAAC,CACvC,MAAM,YAAY;GAClB,IAAI,YAAY,OAAO;IACtB,IAAI,QAAQ;IAGZ,QAAQ,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC,CAAC;GAC5C;EACD,CAAC,CAAC,CACD,OAAO,MAAe;GACtB,MAAM,CAAC;EACR,CAAC;CACH,CAAC,EACH;AACD;AAEA,MAAM,yBAAyB;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;AACD"}
@@ -0,0 +1,13 @@
1
+ import { t as Router } from "./Router-C4ADUfhv.mjs";
2
+ import { o as setBasePath } from "./basePath-DQnbHc7o.mjs";
3
+ import { t as createServerLoad } from "./serverHandlers-B6EcNfBP.mjs";
4
+ import manifest from "@torpor/build/manifest";
5
+ //#region src/site/serverEntry.ts
6
+ setBasePath(manifest.base);
7
+ const router = new Router();
8
+ router.addPages(manifest.routes);
9
+ const load = createServerLoad(router, manifest.base, manifest.middleware ?? []);
10
+ //#endregion
11
+ export { router as n, load as t };
12
+
13
+ //# sourceMappingURL=serverEntry-CnCVNNjp.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverEntry-CnCVNNjp.mjs","names":[],"sources":["../src/site/serverEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\nimport { type ServerLoad, createServerLoad } from \"./serverHandlers.ts\";\n\n// Put adapter-specific functionality in the `adapter` property of\n// globalThis for now\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nexport const router: Router = new Router();\nrouter.addPages(manifest.routes);\n\n//console.log(`routes:\\n ${router.routes.map((r) => r.path).join(\"\\n \")}`);\n\nexport const load: ServerLoad = createServerLoad(router, manifest.base, manifest.middleware ?? []);\n"],"mappings":";;;;;AAOA,YAAY,SAAS,IAAI;AAGzB,MAAa,SAAiB,IAAI,OAAO;AACzC,OAAO,SAAS,SAAS,MAAM;AAI/B,MAAa,OAAmB,iBAAiB,QAAQ,SAAS,MAAM,SAAS,cAAc,CAAC,CAAC"}
@@ -1,5 +1,5 @@
1
- import { t as ServerEvent } from "./ServerEvent-CTx3Q-hk.mjs";
2
- import "./Router-COdQuVUi.mjs";
1
+ import { n as ServerEvent } from "./MiddlewareFunction-BZilnEei.mjs";
2
+ import { t as Router } from "./Router-dAu_5PlG.mjs";
3
3
  //#region src/site/serverHandlers.d.ts
4
4
  /**
5
5
  * The site's request handler, as created by `createServerLoad`.
@@ -7,7 +7,8 @@ import "./Router-COdQuVUi.mjs";
7
7
  type ServerLoad = (ev: ServerEvent, template?: string) => Promise<Response>;
8
8
  //#endregion
9
9
  //#region src/site/serverEntry.d.ts
10
+ declare const router: Router;
10
11
  declare const load: ServerLoad;
11
12
  //#endregion
12
- export { load as t };
13
- //# sourceMappingURL=serverEntry-DVv9YI3I.d.mts.map
13
+ export { router as n, load as t };
14
+ //# sourceMappingURL=serverEntry-fj0XfTs4.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverEntry-fj0XfTs4.d.mts","names":[],"sources":["../src/site/serverHandlers.ts","../src/site/serverEntry.ts"],"mappings":";;;;;;KA2CY,cAAc,IAAI,aAAa,sBAAsB,QAAQ;;;cCjC5D,QAAQ;cAKR,MAAM"}
@@ -1,2 +1,2 @@
1
- import { t as load } from "./serverEntry-DVv9YI3I.mjs";
2
- export { load };
1
+ import { n as router, t as load } from "./serverEntry-fj0XfTs4.mjs";
2
+ export { load, router };
@@ -1,2 +1,2 @@
1
- import { t as load } from "./serverEntry-CUXFQ07g.mjs";
2
- export { load };
1
+ import { n as router, t as load } from "./serverEntry-CnCVNNjp.mjs";
2
+ export { load, router };