@demiurgejs/core 0.2.0-beta.1 → 0.2.0-beta.3

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 (156) hide show
  1. package/README.md +2 -0
  2. package/dist/adapter/testing.d.ts +33 -0
  3. package/dist/adapter/testing.d.ts.map +1 -0
  4. package/dist/adapter/testing.js +251 -0
  5. package/dist/adapter/testing.js.map +1 -0
  6. package/dist/browser/file-router.d.ts.map +1 -1
  7. package/dist/chunks/document-shell-WoM8yZlR.js +35 -0
  8. package/dist/chunks/document-shell-WoM8yZlR.js.map +1 -0
  9. package/dist/chunks/image-codec-Di53WpcH.js +141 -0
  10. package/dist/chunks/image-codec-Di53WpcH.js.map +1 -0
  11. package/dist/chunks/images-Edar3eU1.js +339 -0
  12. package/dist/chunks/images-Edar3eU1.js.map +1 -0
  13. package/dist/chunks/request-metadata-DaIYq4Ea.js +677 -0
  14. package/dist/chunks/request-metadata-DaIYq4Ea.js.map +1 -0
  15. package/dist/chunks/streaming-D0fGAuiO.js +469 -0
  16. package/dist/chunks/streaming-D0fGAuiO.js.map +1 -0
  17. package/dist/chunks/{testing-DBjVCN5v.js → testing-CRflAw4X.js} +1300 -1139
  18. package/dist/chunks/testing-CRflAw4X.js.map +1 -0
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +63 -54
  21. package/dist/cli.js.map +1 -1
  22. package/dist/data/cache.d.ts +8 -0
  23. package/dist/data/cache.d.ts.map +1 -1
  24. package/dist/data/idempotency.d.ts.map +1 -1
  25. package/dist/data/index.d.ts +3 -1
  26. package/dist/data/index.d.ts.map +1 -1
  27. package/dist/data/testing.d.ts.map +1 -1
  28. package/dist/data/testing.js +94 -72
  29. package/dist/data/testing.js.map +1 -1
  30. package/dist/data/tiered.d.ts +7 -0
  31. package/dist/data/tiered.d.ts.map +1 -0
  32. package/dist/document/deferred-scripts.d.ts +11 -0
  33. package/dist/document/deferred-scripts.d.ts.map +1 -0
  34. package/dist/document/hydration.d.ts.map +1 -1
  35. package/dist/document/index.d.ts +4 -1
  36. package/dist/document/index.d.ts.map +1 -1
  37. package/dist/document/render.d.ts.map +1 -1
  38. package/dist/document/scripts.d.ts +12 -1
  39. package/dist/document/scripts.d.ts.map +1 -1
  40. package/dist/document/trusted-types.d.ts +10 -0
  41. package/dist/document/trusted-types.d.ts.map +1 -0
  42. package/dist/edge/assets.d.ts +14 -0
  43. package/dist/edge/assets.d.ts.map +1 -0
  44. package/dist/edge/index.d.ts +19 -0
  45. package/dist/edge/index.d.ts.map +1 -0
  46. package/dist/edge/index.js +286 -0
  47. package/dist/edge/index.js.map +1 -0
  48. package/dist/edge/stores.d.ts +8 -0
  49. package/dist/edge/stores.d.ts.map +1 -0
  50. package/dist/edge/streaming.d.ts +7 -0
  51. package/dist/edge/streaming.d.ts.map +1 -0
  52. package/dist/index.d.ts +7 -7
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +895 -556
  55. package/dist/index.js.map +1 -1
  56. package/dist/internal/testing.js +6 -6
  57. package/dist/kv/index.d.ts +5 -0
  58. package/dist/kv/index.d.ts.map +1 -0
  59. package/dist/kv/index.js +126 -0
  60. package/dist/kv/index.js.map +1 -0
  61. package/dist/kv/rate-limit-store.d.ts +8 -0
  62. package/dist/kv/rate-limit-store.d.ts.map +1 -0
  63. package/dist/kv/store.d.ts +28 -0
  64. package/dist/kv/store.d.ts.map +1 -0
  65. package/dist/node/font.d.ts +5 -0
  66. package/dist/node/font.d.ts.map +1 -0
  67. package/dist/node/http.d.ts.map +1 -1
  68. package/dist/node/image.d.ts +15 -0
  69. package/dist/node/image.d.ts.map +1 -0
  70. package/dist/node/index.d.ts +4 -0
  71. package/dist/node/index.d.ts.map +1 -1
  72. package/dist/node/index.js +25 -23
  73. package/dist/node/index.js.map +1 -1
  74. package/dist/node/static.d.ts.map +1 -1
  75. package/dist/node/streaming.d.ts.map +1 -1
  76. package/dist/platform/analytics.d.ts +58 -5
  77. package/dist/platform/analytics.d.ts.map +1 -1
  78. package/dist/platform/font-assets.d.ts +19 -0
  79. package/dist/platform/font-assets.d.ts.map +1 -0
  80. package/dist/platform/fonts.d.ts +14 -4
  81. package/dist/platform/fonts.d.ts.map +1 -1
  82. package/dist/platform/image-codec.d.ts +15 -0
  83. package/dist/platform/image-codec.d.ts.map +1 -0
  84. package/dist/platform/image-url.d.ts +17 -0
  85. package/dist/platform/image-url.d.ts.map +1 -0
  86. package/dist/platform/image.d.ts +8 -0
  87. package/dist/platform/image.d.ts.map +1 -0
  88. package/dist/platform/images.d.ts +15 -0
  89. package/dist/platform/images.d.ts.map +1 -1
  90. package/dist/platform/index.d.ts +13 -6
  91. package/dist/platform/index.d.ts.map +1 -1
  92. package/dist/platform/observability.d.ts +2 -1
  93. package/dist/platform/observability.d.ts.map +1 -1
  94. package/dist/platform/web-vitals-client.d.ts +32 -0
  95. package/dist/platform/web-vitals-client.d.ts.map +1 -0
  96. package/dist/platform/web-vitals.d.ts +78 -0
  97. package/dist/platform/web-vitals.d.ts.map +1 -0
  98. package/dist/redis/index.d.ts +5 -0
  99. package/dist/redis/index.d.ts.map +1 -0
  100. package/dist/redis/index.js +209 -0
  101. package/dist/redis/index.js.map +1 -0
  102. package/dist/redis/rate-limit-store.d.ts +8 -0
  103. package/dist/redis/rate-limit-store.d.ts.map +1 -0
  104. package/dist/redis/store.d.ts +8 -0
  105. package/dist/redis/store.d.ts.map +1 -0
  106. package/dist/route/action.d.ts.map +1 -1
  107. package/dist/route/middleware.d.ts.map +1 -1
  108. package/dist/route/response.d.ts.map +1 -1
  109. package/dist/router/index.d.ts +1 -1
  110. package/dist/router/index.d.ts.map +1 -1
  111. package/dist/router/manifest.d.ts +1 -0
  112. package/dist/router/manifest.d.ts.map +1 -1
  113. package/dist/security/cookies.d.ts +26 -0
  114. package/dist/security/cookies.d.ts.map +1 -0
  115. package/dist/security/env.d.ts.map +1 -1
  116. package/dist/security/fetch-metadata.d.ts +29 -0
  117. package/dist/security/fetch-metadata.d.ts.map +1 -0
  118. package/dist/security/index.d.ts +5 -1
  119. package/dist/security/index.d.ts.map +1 -1
  120. package/dist/security/policy.d.ts +2 -27
  121. package/dist/security/policy.d.ts.map +1 -1
  122. package/dist/security/rate-limit.d.ts +6 -3
  123. package/dist/security/rate-limit.d.ts.map +1 -1
  124. package/dist/security/request.d.ts.map +1 -1
  125. package/dist/security/types.d.ts +82 -6
  126. package/dist/security/types.d.ts.map +1 -1
  127. package/dist/security/verification.d.ts.map +1 -1
  128. package/dist/server/document-shell.d.ts +12 -0
  129. package/dist/server/document-shell.d.ts.map +1 -0
  130. package/dist/server/index.d.ts +1 -1
  131. package/dist/server/index.d.ts.map +1 -1
  132. package/dist/server/request-handler.d.ts +6 -2
  133. package/dist/server/request-handler.d.ts.map +1 -1
  134. package/dist/static/images.d.ts +13 -0
  135. package/dist/static/images.d.ts.map +1 -0
  136. package/dist/static/index.d.ts +8 -0
  137. package/dist/static/index.d.ts.map +1 -1
  138. package/dist/static/index.js +421 -313
  139. package/dist/static/index.js.map +1 -1
  140. package/dist/static/vercel.d.ts +3 -0
  141. package/dist/static/vercel.d.ts.map +1 -1
  142. package/dist/vite/index.d.ts +3 -0
  143. package/dist/vite/index.d.ts.map +1 -1
  144. package/dist/vite/index.js +1041 -652
  145. package/dist/vite/index.js.map +1 -1
  146. package/dist/vite/plugin.d.ts +9 -0
  147. package/dist/vite/plugin.d.ts.map +1 -1
  148. package/dist/vite/policy-verification.d.ts.map +1 -1
  149. package/dist/vite/route-audit.d.ts +50 -0
  150. package/dist/vite/route-audit.d.ts.map +1 -0
  151. package/package.json +34 -3
  152. package/dist/chunks/request-metadata-DwEO1EAS.js +0 -477
  153. package/dist/chunks/request-metadata-DwEO1EAS.js.map +0 -1
  154. package/dist/chunks/streaming-Ci6vf3BB.js +0 -353
  155. package/dist/chunks/streaming-Ci6vf3BB.js.map +0 -1
  156. package/dist/chunks/testing-DBjVCN5v.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/package-name.ts","../../src/routing/generate.ts","../../src/vite/policy-verification.ts","../../src/vite/plugin.ts"],"sourcesContent":["// The package name is the specifier that user code imports. Generated client\n// entries, server entries, and route type declarations use it. Page route\n// detection also compares application source with it. A mismatch then breaks\n// resolution in the consumer build.\n//\n// This is deliberately not the same thing as the many internal `demiurge`\n// strings elsewhere in the source. `__demiurge_data`, `virtual:demiurge/*`,\n// `demiurge-manifest.json`, and friends name the framework, not the package,\n// and they stay put if the registry name ever changes.\nexport const PACKAGE_NAME = \"@demiurgejs/core\";\n","import { mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport { PACKAGE_NAME } from \"../package-name\";\n\nexport type GenerateRoutesOptions = {\n outputFile: string;\n routesDir: string;\n};\n\ntype RouteInfo = {\n contextMiddleware: number[];\n fileSegments: string[];\n pathVars: string[];\n pattern: string;\n};\n\ntype MiddlewareInfo = {\n file: string;\n fileSegments: string[];\n importPath: string;\n};\n\nexport async function generateRoutes(options: GenerateRoutesOptions) {\n const routeFiles = await findRouteFiles(options.routesDir);\n const middleware = routeFiles\n .map((file) => toMiddlewareInfo(options, file))\n .filter((value): value is MiddlewareInfo => Boolean(value));\n const routes = routeFiles\n .map((file) => toRouteInfo(options.routesDir, file, middleware))\n .filter((route): route is RouteInfo => Boolean(route))\n .sort((a, b) => a.pattern.localeCompare(b.pattern));\n\n const source = renderRoutesModule(routes, middleware);\n\n await mkdir(dirname(options.outputFile), { recursive: true });\n await writeFile(options.outputFile, source);\n\n return {\n routes,\n source,\n };\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\nfunction toRouteInfo(\n routesDir: string,\n file: string,\n middleware: MiddlewareInfo[],\n) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n const basename = fileSegments.at(-1);\n\n if (basename?.startsWith(\"@\")) {\n return null;\n }\n\n const urlSegments = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment === \"index\") {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n return [segment];\n });\n\n const pathVars = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment.slice(4, -1)];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment.slice(1, -1)];\n }\n\n return [];\n });\n\n return {\n contextMiddleware: middleware\n .filter((entry) => isAttachedFileForRoute(entry.fileSegments, fileSegments))\n .map((entry) => middleware.indexOf(entry)),\n fileSegments,\n pathVars,\n pattern: `/${urlSegments.join(\"/\")}`.replace(/\\/$/, \"\") || \"/\",\n };\n}\n\nfunction toMiddlewareInfo(\n options: GenerateRoutesOptions,\n file: string,\n): MiddlewareInfo | null {\n const relativePath = relative(options.routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n\n if (fileSegments.at(-1) !== \"@middleware\") {\n return null;\n }\n\n let importPath = relative(dirname(options.outputFile), file)\n .split(sep)\n .join(\"/\")\n .replace(/\\.tsx?$/, \"\");\n\n if (!importPath.startsWith(\".\")) {\n importPath = `./${importPath}`;\n }\n\n return { file, fileSegments: fileSegments.slice(0, -1), importPath };\n}\n\nfunction isAttachedFileForRoute(\n attachedFileSegments: string[],\n routeFileSegments: string[],\n) {\n return attachedFileSegments.every(\n (segment, index) => routeFileSegments[index] === segment,\n );\n}\n\nfunction isRouteGroupSegment(segment: string) {\n return segment.startsWith(\"(\") && segment.endsWith(\")\");\n}\n\nfunction renderRoutesModule(routes: RouteInfo[], middleware: MiddlewareInfo[]) {\n return `// Generated by Demiurge. Do not edit by hand.\nimport \"${PACKAGE_NAME}\";\nimport type { MiddlewareContextOf, PathValue } from \"${PACKAGE_NAME}\";\n${middleware.map(renderMiddlewareImport).join(\"\\n\")}\n\n${middleware.map((_entry, index) => renderMiddlewareContextAlias(index)).join(\"\\n\")}\n\ndeclare module \"${PACKAGE_NAME}\" {\n interface RoutePathVars {\n${routes.map(renderPathVarsEntry).join(\"\\n\")}\n }\n\n interface RouteConcretePaths {\n${routes.map(renderConcretePathEntry).join(\"\\n\")}\n }\n\n interface RouteRequestContexts {\n${routes.map(renderRequestContextEntry).join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n}\n\nfunction renderMiddlewareImport(entry: MiddlewareInfo, index: number) {\n return `type __DemiurgeMiddleware${index} = typeof import(${JSON.stringify(entry.importPath)}) extends { middleware?: infer T } ? T : never;`;\n}\n\nfunction renderMiddlewareContextAlias(index: number) {\n return `type __DemiurgeMiddlewareContext${index} = MiddlewareContextOf<__DemiurgeMiddleware${index}>;`;\n}\n\nfunction renderPathVarsEntry(route: RouteInfo) {\n if (route.pathVars.length === 0) {\n return ` ${JSON.stringify(route.pattern)}: {};`;\n }\n\n const pathType = route.pathVars\n .map((name) => `${name}: PathValue`)\n .join(\"; \");\n\n return ` ${JSON.stringify(route.pattern)}: { ${pathType} };`;\n}\n\nfunction renderConcretePathEntry(route: RouteInfo) {\n return ` ${JSON.stringify(route.pattern)}: ${toConcretePathType(route.pattern)};`;\n}\n\nfunction renderRequestContextEntry(route: RouteInfo) {\n const contexts = route.contextMiddleware\n .map((index) => `__DemiurgeMiddlewareContext${index}`);\n const context = contexts.length > 0\n ? contexts.join(\" & \")\n : \"Record<never, never>\";\n\n return ` ${JSON.stringify(route.pattern)}: ${context};`;\n}\n\nfunction toConcretePathType(pattern: string) {\n if (!pattern.includes(\"[\")) {\n return JSON.stringify(pattern);\n }\n\n const parts = pattern.split(/(\\[\\.\\.\\.[^\\]]+\\]|\\[[^\\]]+\\])/g).filter(Boolean);\n return `\\`${parts.map((part) => (part.startsWith(\"[\") ? \"${PathValue}\" : escapeTemplate(part))).join(\"\")}\\``;\n}\n\nfunction escapeTemplate(value: string) {\n return value.replace(/[`$\\\\]/g, \"\\\\$&\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport { parseAst, transformWithEsbuild } from \"vite\";\nimport type { HttpMethod } from \"../route\";\nimport {\n createSecurityHeaders,\n security,\n validateCorsPolicy,\n validateRateLimitPolicy,\n type ContentSecurityPolicy,\n type CorsPolicy,\n type RoutePolicy,\n type RouteSecurityPolicy,\n type SecurityPolicy,\n} from \"../security\";\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\nexport type StaticPolicyFinding = {\n code: \"cors-invalid\" | \"cors-method-unavailable\" | \"rate-limit-invalid\" |\n \"security-header-render-failed\";\n exportName?: string;\n file: string;\n message: string;\n severity: \"error\";\n};\n\ntype ExtractedCapability = {\n cors?: CorsPolicy;\n security?: RouteSecurityPolicy;\n};\n\ntype ExtractedRouteModule = {\n capabilities: Partial<Record<HttpMethod, ExtractedCapability>>;\n declaredMethods: Set<HttpMethod>;\n policy?: RoutePolicy;\n};\n\nconst httpMethods = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n] as const satisfies readonly HttpMethod[];\nconst responseHelpers = new Set([\n \"action\",\n \"html\",\n \"json\",\n \"jsonl\",\n \"notFound\",\n \"redirect\",\n \"response\",\n \"sse\",\n \"stream\",\n \"text\",\n]);\n\nexport async function verifyRoutePolicyFile(file: string) {\n const source = await readFile(file, \"utf8\");\n return await verifyRoutePolicySource(source, file);\n}\n\nexport async function verifyRoutePolicySource(source: string, file: string) {\n const loader = file.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n const transformed = await transformWithEsbuild(source, file, {\n format: \"esm\",\n loader,\n target: \"esnext\",\n });\n const extracted = extractRouteModule(transformed.code);\n\n return validateExtractedRouteModule(extracted, file);\n}\n\nfunction extractRouteModule(code: string): ExtractedRouteModule {\n const ast = parseAst(code) as unknown as AstNode;\n const imports = collectCoreImports(ast);\n const constants = collectConstants(ast);\n const declarations = collectVariableInitializers(ast);\n const exports = collectNamedExports(ast);\n const capabilities: ExtractedRouteModule[\"capabilities\"] = {};\n const declaredMethods = new Set<HttpMethod>();\n let policy: RoutePolicy | undefined;\n\n for (const [exportName, localName] of exports) {\n const initializer = declarations.get(localName);\n\n if (exportName === \"policy\") {\n if (initializer) {\n policy = extractRoutePolicy(initializer, imports, constants);\n }\n continue;\n }\n if (!isHttpMethod(exportName)) continue;\n declaredMethods.add(exportName);\n if (!initializer) continue;\n\n const capability = extractCapability(initializer, imports, constants);\n if (capability) capabilities[exportName] = capability;\n }\n\n return { capabilities, declaredMethods, policy };\n}\n\nfunction collectVariableInitializers(ast: AstNode) {\n const declarations = new Map<string, AstNode>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (name && initializer) declarations.set(name, initializer);\n }\n }\n return declarations;\n}\n\nfunction collectNamedExports(ast: AstNode) {\n const exports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n if (name) exports.set(name, name);\n }\n }\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local) exports.set(exported, local);\n }\n }\n return exports;\n}\n\nfunction extractCapability(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n) {\n if (node.type !== \"CallExpression\") return undefined;\n const localName = identifierName(node.callee);\n const helper = localName ? imports.get(localName) : undefined;\n\n if (!helper || !responseHelpers.has(helper)) return undefined;\n const arguments_ = asNodeArray(node.arguments);\n const optionsNode = helper === \"action\" ? arguments_[0] : arguments_[1];\n if (!optionsNode) return {};\n const cors = evaluateObjectProperty(optionsNode, \"cors\", constants);\n const securityPolicy = evaluateObjectProperty(\n optionsNode,\n \"security\",\n constants,\n );\n\n return {\n cors: isRecord(cors) ? cors as CorsPolicy : undefined,\n security: isRecord(securityPolicy)\n ? securityPolicy as RouteSecurityPolicy\n : undefined,\n } satisfies ExtractedCapability;\n}\n\nfunction evaluateObjectProperty(\n node: AstNode,\n property: string,\n constants: Map<string, unknown>,\n) {\n if (node.type === \"Identifier\") {\n const value = constants.get(String(node.name));\n return isRecord(value) ? value[property] : unresolved;\n }\n if (node.type !== \"ObjectExpression\") return unresolved;\n\n let value: unknown = undefined;\n for (const item of asNodeArray(node.properties)) {\n if (item.type !== \"Property\" || item.computed) return unresolved;\n if (propertyName(item.key) !== property) continue;\n value = evaluateLiteral(asNode(item.value), constants);\n }\n\n return value;\n}\n\nfunction extractRoutePolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): RoutePolicy | undefined {\n if (node.type === \"CallExpression\") {\n const localName = identifierName(node.callee);\n if (localName && imports.get(localName) === \"defineRoutePolicy\") {\n const argument = asNodeArray(node.arguments)[0];\n return argument\n ? extractRoutePolicy(argument, imports, constants)\n : undefined;\n }\n }\n\n if (node.type !== \"ObjectExpression\") {\n const value = evaluateLiteral(node, constants);\n return isRecord(value) ? value as RoutePolicy : undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return undefined;\n const name = propertyName(property.key);\n const valueNode = asNode(property.value);\n if (!name || !valueNode) return undefined;\n\n if (name === \"document\") {\n const document = extractSecurityPolicy(valueNode, imports, constants);\n if (!document) return undefined;\n result.document = document;\n continue;\n }\n\n const value = evaluateLiteral(valueNode, constants);\n if (value === unresolved) return undefined;\n result[name] = value;\n }\n\n return result as RoutePolicy;\n}\n\nfunction extractSecurityPolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): SecurityPolicy | undefined {\n if (node.type !== \"CallExpression\") {\n const value = evaluateLiteral(node, constants);\n return isRecord(value) ? value as SecurityPolicy : undefined;\n }\n\n const callee = asNode(node.callee);\n if (callee?.type !== \"MemberExpression\") return undefined;\n const objectName = identifierName(callee.object);\n const preset = propertyName(callee.property);\n if (!objectName || imports.get(objectName) !== \"security\" || !preset) {\n return undefined;\n }\n\n const options = evaluateLiteral(asNodeArray(node.arguments)[0], constants);\n if (options !== unresolved && options !== undefined && !isRecord(options)) {\n return undefined;\n }\n\n if (preset === \"api\") return security.api(options as never);\n if (preset === \"crossOriginIsolated\") {\n return security.crossOriginIsolated(options as never);\n }\n if (preset === \"static\") return security.static(options as never);\n if (preset === \"strict\") return security.strict(options as never);\n return undefined;\n}\n\nfunction validateExtractedRouteModule(\n routeModule: ExtractedRouteModule,\n file: string,\n) {\n const findings: StaticPolicyFinding[] = [];\n const availableMethods = new Set(routeModule.declaredMethods);\n if (availableMethods.has(\"GET\")) availableMethods.add(\"HEAD\");\n // Demiurge answers preflight itself, so a route never exports an OPTIONS\n // capability to serve one. Listing OPTIONS is a habit carried in from other\n // CORS configuration, and rejecting it would fail a build over nothing.\n availableMethods.add(\"OPTIONS\");\n\n for (const [exportName, capability] of Object.entries(\n routeModule.capabilities,\n ) as Array<[HttpMethod, ExtractedCapability]>) {\n if (capability.cors) {\n try {\n validateCorsPolicy(capability.cors);\n } catch (error) {\n findings.push(finding(\n \"cors-invalid\",\n file,\n errorMessage(error, \"The CORS policy is invalid.\"),\n exportName,\n ));\n }\n\n for (const method of capability.cors.methods ?? []) {\n if (!availableMethods.has(method)) {\n findings.push(finding(\n \"cors-method-unavailable\",\n file,\n `CORS method ${method} is not available from this route.`,\n exportName,\n ));\n }\n }\n }\n\n validateRateLimit(capability.security, file, exportName, findings);\n }\n\n validateRateLimit(routeModule.policy?.security, file, undefined, findings);\n if (routeModule.policy?.document) {\n try {\n createSecurityHeaders(toFragmentDocument(routeModule.policy.document), {\n nonce: \"build-verification-nonce\",\n });\n } catch (error) {\n findings.push(finding(\n \"security-header-render-failed\",\n file,\n errorMessage(error, \"The security headers are invalid.\"),\n ));\n }\n }\n\n return findings;\n}\n\n// A build reads one file at a time, but policy cascades. A file declaring no\n// reporting endpoints of its own inherits them. Its `csp.reportTo` therefore\n// names a group only the merged policy resolves, which\n// `validateRouteModules(...)` checks during startup. A file declaring its own\n// endpoint map is self-contained. A name outside that map stays a build\n// error, because that is the typo worth catching early.\nfunction toFragmentDocument(document: SecurityPolicy): SecurityPolicy {\n const endpoints = document.headers?.reportingEndpoints;\n const declaresEndpoints = Boolean(\n endpoints && Object.keys(endpoints).length,\n );\n const reportTo = document.csp === false ? undefined : document.csp?.reportTo;\n\n if (declaresEndpoints || !reportTo) {\n return document;\n }\n\n return {\n ...document,\n csp: { ...document.csp as ContentSecurityPolicy, reportTo: undefined },\n headers: endpoints\n ? { ...document.headers, reportingEndpoints: undefined }\n : document.headers,\n };\n}\n\nfunction validateRateLimit(\n securityPolicy: RouteSecurityPolicy | undefined,\n file: string,\n exportName: string | undefined,\n findings: StaticPolicyFinding[],\n) {\n if (!securityPolicy?.rateLimit) return;\n try {\n validateRateLimitPolicy(securityPolicy.rateLimit);\n } catch (error) {\n findings.push(finding(\n \"rate-limit-invalid\",\n file,\n errorMessage(error, \"The rate limit policy is invalid.\"),\n exportName,\n ));\n }\n}\n\nfunction finding(\n code: StaticPolicyFinding[\"code\"],\n file: string,\n message: string,\n exportName?: string,\n): StaticPolicyFinding {\n return { code, exportName, file, message, severity: \"error\" };\n}\n\nfunction collectCoreImports(ast: AstNode) {\n const imports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (\n statement.type !== \"ImportDeclaration\" ||\n asNode(statement.source)?.value !== \"@demiurgejs/core\"\n ) continue;\n for (const specifier of asNodeArray(statement.specifiers)) {\n if (specifier.type !== \"ImportSpecifier\") continue;\n const local = identifierName(specifier.local);\n const imported = propertyName(specifier.imported);\n if (local && imported) imports.set(local, imported);\n }\n }\n return imports;\n}\n\nfunction collectConstants(ast: AstNode) {\n const constants = new Map<string, unknown>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (!name || !initializer) continue;\n const value = evaluateLiteral(initializer, constants);\n if (value !== unresolved) constants.set(name, value);\n }\n }\n return constants;\n}\n\nconst unresolved = Symbol(\"unresolved\");\n\nfunction evaluateLiteral(\n node: AstNode | undefined,\n constants: Map<string, unknown>,\n): unknown | typeof unresolved {\n if (!node) return undefined;\n if (node.type === \"Literal\") return node.value;\n if (node.type === \"Identifier\") {\n if (node.name === \"undefined\") return undefined;\n return constants.has(String(node.name))\n ? constants.get(String(node.name))\n : unresolved;\n }\n if (node.type === \"TemplateLiteral\") {\n if (asNodeArray(node.expressions).length) return unresolved;\n return asNodeArray(node.quasis)\n .map((quasi) => asNode(quasi.value)?.cooked ?? \"\")\n .join(\"\");\n }\n if (node.type === \"UnaryExpression\") {\n const value = evaluateLiteral(asNode(node.argument), constants);\n if (typeof value !== \"number\") return unresolved;\n if (node.operator === \"-\") return -value;\n if (node.operator === \"+\") return value;\n return unresolved;\n }\n if (node.type === \"ArrayExpression\") {\n const values: unknown[] = [];\n for (const element of asNodeArray(node.elements)) {\n const value = evaluateLiteral(element, constants);\n if (value === unresolved) return unresolved;\n values.push(value);\n }\n return values;\n }\n if (node.type === \"ObjectExpression\") {\n const value: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return unresolved;\n const name = propertyName(property.key);\n const child = evaluateLiteral(asNode(property.value), constants);\n if (!name || child === unresolved) return unresolved;\n value[name] = child;\n }\n return value;\n }\n return unresolved;\n}\n\nfunction isHttpMethod(value: string): value is HttpMethod {\n return httpMethods.includes(value as HttpMethod);\n}\n\nfunction errorMessage(error: unknown, fallback: string) {\n return error instanceof Error ? error.message : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asNode(value: unknown) {\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction identifierName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" ? String(node.name) : undefined;\n}\n\nfunction propertyName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" || node?.type === \"Literal\"\n ? String(node.name ?? node.value)\n : undefined;\n}\n","import { existsSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { dirname, join, resolve, relative, sep } from \"node:path\";\nimport MagicString from \"magic-string\";\nimport {\n type ConfigEnv,\n parseAst,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n} from \"vite\";\nimport { renderDocument } from \"../document\";\nimport type {\n LinkTag,\n ResolvedMetadata,\n ScriptTag,\n} from \"../document\";\nimport { PACKAGE_NAME } from \"../package-name\";\nimport { generateRoutes } from \"../routing/generate\";\nimport {\n createRouteManifest,\n findRouteMatch,\n type RouteManifest,\n} from \"../router\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n renderPageDocument,\n type PageRenderer,\n} from \"../server\";\nimport {\n type RouteImporter,\n type RouteModule,\n} from \"../route\";\nimport {\n UnsupportedMethodError,\n toWebRequest,\n writeNotImplemented,\n writeWebResponse,\n} from \"../node/http\";\nimport { renderStreamingPageResponse } from \"../node/streaming\";\nimport { createCspNonce } from \"../security/policy\";\nimport {\n verifyRoutePolicyFile,\n type StaticPolicyFinding,\n} from \"./policy-verification\";\nimport type {\n StaticFileHeaderPatternRule,\n VercelStaticDeployment,\n} from \"../static\";\n\nexport type DemiurgeVitePluginOptions = {\n document?: {\n lang?: string;\n title?: string;\n };\n routesDir?: string;\n static?: {\n deployment?: VercelStaticDeployment;\n headers?: readonly StaticFileHeaderPatternRule[];\n };\n styles?: false | string;\n typedRoutes?: boolean | {\n outputFile?: string;\n };\n};\n\nexport type DemiurgeVitePluginApi = {\n demiurge: true;\n staticDeployment?: VercelStaticDeployment;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\nconst CLIENT_ENTRY_ID = \"virtual:demiurge/client-entry\";\nconst DEV_CLIENT_ENTRY_PATH = `/@id/${CLIENT_ENTRY_ID}`;\nconst RESOLVED_CLIENT_ENTRY_ID = `\\0${CLIENT_ENTRY_ID}`;\nconst SERVER_ENTRY_ID = \"virtual:demiurge/server-entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\nconst DEFAULT_TYPED_ROUTES_OUTPUT = \".demiurge/route-manifest.d.ts\";\nexport function demiurge(options: DemiurgeVitePluginOptions = {}): Plugin {\n let root = process.cwd();\n let isBuild = false;\n const viteNoncePlaceholder = `demiurge-${createCspNonce()}`;\n\n return {\n api: {\n demiurge: true,\n staticDeployment: options.static?.deployment,\n staticFileHeaders: options.static?.headers,\n } satisfies DemiurgeVitePluginApi,\n enforce: \"post\",\n name: \"demiurge\",\n config(config, environment) {\n return createViteConfig(config, environment, viteNoncePlaceholder);\n },\n configResolved(config) {\n root = config.root;\n isBuild = config.command === \"build\";\n },\n resolveId(id) {\n if (id === CLIENT_ENTRY_ID) {\n return RESOLVED_CLIENT_ENTRY_ID;\n }\n\n if (id === SERVER_ENTRY_ID) {\n return RESOLVED_SERVER_ENTRY_ID;\n }\n\n return null;\n },\n load(id) {\n if (id === RESOLVED_CLIENT_ENTRY_ID) {\n return createClientEntrySource(root, options);\n }\n\n if (id === RESOLVED_SERVER_ENTRY_ID) {\n return createServerEntrySource(root, options);\n }\n\n return null;\n },\n transform: {\n order: \"post\",\n handler(code, id, transformOptions) {\n if (!isRouteSource(root, options, id)) {\n return null;\n }\n\n if (transformOptions?.ssr) {\n return isBuild ? null : protectSsrImportMeta(code, id);\n }\n\n const transformed = stripClientPageData(code);\n return transformed === code ? null : { code: transformed, map: null };\n },\n },\n generateBundle(_outputOptions, bundle) {\n const entry = Object.values(bundle).find(\n (item) =>\n item.type === \"chunk\" &&\n item.isEntry &&\n item.facadeModuleId === RESOLVED_CLIENT_ENTRY_ID,\n );\n\n if (!entry) {\n return;\n }\n\n const styles = Object.values(bundle)\n .filter(\n (asset): asset is Extract<(typeof bundle)[string], { type: \"asset\" }> =>\n asset.type === \"asset\" && asset.fileName.endsWith(\".css\"),\n )\n .map((asset) => `/${asset.fileName}`);\n const clientEntry = `/${entry.fileName}`;\n\n this.emitFile({\n fileName: \"index.html\",\n source: createDocumentHtml({\n entrySrc: clientEntry,\n lang: options.document?.lang,\n styles,\n title: options.document?.title,\n }),\n type: \"asset\",\n });\n this.emitFile({\n fileName: \"demiurge-manifest.json\",\n source: JSON.stringify({ clientEntry, styles }, null, 2),\n type: \"asset\",\n });\n },\n async buildStart() {\n if (isBuild) {\n await assertRootNotFoundRoute(root, options);\n const findings = await verifyRoutePolicies(root, options);\n\n if (findings.length) {\n throw new Error(formatStaticPolicyFindings(findings));\n }\n }\n\n if (!options.typedRoutes) {\n return;\n }\n\n await generateTypedRoutes(root, options);\n },\n configureServer(server) {\n const reportPolicyFindings = async () => {\n const findings = await verifyRoutePolicies(server.config.root, options);\n\n for (const finding of findings) {\n server.config.logger.warn(formatStaticPolicyFinding(finding));\n }\n };\n // A single editor save can fire several watcher events, and a branch\n // switch fires one per route file. Collapse a burst into one scan, and\n // chain scans so two never walk the route tree at the same time.\n let policyVerificationTimer: ReturnType<typeof setTimeout> | undefined;\n let policyVerificationRun = Promise.resolve();\n const runPolicyVerification = () => {\n policyVerificationRun = policyVerificationRun\n .then(reportPolicyFindings)\n .catch(() => {\n // Vite reports route read and syntax errors through its module pipeline.\n });\n };\n const startPolicyVerification = () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n }\n\n policyVerificationTimer = setTimeout(() => {\n policyVerificationTimer = undefined;\n runPolicyVerification();\n }, policyVerificationDebounceMs);\n policyVerificationTimer.unref?.();\n };\n\n server.httpServer?.once(\"close\", () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n policyVerificationTimer = undefined;\n }\n });\n\n runPolicyVerification();\n if (options.typedRoutes) {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n\n void generateTypedRoutes(server.config.root, options);\n server.watcher.add(routesDir);\n server.watcher.on(\"add\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"change\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"unlink\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n } else {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n server.watcher.add(routesDir);\n for (const event of [\"add\", \"change\", \"unlink\"] as const) {\n server.watcher.on(event, (file) => {\n if (isRouteFile(routesDir, file)) startPolicyVerification();\n });\n }\n }\n\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n // Vite performs its own configured host allowlist check before\n // Demiurge's middleware runs. Production Node listeners require\n // an explicit application allowlist instead.\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const result = await handleDevRequest(\n manifest,\n webRequest,\n createDevRuntimeOptions(options, documentSecurity.transform),\n );\n\n if (result === \"next\") {\n // Vite owns its own asset URLs, so an unmatched request still\n // falls through. The post middleware below is what turns whatever\n // Vite could not serve into the same negotiated not-found\n // production returns.\n next();\n return;\n }\n\n applyDevDocumentSecurity(result, documentSecurity.nonce);\n await writeWebResponse(response, result);\n } catch (error) {\n next(error);\n }\n });\n\n // The returned hook registers this after the Vite middleware. It sees\n // only requests that Vite cannot serve. `appType` is \"custom\", so no SPA\n // fallback intercepts these requests. Development and production render\n // the same negotiated not-found response for an unmatched path.\n return () => {\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n\n warnMissingRootNotFound(manifest, routesDir);\n\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n webRequest,\n createDevFallbackOptions(options, documentSecurity.transform),\n );\n applyDevDocumentSecurity(\n notFoundResponse,\n documentSecurity.nonce,\n );\n await writeWebResponse(response, notFoundResponse);\n } catch (error) {\n next(error);\n }\n });\n };\n },\n };\n}\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\n// Vite 6 treats the `meta` token in `import.meta` as an imported reference.\n// Give an imported `meta` binding a private name before development SSR runs.\nfunction protectSsrImportMeta(code: string, id: string) {\n if (!code.includes(\"import.meta\")) {\n return null;\n }\n\n const ast = parseAst(code) as unknown as AstNode;\n const declaration = asNodeArray(ast.body).find((node) =>\n node.type === \"ImportDeclaration\" &&\n asNodeArray(node.specifiers).some((specifier) =>\n asNode(specifier.local)?.type === \"Identifier\" &&\n asNode(specifier.local)?.name === \"meta\"\n )\n );\n const specifier = declaration &&\n asNodeArray(declaration.specifiers).find((candidate) =>\n asNode(candidate.local)?.type === \"Identifier\" &&\n asNode(candidate.local)?.name === \"meta\"\n );\n const local = specifier && asNode(specifier.local);\n\n if (!declaration || !specifier || !local) {\n return null;\n }\n\n let alias = \"__demiurge_imported_meta__\";\n while (new RegExp(`\\\\b${alias}\\\\b`).test(code)) {\n alias += \"_\";\n }\n\n const editor = new MagicString(code);\n const imported = asNode(specifier.imported);\n editor.overwrite(\n local.start,\n local.end,\n imported?.start === local.start ? `meta as ${alias}` : alias,\n );\n editor.appendLeft(declaration.end, `\\nconst meta = ${alias};`);\n\n return {\n code: editor.toString(),\n map: editor.generateMap({\n hires: \"boundary\",\n includeContent: true,\n source: id,\n }),\n };\n}\n\n// Page data and document contributions are server capabilities. Vite and React\n// first parse TypeScript and JSX. The plugin then removes these capabilities\n// before Rollup follows the final client graph. This sequence excludes request\n// code and server-only imports from browser chunks. The exported document\n// bindings remain as `undefined` so the\n// route module keeps a stable shape without evaluating their initializers.\nexport function stripClientPageData(code: string) {\n const ast = parseAst(code) as unknown as AstNode;\n const dataRanges: Array<{ end: number; start: number }> = [];\n const documentRanges = findDocumentContributionRanges(ast);\n const serverImports: AstNode[] = [];\n\n walkAst(ast, (node) => {\n if (node.type === \"ImportDeclaration\" && isServerOnlyImport(node)) {\n serverImports.push(node);\n return;\n }\n\n if (node.type !== \"CallExpression\" || !isPageCallee(node.callee)) {\n return;\n }\n\n const argument = asNodeArray(node.arguments)[0];\n if (argument?.type !== \"ObjectExpression\") {\n return;\n }\n\n for (const property of asNodeArray(argument.properties)) {\n if (property.type === \"Property\" && propertyName(property.key) === \"data\") {\n dataRanges.push({ end: property.end, start: property.start });\n }\n }\n });\n\n const serverRanges = [...dataRanges, ...documentRanges];\n\n if (serverRanges.length === 0) {\n return code;\n }\n\n const removalRanges = [...serverRanges];\n for (const declaration of serverImports) {\n const localNames = asNodeArray(declaration.specifiers)\n .map((specifier) => asNode(specifier.local))\n .filter((local): local is AstNode => local?.type === \"Identifier\")\n .map((local) => String(local.name));\n const masked = maskRanges(code, [\n ...serverRanges,\n { end: declaration.end, start: declaration.start },\n ]);\n const leakedName = localNames.find((name) =>\n new RegExp(`\\\\b${escapeRegExp(name)}\\\\b`).test(masked)\n );\n\n if (leakedName) {\n throw new Error(\n `Server-only import ${JSON.stringify(leakedName)} is used by client route code. Move that use into page data, a document contribution, or a client-safe module.`,\n );\n }\n\n removalRanges.push({ end: declaration.end, start: declaration.start });\n }\n\n return replaceRanges(code, removalRanges, (range) =>\n dataRanges.includes(range) ? \"data: undefined\" :\n documentRanges.includes(range) ? \"undefined\" : \"\"\n );\n}\n\nconst documentContributionNames = new Set([\"links\", \"metadata\", \"scripts\"]);\n\nfunction findDocumentContributionRanges(ast: AstNode) {\n const exportedLocals = new Set<string>();\n\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const id = asNode(declarator.id);\n if (\n id?.type === \"Identifier\" &&\n documentContributionNames.has(String(id.name))\n ) {\n exportedLocals.add(String(id.name));\n }\n }\n }\n\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local && documentContributionNames.has(exported)) {\n exportedLocals.add(local);\n }\n }\n }\n\n const ranges: Array<{ end: number; start: number }> = [];\n walkAst(ast, (node) => {\n if (node.type !== \"VariableDeclarator\") return;\n const id = asNode(node.id);\n const init = asNode(node.init);\n if (\n id?.type === \"Identifier\" &&\n exportedLocals.has(String(id.name)) &&\n init\n ) {\n ranges.push({ end: init.end, start: init.start });\n }\n });\n\n return ranges;\n}\n\nfunction isRouteSource(\n root: string,\n options: DemiurgeVitePluginOptions,\n id: string,\n) {\n const file = id.split(\"?\", 1)[0] ?? id;\n const routesRoot = resolve(root, options.routesDir ?? \"src/routes\");\n const pathFromRoutes = relative(routesRoot, file);\n return pathFromRoutes !== \"\" &&\n pathFromRoutes !== \"..\" &&\n !pathFromRoutes.startsWith(`..${sep}`);\n}\n\nfunction walkAst(value: unknown, visit: (node: AstNode) => void) {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n\n const node = value as Partial<AstNode>;\n if (typeof node.type !== \"string\") return;\n visit(node as AstNode);\n for (const [key, child] of Object.entries(node)) {\n if (!new Set([\"end\", \"loc\", \"start\", \"type\"]).has(key)) {\n walkAst(child, visit);\n }\n }\n}\n\nfunction asNode(value: unknown) {\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction isPageCallee(value: unknown) {\n const callee = asNode(value);\n if (callee?.type === \"Identifier\") return callee.name === \"page\";\n return callee?.type === \"MemberExpression\" &&\n propertyName(callee.property) === \"page\";\n}\n\nfunction propertyName(value: unknown) {\n const property = asNode(value);\n return property?.type === \"Identifier\" || property?.type === \"Literal\"\n ? String(property.name ?? property.value)\n : undefined;\n}\n\nfunction isServerOnlyImport(node: AstNode) {\n const source = asNode(node.source)?.value;\n return typeof source === \"string\" &&\n /(?:^|[/.-])server(?:[/.-]|$)/.test(source);\n}\n\nfunction maskRanges(code: string, ranges: Array<{ end: number; start: number }>) {\n const characters = [...code];\n for (const { end, start } of ranges) {\n characters.fill(\" \", start, end);\n }\n return characters.join(\"\");\n}\n\nfunction replaceRanges(\n code: string,\n ranges: Array<{ end: number; start: number }>,\n replacement: (range: { end: number; start: number }) => string,\n) {\n return [...ranges]\n .sort((left, right) => right.start - left.start)\n .reduce(\n (result, range) =>\n `${result.slice(0, range.start)}${replacement(range)}${result.slice(range.end)}`,\n code,\n );\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction createViteConfig(\n config: UserConfig,\n environment: ConfigEnv,\n viteNoncePlaceholder: string,\n): UserConfig {\n return {\n appType: \"custom\",\n build: {\n assetsInlineLimit: config.build?.assetsInlineLimit ?? 0,\n ...(environment.isSsrBuild &&\n config.build?.target === undefined &&\n config.ssr?.target !== \"webworker\"\n ? { target: \"node22.13\" }\n : {}),\n rollupOptions: {\n input: config.build?.rollupOptions?.input ?? CLIENT_ENTRY_ID,\n },\n },\n ...(environment.command === \"serve\"\n ? {\n html: { cspNonce: viteNoncePlaceholder },\n ssr: { external: [PACKAGE_NAME] },\n }\n : {}),\n };\n}\n\nexport function createClientEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n const stylesImport = createStylesImport(root, options);\n\n return `import { hydrateFileRouter } from \"${PACKAGE_NAME}\";\n${stylesImport}\n\n${createRouteMapSource(routesDir, {\n exportRoutes: false,\n includeServerOnly: false,\n })}\n\nvoid hydrateFileRouter({ routes });\n`;\n}\n\nexport function createServerEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n\n return `import { createRequestHandler } from \"${PACKAGE_NAME}\";\n\n${createRouteMapSource(routesDir, {\n exportRoutes: true,\n includeServerOnly: true,\n eagerModules: true,\n })}\n\nexport function createHandler(options = {}) {\n const { clientEntry, lang, styles, title, ...handlerOptions } = options;\n\n return createRequestHandler({\n ...handlerOptions,\n routes,\n routeModules,\n ssr: {\n clientEntry,\n lang: lang ?? ${JSON.stringify(options.document?.lang)},\n styles,\n title: title ?? ${JSON.stringify(options.document?.title)},\n },\n });\n}\n`;\n}\n\n// Both virtual entries use this function. Therefore, their prefix removal and\n// route-key formats stay equal. The server entry requires framework-attached\n// `.ts` files such as `@policy.ts` and `@middleware.ts`. Previously, a\n// `.tsx`-only glob omitted these files from production. Development still found\n// and applied them.\nfunction createRouteMapSource(\n routesDir: string,\n {\n exportRoutes,\n eagerModules = false,\n includeServerOnly,\n }: {\n eagerModules?: boolean;\n exportRoutes: boolean;\n includeServerOnly: boolean;\n },\n) {\n const routesGlobs = toRootAbsoluteGlobs(routesDir, includeServerOnly);\n const routesPrefix = toRootAbsolutePrefix(routesDir);\n\n return eagerModules\n ? `const eagerRouteModules = import.meta.glob(${JSON.stringify(routesGlobs)}, { eager: true });\nconst routePrefix = ${JSON.stringify(routesPrefix)};\nexport const routeModules = Object.fromEntries(\n Object.entries(eagerRouteModules).map(([file, module]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n module,\n ]),\n);\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, module]) => [\n file,\n async () => module,\n ]),\n);`\n : `const routeModules = import.meta.glob(${JSON.stringify(routesGlobs)});\nconst routePrefix = ${JSON.stringify(routesPrefix)};\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, load]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n load,\n ]),\n);`;\n}\n\n// These two files run only on the server. They control a request before the\n// route runs and do not render. A client glob would create public chunks in\n// `dist/client`. These chunks could expose credentials, authorization logic, or\n// internal host names from a middleware or policy closure.\nconst serverOnlyRouteFiles = [\"@middleware.ts\", \"@policy.ts\"];\n\nfunction toRootAbsoluteGlobs(routesDir: string, includeServerOnly: boolean) {\n const base = `/${routesDir.replace(/^\\/|\\/$/g, \"\")}`;\n const globs = [`${base}/**/*.{ts,tsx}`];\n\n if (!includeServerOnly) {\n globs.push(\n ...serverOnlyRouteFiles.flatMap((fileName) => [\n `!${base}/${fileName}`,\n `!${base}/**/${fileName}`,\n ]),\n );\n }\n\n return globs;\n}\n\nfunction toRootAbsolutePrefix(routesDir: string) {\n return `/${routesDir.replace(/^\\/|\\/$/g, \"\")}/`;\n}\n\nfunction createStylesImport(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n if (options.styles === false) {\n return \"\";\n }\n\n const stylesFile = options.styles ?? \"src/styles.css\";\n const resolvedStylesFile = resolve(root, stylesFile);\n\n return existsSync(resolvedStylesFile)\n ? `import ${JSON.stringify(`/${stylesFile.replace(/^\\/+/, \"\")}`)};`\n : \"\";\n}\n\n// Development renders through the production pipeline. It adds the virtual\n// client entry, the Vite HTML transform, and a development flag for stack\n// traces. The shared handler makes all security and routing decisions.\nfunction createDevRuntimeOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n dev: true,\n ssr: createDevSsrOptions(options),\n transformDocument,\n renderPage: async (\n match: Parameters<PageRenderer>[0],\n renderOptions: Parameters<PageRenderer>[1],\n ) => {\n if (match.render.mode === \"streaming\") {\n return await renderStreamingPageResponse(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n transformDocument,\n });\n }\n\n const html = await transformDocument(\n renderPageDocument(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n }),\n );\n\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n },\n };\n}\n\nfunction createDevDocumentSecurity(\n server: ViteDevServer,\n viteNoncePlaceholder: string,\n) {\n const nonce = createCspNonce();\n const shieldNonce = createCspNonce();\n\n return {\n nonce,\n transform: async (html: string) => {\n const shielded = shieldViteNonceTargets(html, shieldNonce);\n const transformed = await server.transformIndexHtml(\"/\", shielded);\n\n return replaceNonceAttribute(\n replaceNonceAttribute(transformed, shieldNonce),\n viteNoncePlaceholder,\n nonce,\n );\n },\n };\n}\n\nfunction shieldViteNonceTargets(html: string, nonce: string) {\n const lowerHtml = html.toLowerCase();\n let cursor = 0;\n let output = \"\";\n\n while (cursor < html.length) {\n const tagStart = html.indexOf(\"<\", cursor);\n\n if (tagStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, tagStart);\n\n if (lowerHtml.startsWith(\"<!--\", tagStart)) {\n const commentEnd = lowerHtml.indexOf(\"-->\", tagStart + 4);\n const end = commentEnd === -1 ? html.length : commentEnd + 3;\n output += html.slice(tagStart, end);\n cursor = end;\n continue;\n }\n\n const name = lowerHtml.slice(tagStart).match(/^<\\s*(script|style|link)\\b/)?.[1];\n\n if (!name) {\n output += \"<\";\n cursor = tagStart + 1;\n continue;\n }\n\n const tagEnd = findHtmlTagEnd(html, tagStart);\n\n if (tagEnd === -1) {\n return output + html.slice(tagStart);\n }\n\n const openingTag = html.slice(tagStart, tagEnd + 1);\n output += /(?:^|\\s)nonce(?:\\s|=|>)/i.test(openingTag)\n ? openingTag\n : addNonceAttribute(openingTag, nonce);\n cursor = tagEnd + 1;\n\n if (name === \"script\" || name === \"style\") {\n const closeStart = lowerHtml.indexOf(`</${name}`, cursor);\n\n if (closeStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, closeStart);\n cursor = closeStart;\n }\n }\n\n return output;\n}\n\nfunction findHtmlTagEnd(html: string, start: number) {\n let quote: \"\\\"\" | \"'\" | undefined;\n\n for (let index = start + 1; index < html.length; index++) {\n const character = html[index];\n\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character;\n } else if (character === \">\") {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction addNonceAttribute(openingTag: string, nonce: string) {\n const insertion = /\\/\\s*>$/.test(openingTag)\n ? openingTag.lastIndexOf(\"/\")\n : openingTag.length - 1;\n\n return `${openingTag.slice(0, insertion)} nonce=\"${nonce}\"${openingTag.slice(insertion)}`;\n}\n\nfunction replaceNonceAttribute(\n html: string,\n current: string,\n replacement?: string,\n) {\n const pattern = new RegExp(\n `(\\\\snonce\\\\s*=\\\\s*)([\"'])${escapeRegExp(current)}\\\\2`,\n \"g\",\n );\n\n return html.replace(\n pattern,\n replacement ? `$1\"${replacement}\"` : \"\",\n );\n}\n\nfunction applyDevDocumentSecurity(response: Response, nonce: string) {\n const contentType = response.headers.get(\"content-type\");\n const csp = response.headers.get(\"content-security-policy\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\") || !csp) {\n return;\n }\n\n const source = `'nonce-${nonce}'`;\n const withScriptNonce = addCspSource(\n csp,\n [\"script-src-elem\", \"script-src\"],\n \"script-src\",\n source,\n );\n const withStyleNonce = allowsUnsafeInline(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n )\n ? withScriptNonce\n : addCspSource(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n \"style-src\",\n source,\n );\n\n response.headers.set(\"content-security-policy\", withStyleNonce);\n response.headers.set(\"cache-control\", \"private, no-store\");\n}\n\nfunction addCspSource(\n csp: string,\n directiveNames: readonly string[],\n fallbackDirectiveName: \"script-src\" | \"style-src\",\n source: string,\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n\n if (directiveIndex === -1 && !defaultDirective) return csp;\n\n const [currentName, ...currentSources] =\n (directiveIndex === -1 ? defaultDirective! : directives[directiveIndex]!)\n .split(/\\s+/);\n const updatedDirective = [\n directiveIndex === -1 ? fallbackDirectiveName : currentName!,\n ...new Set([\n ...currentSources.filter((current) => current !== \"'none'\"),\n source,\n ]),\n ].join(\" \");\n\n if (directiveIndex === -1) {\n directives.push(updatedDirective);\n } else {\n directives[directiveIndex] = updatedDirective;\n }\n\n return directives.join(\"; \");\n}\n\nfunction allowsUnsafeInline(\n csp: string,\n directiveNames: readonly string[],\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n const effectiveDirective = directiveIndex === -1\n ? directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n )\n : directives[directiveIndex];\n const sources = effectiveDirective?.split(/\\s+/).slice(1) ?? [];\n\n return sources.includes(\"'unsafe-inline'\") &&\n !sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-)/i.test(source));\n}\n\nfunction findCspDirectiveIndex(\n directives: readonly string[],\n directiveNames: readonly string[],\n) {\n for (const name of directiveNames) {\n const index = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === name\n );\n\n if (index !== -1) return index;\n }\n\n return -1;\n}\n\n// Both dev middlewares need the manifest for the same request, and building\n// it walks the routes directory. The pre middleware always runs, so the post\n// middleware reuses what it already produced rather than scanning twice on\n// every unmatched request.\nconst DEV_MANIFEST = Symbol.for(\"demiurge.devManifest\");\n\ntype DevManifestCarrier = { [DEV_MANIFEST]?: RouteManifest };\n\nasync function loadDevManifest(\n server: ViteDevServer,\n request: IncomingMessage,\n routesDir: string,\n) {\n const carrier = request as IncomingMessage & DevManifestCarrier;\n const cached = carrier[DEV_MANIFEST];\n\n if (cached) {\n return cached;\n }\n\n const manifest = createRouteManifest(\n await createDevRouteImporters(server, routesDir),\n );\n\n carrier[DEV_MANIFEST] = manifest;\n\n return manifest;\n}\n\nfunction createDevSsrOptions(options: DemiurgeVitePluginOptions) {\n return {\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n lang: options.document?.lang,\n title: options.document?.title,\n };\n}\n\nfunction createDevFallbackOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n ...createDevSsrOptions(options),\n dev: true,\n transformDocument,\n };\n}\n\nconst warnedRoots = new Set<string>();\n\n// The framework built-in is a temporary fallback, not a production 404. The\n// build gate enforces this rule. This warning gives the same message earlier.\nfunction warnMissingRootNotFound(manifest: RouteManifest, routesDir: string) {\n if (\n warnedRoots.has(routesDir) ||\n manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n )\n ) {\n return;\n }\n\n warnedRoots.add(routesDir);\n console.warn(missingRootNotFoundMessage(join(routesDir, \"@not-found.tsx\")));\n}\n\n// The framework ships a working 404 so nothing is ever blank, and refuses to\n// let an app reach production still rendering it. A generic framework page in\n// front of real users is a failure of the framework, not of the app that never\n// got around to it.\nexport async function assertRootNotFoundRoute(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDirOption = options.routesDir ?? \"src/routes\";\n const routesDir = resolve(root, routesDirOption);\n\n if (!existsSync(routesDir)) {\n return;\n }\n\n const files = await findRouteFiles(routesDir);\n const names = files.map((file) =>\n relative(routesDir, file).split(sep).join(\"/\"),\n );\n\n if (names.some((name) => /^@not-found\\.tsx?$/.test(name))) {\n return;\n }\n\n const pageRoute = await findPageRouteFile(files);\n\n // An API-only app never wants an HTML not-found document, and nagging it\n // would be user hostile. It builds clean and gets problem+json.\n if (!pageRoute) {\n return;\n }\n\n throw new Error(\n missingRootNotFoundBuildMessage(\n routesDirOption,\n relative(routesDir, pageRoute).split(sep).join(\"/\"),\n ),\n );\n}\n\n// Page detection is a source scan rather than a module evaluation: the plugin\n// cannot execute route modules at build time. A page route is a file that\n// calls `page(...)`, which is the only way to declare one.\nasync function findPageRouteFile(files: string[]) {\n for (const file of files) {\n // Framework-attached files own no address, so they are never page routes.\n if (relative(dirname(file), file).startsWith(\"@\")) {\n continue;\n }\n\n if (declaresPageRoute(await readFile(file, \"utf8\"))) {\n return file;\n }\n }\n\n return undefined;\n}\n\n// Escaped because a package name may contain `.`, which the regex would\n// otherwise read as a wildcard.\nconst PACKAGE_NAME_PATTERN = PACKAGE_NAME.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst DEMIURGE_NAMED_IMPORT = new RegExp(\n `import\\\\s*\\\\{([^}]*)\\\\}\\\\s*from\\\\s*[\"']${PACKAGE_NAME_PATTERN}[\"']`,\n \"g\",\n);\n\n// The plugin cannot evaluate route modules during the build. Therefore, page\n// detection reads the source. It checks the import, not only the word. An API\n// application can call `db.users.page(2)` without serving an HTML document.\n// Only a page route imports `page` from the framework package.\nexport function declaresPageRoute(source: string) {\n const locals = [...source.matchAll(DEMIURGE_NAMED_IMPORT)].flatMap((match) =>\n match[1].split(\",\").flatMap((binding) => {\n const [imported, local] = binding.trim().split(/\\s+as\\s+/);\n\n // `import type { page }` cannot be called, and an alias renames what the\n // call site looks like.\n return imported.replace(/^type\\s+/, \"\") === \"page\"\n ? [local ?? imported]\n : [];\n }),\n );\n\n if (locals.length === 0) {\n return false;\n }\n\n // Strip the import statements first so the binding list is not itself\n // mistaken for a call.\n const body = source.replace(DEMIURGE_NAMED_IMPORT, \"\");\n\n return locals.some((local) => new RegExp(`\\\\b${local}\\\\s*\\\\(`).test(body));\n}\n\nexport function missingRootNotFoundBuildMessage(\n routesDir: string,\n pageRoute: string,\n) {\n return `Demiurge will not build an app with page routes and no ${routesDir}/@not-found.tsx.\n\n\"${pageRoute}\" declares a page, so a browser can reach a path this app does not serve. Decide what that looks like rather than shipping the framework built-in.\n\nCreate ${routesDir}/@not-found.tsx:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n\nIt renders inside the layouts above the requested path. Opt out with \"export const layout = false\".`;\n}\n\nexport function missingRootNotFoundMessage(notFoundFile: string) {\n return `Demiurge is serving its built-in 404 because ${notFoundFile} does not exist.\n\nCreate it before building for production:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n`;\n}\n\nexport function createDocumentHtml({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n}: {\n entrySrc: string;\n lang?: string;\n links?: LinkTag[];\n metadata?: ResolvedMetadata;\n nonce?: string;\n scripts?: ScriptTag[];\n styles?: string[];\n title?: string;\n}) {\n return renderDocument({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n });\n}\n\nasync function generateTypedRoutes(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n const outputFile = resolve(\n root,\n typeof options.typedRoutes === \"object\"\n ? options.typedRoutes.outputFile ?? DEFAULT_TYPED_ROUTES_OUTPUT\n : DEFAULT_TYPED_ROUTES_OUTPUT,\n );\n\n await generateRoutes({ outputFile, routesDir });\n}\n\nfunction isRouteFile(routesDir: string, file: string) {\n return (\n file.startsWith(routesDir) &&\n /\\.tsx?$/.test(file)\n );\n}\n\nexport async function createDevRouteImporters(\n server: ViteDevServer,\n routesDir: string,\n) {\n const files = await findRouteFiles(routesDir);\n const routes: Record<string, RouteImporter> = {};\n\n for (const file of files) {\n const routeKey = toRouteKey(routesDir, file);\n routes[routeKey] = async () =>\n (await server.ssrLoadModule(file)) as RouteModule;\n }\n\n return routes;\n}\n\nexport async function handleDevRequest(\n manifest: RouteManifest,\n request: Request,\n options: Parameters<typeof handleRequestWithManifest>[2] = {},\n) {\n const url = new URL(request.url);\n const routeMatch = findRouteMatch(manifest.routes, url.pathname);\n\n if (!routeMatch) {\n return \"next\" as const;\n }\n\n return await handleRequestWithManifest(manifest, request, options);\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\n// Every route file is read and parsed. Without a cap, a large route tree opens\n// one descriptor per file at once, which is how this hits EMFILE rather than a\n// CPU limit.\nconst policyVerificationConcurrency = 8;\nconst policyVerificationDebounceMs = 50;\n\nasync function mapWithConcurrency<Item, Result>(\n items: readonly Item[],\n limit: number,\n task: (item: Item) => Promise<Result>,\n) {\n const results = new Array<Result>(items.length);\n let next = 0;\n\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index]!);\n }\n },\n );\n\n await Promise.all(workers);\n\n return results;\n}\n\nexport async function verifyRoutePolicies(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n\n if (!existsSync(routesDir)) return [];\n const findings = (await mapWithConcurrency(\n await findRouteFiles(routesDir),\n policyVerificationConcurrency,\n verifyRoutePolicyFile,\n )).flat();\n\n return findings.sort((left, right) =>\n left.file.localeCompare(right.file) ||\n (left.exportName ?? \"\").localeCompare(right.exportName ?? \"\") ||\n left.code.localeCompare(right.code)\n );\n}\n\nexport function formatStaticPolicyFindings(findings: StaticPolicyFinding[]) {\n return [\n \"Demiurge found invalid static route policy:\",\n ...findings.map(formatStaticPolicyFinding),\n ].join(\"\\n\");\n}\n\nfunction formatStaticPolicyFinding(finding: StaticPolicyFinding) {\n const source = finding.exportName\n ? `${finding.file} export ${finding.exportName}`\n : finding.file;\n return `${source}: [${finding.code}] ${finding.message}`;\n}\n\nfunction toRouteKey(routesDir: string, file: string) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n return `./routes/${relativePath}`;\n}\n"],"names":["PACKAGE_NAME","generateRoutes","options","routeFiles","findRouteFiles","middleware","file","toMiddlewareInfo","value","routes","toRouteInfo","route","a","b","source","renderRoutesModule","mkdir","dirname","writeFile","directory","readdir","entry","resolve","routesDir","fileSegments","relative","sep","urlSegments","segment","isRouteGroupSegment","pathVars","isAttachedFileForRoute","importPath","attachedFileSegments","routeFileSegments","index","renderMiddlewareImport","_entry","renderMiddlewareContextAlias","renderPathVarsEntry","renderConcretePathEntry","renderRequestContextEntry","pathType","name","toConcretePathType","contexts","context","pattern","part","escapeTemplate","httpMethods","responseHelpers","verifyRoutePolicyFile","readFile","verifyRoutePolicySource","loader","transformed","transformWithEsbuild","extracted","extractRouteModule","validateExtractedRouteModule","code","ast","parseAst","imports","collectCoreImports","constants","collectConstants","declarations","collectVariableInitializers","exports","collectNamedExports","capabilities","declaredMethods","policy","exportName","localName","initializer","extractRoutePolicy","isHttpMethod","capability","extractCapability","statement","asNodeArray","declaration","asNode","declarator","identifierName","specifier","exported","propertyName","local","node","helper","arguments_","optionsNode","cors","evaluateObjectProperty","securityPolicy","isRecord","property","unresolved","item","evaluateLiteral","argument","result","valueNode","document","extractSecurityPolicy","callee","objectName","preset","security","routeModule","findings","availableMethods","validateCorsPolicy","error","finding","errorMessage","method","validateRateLimit","createSecurityHeaders","toFragmentDocument","endpoints","declaresEndpoints","reportTo","validateRateLimitPolicy","message","imported","quasi","values","element","child","fallback","CLIENT_ENTRY_ID","DEV_CLIENT_ENTRY_PATH","RESOLVED_CLIENT_ENTRY_ID","SERVER_ENTRY_ID","RESOLVED_SERVER_ENTRY_ID","DEFAULT_TYPED_ROUTES_OUTPUT","demiurge","root","isBuild","viteNoncePlaceholder","createCspNonce","config","environment","createViteConfig","id","createClientEntrySource","createServerEntrySource","transformOptions","isRouteSource","protectSsrImportMeta","stripClientPageData","_outputOptions","bundle","styles","asset","clientEntry","createDocumentHtml","assertRootNotFoundRoute","verifyRoutePolicies","formatStaticPolicyFindings","generateTypedRoutes","server","reportPolicyFindings","formatStaticPolicyFinding","policyVerificationTimer","policyVerificationRun","runPolicyVerification","startPolicyVerification","policyVerificationDebounceMs","isRouteFile","event","request","response","next","webRequest","toWebRequest","UnsupportedMethodError","writeNotImplemented","manifest","loadDevManifest","documentSecurity","createDevDocumentSecurity","handleDevRequest","createDevRuntimeOptions","applyDevDocumentSecurity","writeWebResponse","warnMissingRootNotFound","notFoundResponse","renderNotFoundResponse","createDevFallbackOptions","candidate","alias","editor","MagicString","dataRanges","documentRanges","findDocumentContributionRanges","serverImports","walkAst","isServerOnlyImport","isPageCallee","serverRanges","removalRanges","localNames","masked","maskRanges","leakedName","escapeRegExp","replaceRanges","range","documentContributionNames","exportedLocals","ranges","init","routesRoot","pathFromRoutes","visit","key","characters","end","start","replacement","left","right","stylesImport","createStylesImport","createRouteMapSource","exportRoutes","eagerModules","includeServerOnly","routesGlobs","toRootAbsoluteGlobs","routesPrefix","toRootAbsolutePrefix","serverOnlyRouteFiles","base","globs","fileName","stylesFile","resolvedStylesFile","existsSync","transformDocument","createDevSsrOptions","match","renderOptions","renderStreamingPageResponse","html","renderPageDocument","nonce","shieldNonce","shielded","shieldViteNonceTargets","replaceNonceAttribute","lowerHtml","cursor","output","tagStart","commentEnd","tagEnd","findHtmlTagEnd","openingTag","addNonceAttribute","closeStart","quote","character","insertion","current","contentType","csp","withScriptNonce","addCspSource","withStyleNonce","allowsUnsafeInline","directiveNames","fallbackDirectiveName","directives","directive","directiveIndex","findCspDirectiveIndex","defaultDirective","currentName","currentSources","updatedDirective","sources","DEV_MANIFEST","carrier","cached","createRouteManifest","createDevRouteImporters","warnedRoots","missingRootNotFoundMessage","join","routesDirOption","files","pageRoute","findPageRouteFile","missingRootNotFoundBuildMessage","declaresPageRoute","PACKAGE_NAME_PATTERN","DEMIURGE_NAMED_IMPORT","locals","binding","body","notFoundFile","entrySrc","lang","links","metadata","scripts","title","renderDocument","outputFile","routeKey","toRouteKey","url","findRouteMatch","handleRequestWithManifest","policyVerificationConcurrency","mapWithConcurrency","items","limit","task","results","workers"],"mappings":";;;;;;;;;;;AASO,MAAMA,IAAe;ACa5B,eAAsBC,GAAeC,GAAgC;AACnE,QAAMC,IAAa,MAAMC,GAAeF,EAAQ,SAAS,GACnDG,IAAaF,EAChB,IAAI,CAACG,MAASC,GAAiBL,GAASI,CAAI,CAAC,EAC7C,OAAO,CAACE,MAAmC,EAAQA,CAAM,GACtDC,IAASN,EACZ,IAAI,CAACG,MAASI,GAAYR,EAAQ,WAAWI,GAAMD,CAAU,CAAC,EAC9D,OAAO,CAACM,MAA8B,EAAQA,CAAM,EACpD,KAAK,CAACC,GAAGC,MAAMD,EAAE,QAAQ,cAAcC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A,EAAS,IAAIsD,EAAyB;AAAA,EAAA,EACzC,KAAK;AAAA,CAAI;AACb;AAEA,SAASA,GAA0BlD,GAA8B;AAI/D,SAAO,GAHQA,EAAQ,aACnB,GAAGA,EAAQ,IAAI,WAAWA,EAAQ,UAAU,KAC5CA,EAAQ,IACI,MAAMA,EAAQ,IAAI,KAAKA,EAAQ,OAAO;AACxD;AAEA,SAASwM,GAAWvS,GAAmBjB,GAAc;AAEnD,SAAO,YADcmB,EAASF,GAAWjB,CAAI,EAAE,MAAMoB,CAAG,EAAE,KAAK,GAAG,CACnC;AACjC;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/package-name.ts","../../src/routing/generate.ts","../../src/vite/policy-verification.ts","../../src/vite/route-audit.ts","../../src/vite/plugin.ts"],"sourcesContent":["// The package name is the specifier that user code imports. Generated client\n// entries, server entries, and route type declarations use it. Page route\n// detection also compares application source with it. A mismatch then breaks\n// resolution in the consumer build.\n//\n// This is deliberately not the same thing as the many internal `demiurge`\n// strings elsewhere in the source. `__demiurge_data`, `virtual:demiurge/*`,\n// `demiurge-manifest.json`, and friends name the framework, not the package,\n// and they stay put if the registry name ever changes.\nexport const PACKAGE_NAME = \"@demiurgejs/core\";\n","import { mkdir, readdir, writeFile } from \"node:fs/promises\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport { PACKAGE_NAME } from \"../package-name\";\n\nexport type GenerateRoutesOptions = {\n outputFile: string;\n routesDir: string;\n};\n\ntype RouteInfo = {\n contextMiddleware: number[];\n fileSegments: string[];\n pathVars: string[];\n pattern: string;\n};\n\ntype MiddlewareInfo = {\n file: string;\n fileSegments: string[];\n importPath: string;\n};\n\nexport async function generateRoutes(options: GenerateRoutesOptions) {\n const routeFiles = await findRouteFiles(options.routesDir);\n const middleware = routeFiles\n .map((file) => toMiddlewareInfo(options, file))\n .filter((value): value is MiddlewareInfo => Boolean(value));\n const routes = routeFiles\n .map((file) => toRouteInfo(options.routesDir, file, middleware))\n .filter((route): route is RouteInfo => Boolean(route))\n .sort((a, b) => a.pattern.localeCompare(b.pattern));\n\n const source = renderRoutesModule(routes, middleware);\n\n await mkdir(dirname(options.outputFile), { recursive: true });\n await writeFile(options.outputFile, source);\n\n return {\n routes,\n source,\n };\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\nfunction toRouteInfo(\n routesDir: string,\n file: string,\n middleware: MiddlewareInfo[],\n) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n const basename = fileSegments.at(-1);\n\n if (basename?.startsWith(\"@\")) {\n return null;\n }\n\n const urlSegments = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment === \"index\") {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment];\n }\n\n return [segment];\n });\n\n const pathVars = fileSegments.flatMap((segment) => {\n if (isRouteGroupSegment(segment)) {\n return [];\n }\n\n if (segment.startsWith(\"[...\") && segment.endsWith(\"]\")) {\n return [segment.slice(4, -1)];\n }\n\n if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n return [segment.slice(1, -1)];\n }\n\n return [];\n });\n\n return {\n contextMiddleware: middleware\n .filter((entry) => isAttachedFileForRoute(entry.fileSegments, fileSegments))\n .map((entry) => middleware.indexOf(entry)),\n fileSegments,\n pathVars,\n pattern: `/${urlSegments.join(\"/\")}`.replace(/\\/$/, \"\") || \"/\",\n };\n}\n\nfunction toMiddlewareInfo(\n options: GenerateRoutesOptions,\n file: string,\n): MiddlewareInfo | null {\n const relativePath = relative(options.routesDir, file).split(sep).join(\"/\");\n const fileSegments = relativePath.replace(/\\.tsx?$/, \"\").split(\"/\");\n\n if (fileSegments.at(-1) !== \"@middleware\") {\n return null;\n }\n\n let importPath = relative(dirname(options.outputFile), file)\n .split(sep)\n .join(\"/\")\n .replace(/\\.tsx?$/, \"\");\n\n if (!importPath.startsWith(\".\")) {\n importPath = `./${importPath}`;\n }\n\n return { file, fileSegments: fileSegments.slice(0, -1), importPath };\n}\n\nfunction isAttachedFileForRoute(\n attachedFileSegments: string[],\n routeFileSegments: string[],\n) {\n return attachedFileSegments.every(\n (segment, index) => routeFileSegments[index] === segment,\n );\n}\n\nfunction isRouteGroupSegment(segment: string) {\n return segment.startsWith(\"(\") && segment.endsWith(\")\");\n}\n\nfunction renderRoutesModule(routes: RouteInfo[], middleware: MiddlewareInfo[]) {\n return `// Generated by Demiurge. Do not edit by hand.\nimport \"${PACKAGE_NAME}\";\nimport type { MiddlewareContextOf, PathValue } from \"${PACKAGE_NAME}\";\n${middleware.map(renderMiddlewareImport).join(\"\\n\")}\n\n${middleware.map((_entry, index) => renderMiddlewareContextAlias(index)).join(\"\\n\")}\n\ndeclare module \"${PACKAGE_NAME}\" {\n interface RoutePathVars {\n${routes.map(renderPathVarsEntry).join(\"\\n\")}\n }\n\n interface RouteConcretePaths {\n${routes.map(renderConcretePathEntry).join(\"\\n\")}\n }\n\n interface RouteRequestContexts {\n${routes.map(renderRequestContextEntry).join(\"\\n\")}\n }\n}\n\nexport {};\n`;\n}\n\nfunction renderMiddlewareImport(entry: MiddlewareInfo, index: number) {\n return `type __DemiurgeMiddleware${index} = typeof import(${JSON.stringify(entry.importPath)}) extends { middleware?: infer T } ? T : never;`;\n}\n\nfunction renderMiddlewareContextAlias(index: number) {\n return `type __DemiurgeMiddlewareContext${index} = MiddlewareContextOf<__DemiurgeMiddleware${index}>;`;\n}\n\nfunction renderPathVarsEntry(route: RouteInfo) {\n if (route.pathVars.length === 0) {\n return ` ${JSON.stringify(route.pattern)}: {};`;\n }\n\n const pathType = route.pathVars\n .map((name) => `${name}: PathValue`)\n .join(\"; \");\n\n return ` ${JSON.stringify(route.pattern)}: { ${pathType} };`;\n}\n\nfunction renderConcretePathEntry(route: RouteInfo) {\n return ` ${JSON.stringify(route.pattern)}: ${toConcretePathType(route.pattern)};`;\n}\n\nfunction renderRequestContextEntry(route: RouteInfo) {\n const contexts = route.contextMiddleware\n .map((index) => `__DemiurgeMiddlewareContext${index}`);\n const context = contexts.length > 0\n ? contexts.join(\" & \")\n : \"Record<never, never>\";\n\n return ` ${JSON.stringify(route.pattern)}: ${context};`;\n}\n\nfunction toConcretePathType(pattern: string) {\n if (!pattern.includes(\"[\")) {\n return JSON.stringify(pattern);\n }\n\n const parts = pattern.split(/(\\[\\.\\.\\.[^\\]]+\\]|\\[[^\\]]+\\])/g).filter(Boolean);\n return `\\`${parts.map((part) => (part.startsWith(\"[\") ? \"${PathValue}\" : escapeTemplate(part))).join(\"\")}\\``;\n}\n\nfunction escapeTemplate(value: string) {\n return value.replace(/[`$\\\\]/g, \"\\\\$&\");\n}\n","import { readFile } from \"node:fs/promises\";\nimport { parseAst, transformWithEsbuild } from \"vite\";\nimport type { HttpMethod } from \"../route\";\nimport {\n createSecurityHeaders,\n security,\n validateCorsPolicy,\n validateRateLimitPolicy,\n type ContentSecurityPolicy,\n type CorsPolicy,\n type RoutePolicy,\n type RouteSecurityPolicy,\n type SecurityPolicy,\n} from \"../security\";\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\n// TYPE-EVIDENCE: rollup returns a generic program node. The local type is a loose access shape.\nfunction asAstNode(value: unknown): AstNode {\n // TYPE-EVIDENCE: the caller passes a rollup program node. The cast labels it with the loose access shape.\n return value as AstNode;\n}\n\nexport type StaticPolicyFinding = {\n code: \"cors-invalid\" | \"cors-method-unavailable\" | \"rate-limit-invalid\" |\n \"security-header-render-failed\";\n exportName?: string;\n file: string;\n message: string;\n severity: \"error\";\n};\n\ntype ExtractedCapability = {\n cors?: CorsPolicy;\n security?: RouteSecurityPolicy;\n};\n\ntype ExtractedRouteModule = {\n capabilities: Partial<Record<HttpMethod, ExtractedCapability>>;\n declaredMethods: Set<HttpMethod>;\n policy?: RoutePolicy;\n};\n\nconst httpMethods = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n] as const satisfies readonly HttpMethod[];\nconst responseHelpers = new Set([\n \"action\",\n \"html\",\n \"json\",\n \"jsonl\",\n \"notFound\",\n \"redirect\",\n \"response\",\n \"sse\",\n \"stream\",\n \"text\",\n]);\n\nexport async function verifyRoutePolicyFile(file: string) {\n const source = await readFile(file, \"utf8\");\n return await verifyRoutePolicySource(source, file);\n}\n\nexport async function verifyRoutePolicySource(source: string, file: string) {\n const loader = file.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n const transformed = await transformWithEsbuild(source, file, {\n format: \"esm\",\n loader,\n target: \"esnext\",\n });\n const extracted = extractRouteModule(transformed.code);\n\n return validateExtractedRouteModule(extracted, file);\n}\n\nfunction extractRouteModule(code: string): ExtractedRouteModule {\n const ast = asAstNode(parseAst(code));\n const imports = collectCoreImports(ast);\n const constants = collectConstants(ast);\n const declarations = collectVariableInitializers(ast);\n const exports = collectNamedExports(ast);\n const capabilities: ExtractedRouteModule[\"capabilities\"] = {};\n const declaredMethods = new Set<HttpMethod>();\n let policy: RoutePolicy | undefined;\n\n for (const [exportName, localName] of exports) {\n const initializer = declarations.get(localName);\n\n if (exportName === \"policy\") {\n if (initializer) {\n policy = extractRoutePolicy(initializer, imports, constants);\n }\n continue;\n }\n if (!isHttpMethod(exportName)) continue;\n declaredMethods.add(exportName);\n if (!initializer) continue;\n\n const capability = extractCapability(initializer, imports, constants);\n if (capability) capabilities[exportName] = capability;\n }\n\n return { capabilities, declaredMethods, policy };\n}\n\nfunction collectVariableInitializers(ast: AstNode) {\n const declarations = new Map<string, AstNode>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (name && initializer) declarations.set(name, initializer);\n }\n }\n return declarations;\n}\n\nfunction collectNamedExports(ast: AstNode) {\n const exports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n if (name) exports.set(name, name);\n }\n }\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local) exports.set(exported, local);\n }\n }\n return exports;\n}\n\nfunction extractCapability(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n) {\n if (node.type !== \"CallExpression\") return undefined;\n const localName = identifierName(node.callee);\n const helper = localName ? imports.get(localName) : undefined;\n\n if (!helper || !responseHelpers.has(helper)) return undefined;\n const arguments_ = asNodeArray(node.arguments);\n const optionsNode = helper === \"action\" ? arguments_[0] : arguments_[1];\n if (!optionsNode) return {};\n const cors = evaluateObjectProperty(optionsNode, \"cors\", constants);\n const securityPolicy = evaluateObjectProperty(\n optionsNode,\n \"security\",\n constants,\n );\n\n // TYPE-EVIDENCE: the isRecord checks confirm the values are plain objects. The casts label them as the capability policy types.\n return {\n cors: isRecord(cors) ? cors as CorsPolicy : undefined,\n security: isRecord(securityPolicy)\n ? securityPolicy as RouteSecurityPolicy\n : undefined,\n } satisfies ExtractedCapability;\n}\n\nfunction evaluateObjectProperty(\n node: AstNode,\n property: string,\n constants: Map<string, unknown>,\n) {\n if (node.type === \"Identifier\") {\n const value = constants.get(String(node.name));\n return isRecord(value) ? value[property] : unresolved;\n }\n if (node.type !== \"ObjectExpression\") return unresolved;\n\n let value: unknown = undefined;\n for (const item of asNodeArray(node.properties)) {\n if (item.type !== \"Property\" || item.computed) return unresolved;\n if (propertyName(item.key) !== property) continue;\n value = evaluateLiteral(asNode(item.value), constants);\n }\n\n return value;\n}\n\nfunction extractRoutePolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): RoutePolicy | undefined {\n if (node.type === \"CallExpression\") {\n const localName = identifierName(node.callee);\n if (localName && imports.get(localName) === \"defineRoutePolicy\") {\n const argument = asNodeArray(node.arguments)[0];\n return argument\n ? extractRoutePolicy(argument, imports, constants)\n : undefined;\n }\n }\n\n if (node.type !== \"ObjectExpression\") {\n const value = evaluateLiteral(node, constants);\n // TYPE-EVIDENCE: the isRecord check confirms the value is a plain object. The cast labels it as a route policy.\n return isRecord(value) ? value as RoutePolicy : undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return undefined;\n const name = propertyName(property.key);\n const valueNode = asNode(property.value);\n if (!name || !valueNode) return undefined;\n\n if (name === \"document\") {\n const document = extractSecurityPolicy(valueNode, imports, constants);\n if (!document) return undefined;\n result.document = document;\n continue;\n }\n\n const value = evaluateLiteral(valueNode, constants);\n if (value === unresolved) return undefined;\n result[name] = value;\n }\n\n // TYPE-EVIDENCE: the loop above copied each property from the object expression. The cast labels the accumulated record as a route policy.\n return result as RoutePolicy;\n}\n\nfunction extractSecurityPolicy(\n node: AstNode,\n imports: Map<string, string>,\n constants: Map<string, unknown>,\n): SecurityPolicy | undefined {\n if (node.type !== \"CallExpression\") {\n const value = evaluateLiteral(node, constants);\n // TYPE-EVIDENCE: the isRecord check confirms the value is a plain object. The cast labels it as a security policy.\n return isRecord(value) ? value as SecurityPolicy : undefined;\n }\n\n const callee = asNode(node.callee);\n if (callee?.type !== \"MemberExpression\") return undefined;\n const objectName = identifierName(callee.object);\n const preset = propertyName(callee.property);\n if (!objectName || imports.get(objectName) !== \"security\" || !preset) {\n return undefined;\n }\n\n const options = evaluateLiteral(asNodeArray(node.arguments)[0], constants);\n if (options !== unresolved && options !== undefined && !isRecord(options)) {\n return undefined;\n }\n\n if (preset === \"api\") {\n // TYPE-EVIDENCE: the guard above rejects non-object options values. The preset helper validates the specific option fields.\n return security.api(options as never);\n }\n if (preset === \"crossOriginIsolated\") {\n // TYPE-EVIDENCE: the guard above rejects non-object options values. The preset helper validates the specific option fields.\n return security.crossOriginIsolated(options as never);\n }\n if (preset === \"static\") {\n // TYPE-EVIDENCE: the guard above rejects non-object options values. The preset helper validates the specific option fields.\n return security.static(options as never);\n }\n if (preset === \"strict\") {\n // TYPE-EVIDENCE: the guard above rejects non-object options values. The preset helper validates the specific option fields.\n return security.strict(options as never);\n }\n return undefined;\n}\n\nfunction validateExtractedRouteModule(\n routeModule: ExtractedRouteModule,\n file: string,\n) {\n const findings: StaticPolicyFinding[] = [];\n const availableMethods = new Set(routeModule.declaredMethods);\n if (availableMethods.has(\"GET\")) availableMethods.add(\"HEAD\");\n // Demiurge answers preflight itself, so a route never exports an OPTIONS\n // capability to serve one. Listing OPTIONS is a habit carried in from other\n // CORS configuration, and rejecting it would fail a build over nothing.\n availableMethods.add(\"OPTIONS\");\n\n // TYPE-EVIDENCE: Object.entries returns the capability map entries as string keyed pairs. The cast narrows the keys to HTTP methods and the values to capability types.\n for (const [exportName, capability] of Object.entries(\n routeModule.capabilities,\n ) as Array<[HttpMethod, ExtractedCapability]>) {\n if (capability.cors) {\n try {\n validateCorsPolicy(capability.cors);\n } catch (error) {\n findings.push(finding(\n \"cors-invalid\",\n file,\n errorMessage(error, \"The CORS policy is invalid.\"),\n exportName,\n ));\n }\n\n for (const method of capability.cors.methods ?? []) {\n if (!availableMethods.has(method)) {\n findings.push(finding(\n \"cors-method-unavailable\",\n file,\n `CORS method ${method} is not available from this route.`,\n exportName,\n ));\n }\n }\n }\n\n validateRateLimit(capability.security, file, exportName, findings);\n }\n\n validateRateLimit(routeModule.policy?.security, file, undefined, findings);\n if (routeModule.policy?.document) {\n try {\n createSecurityHeaders(toFragmentDocument(routeModule.policy.document), {\n nonce: \"build-verification-nonce\",\n });\n } catch (error) {\n findings.push(finding(\n \"security-header-render-failed\",\n file,\n errorMessage(error, \"The security headers are invalid.\"),\n ));\n }\n }\n\n return findings;\n}\n\n// A build reads one file at a time, but policy cascades. A file declaring no\n// reporting endpoints of its own inherits them. Its `csp.reportTo` therefore\n// names a group only the merged policy resolves, which\n// `validateRouteModules(...)` checks during startup. A file declaring its own\n// endpoint map is self-contained. A name outside that map stays a build\n// error, because that is the typo worth catching early.\nfunction toFragmentDocument(document: SecurityPolicy): SecurityPolicy {\n const endpoints = document.headers?.reportingEndpoints;\n const declaresEndpoints = Boolean(\n endpoints && Object.keys(endpoints).length,\n );\n const reportTo = document.csp === false ? undefined : document.csp?.reportTo;\n\n if (declaresEndpoints || !reportTo) {\n return document;\n }\n\n // TYPE-EVIDENCE: the guard above returns early when the csp field is false or missing. The remaining value is therefore a policy object.\n return {\n ...document,\n csp: { ...document.csp as ContentSecurityPolicy, reportTo: undefined },\n headers: endpoints\n ? { ...document.headers, reportingEndpoints: undefined }\n : document.headers,\n };\n}\n\nfunction validateRateLimit(\n securityPolicy: RouteSecurityPolicy | undefined,\n file: string,\n exportName: string | undefined,\n findings: StaticPolicyFinding[],\n) {\n if (!securityPolicy?.rateLimit) return;\n try {\n validateRateLimitPolicy(securityPolicy.rateLimit);\n } catch (error) {\n findings.push(finding(\n \"rate-limit-invalid\",\n file,\n errorMessage(error, \"The rate limit policy is invalid.\"),\n exportName,\n ));\n }\n}\n\nfunction finding(\n code: StaticPolicyFinding[\"code\"],\n file: string,\n message: string,\n exportName?: string,\n): StaticPolicyFinding {\n return { code, exportName, file, message, severity: \"error\" };\n}\n\nfunction collectCoreImports(ast: AstNode) {\n const imports = new Map<string, string>();\n for (const statement of asNodeArray(ast.body)) {\n if (\n statement.type !== \"ImportDeclaration\" ||\n asNode(statement.source)?.value !== \"@demiurgejs/core\"\n ) continue;\n for (const specifier of asNodeArray(statement.specifiers)) {\n if (specifier.type !== \"ImportSpecifier\") continue;\n const local = identifierName(specifier.local);\n const imported = propertyName(specifier.imported);\n if (local && imported) imports.set(local, imported);\n }\n }\n return imports;\n}\n\nfunction collectConstants(ast: AstNode) {\n const constants = new Map<string, unknown>();\n for (const statement of asNodeArray(ast.body)) {\n const declaration = statement.type === \"ExportNamedDeclaration\"\n ? asNode(statement.declaration)\n : statement;\n if (declaration?.type !== \"VariableDeclaration\") continue;\n for (const declarator of asNodeArray(declaration.declarations)) {\n const name = identifierName(declarator.id);\n const initializer = asNode(declarator.init);\n if (!name || !initializer) continue;\n const value = evaluateLiteral(initializer, constants);\n if (value !== unresolved) constants.set(name, value);\n }\n }\n return constants;\n}\n\nconst unresolved = Symbol(\"unresolved\");\n\nfunction evaluateLiteral(\n node: AstNode | undefined,\n constants: Map<string, unknown>,\n): unknown | typeof unresolved {\n if (!node) return undefined;\n if (node.type === \"Literal\") return node.value;\n if (node.type === \"Identifier\") {\n if (node.name === \"undefined\") return undefined;\n return constants.has(String(node.name))\n ? constants.get(String(node.name))\n : unresolved;\n }\n if (node.type === \"TemplateLiteral\") {\n if (asNodeArray(node.expressions).length) return unresolved;\n return asNodeArray(node.quasis)\n .map((quasi) => asNode(quasi.value)?.cooked ?? \"\")\n .join(\"\");\n }\n if (node.type === \"UnaryExpression\") {\n const value = evaluateLiteral(asNode(node.argument), constants);\n if (typeof value !== \"number\") return unresolved;\n if (node.operator === \"-\") return -value;\n if (node.operator === \"+\") return value;\n return unresolved;\n }\n if (node.type === \"ArrayExpression\") {\n const values: unknown[] = [];\n for (const element of asNodeArray(node.elements)) {\n const value = evaluateLiteral(element, constants);\n if (value === unresolved) return unresolved;\n values.push(value);\n }\n return values;\n }\n if (node.type === \"ObjectExpression\") {\n const value: Record<string, unknown> = {};\n for (const property of asNodeArray(node.properties)) {\n if (property.type !== \"Property\" || property.computed) return unresolved;\n const name = propertyName(property.key);\n const child = evaluateLiteral(asNode(property.value), constants);\n if (!name || child === unresolved) return unresolved;\n value[name] = child;\n }\n return value;\n }\n return unresolved;\n}\n\nfunction isHttpMethod(value: string): value is HttpMethod {\n // TYPE-EVIDENCE: the value is a string that the includes check tests against the HTTP methods tuple. The cast narrows it for the check.\n return httpMethods.includes(value as HttpMethod);\n}\n\nfunction errorMessage(error: unknown, fallback: string) {\n return error instanceof Error ? error.message : fallback;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction asNode(value: unknown) {\n // TYPE-EVIDENCE: the type in value check confirms the value is an AST node. The cast asserts that node shape.\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction identifierName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" ? String(node.name) : undefined;\n}\n\nfunction propertyName(value: unknown) {\n const node = asNode(value);\n return node?.type === \"Identifier\" || node?.type === \"Literal\"\n ? String(node.name ?? node.value)\n : undefined;\n}\n","import {\n createMemoryCache,\n serializeCacheKey,\n serializeCacheTag,\n type Cache,\n type CacheScope,\n} from \"../data\";\nimport type { ResolvedMetadata, ScriptTag } from \"../document\";\nimport {\n findRouteMatch,\n isAttachedFileForRoute,\n isRouteGroupSegment,\n loadPageRoute,\n MalformedPathnameError,\n toRoutePattern,\n type RouteManifest,\n} from \"../router\";\nimport type {\n HttpMethod,\n PageRenderMode,\n PathVars,\n RouteModule,\n} from \"../route\";\nimport { loadInheritedRoutePolicy } from \"../server\";\nimport {\n createSecurityAudit,\n type CorsPolicy,\n type RoutePolicy,\n type SecurityAudit,\n type SecurityAuditFinding,\n} from \"../security\";\nimport { createCspNonce, securityPolicyRequiresNonce } from \"../security/policy\";\n\n// The development server reserves this path. The name matches the image\n// optimizer path, so every framework endpoint keeps one prefix.\nexport const ROUTE_AUDIT_PATH = \"/_demiurge/audit\";\n\nconst supportedMethods = [\n \"GET\",\n \"POST\",\n \"PUT\",\n \"PATCH\",\n \"DELETE\",\n \"OPTIONS\",\n \"HEAD\",\n] as const satisfies readonly HttpMethod[];\n\nexport type RouteAuditCacheRead = {\n key: string;\n scope: CacheScope;\n staleWhileRevalidate?: string;\n tags: string[];\n ttl?: string;\n};\n\nexport type RouteAuditScript = {\n findings: SecurityAuditFinding[];\n integrity?: string;\n nonce?: string;\n purpose?: string;\n src: string;\n strategy: string;\n};\n\nexport type RouteAuditRoute = {\n file: string;\n groups: string[];\n layouts: string[];\n methods: HttpMethod[];\n middlewares: string[];\n params: PathVars;\n pattern: string;\n policies: string[];\n render?: PageRenderMode;\n};\n\nexport type RouteAudit = {\n audit: SecurityAudit;\n cacheControl?: string;\n cacheReads: RouteAuditCacheRead[];\n kind: \"page\" | \"resource\" | \"unmatched\";\n metadata?: ResolvedMetadata;\n method: HttpMethod;\n nonce?: string;\n pathname: string;\n policy: RoutePolicy;\n route?: RouteAuditRoute;\n scripts: RouteAuditScript[];\n};\n\nexport function isRouteAuditRequest(request: Request) {\n return new URL(request.url).pathname === ROUTE_AUDIT_PATH;\n}\n\nexport async function createRouteAuditResponse(\n manifest: RouteManifest,\n request: Request,\n) {\n const url = new URL(request.url);\n const report = await createRouteAudit(\n manifest,\n url.searchParams.get(\"path\") || \"/\",\n request,\n );\n const json = url.searchParams.get(\"format\") === \"json\";\n\n return new Response(\n json\n ? JSON.stringify(report, null, 2)\n : renderRouteAuditDocument(report),\n {\n headers: {\n \"cache-control\": \"no-store\",\n // The panel is a side channel. It declares its own policy, so the\n // policy of the application stays unchanged. The panel runs no script.\n \"content-security-policy\":\n \"default-src 'none'; base-uri 'none'; form-action 'self'; style-src 'unsafe-inline'\",\n \"content-type\": json\n ? \"application/json; charset=utf-8\"\n : \"text/html; charset=utf-8\",\n \"x-robots-tag\": \"noindex\",\n },\n },\n );\n}\n\nexport async function createRouteAudit(\n manifest: RouteManifest,\n target: string,\n request: Request,\n): Promise<RouteAudit> {\n const origin = new URL(request.url).origin;\n const url = new URL(target, origin);\n const pathname = url.pathname;\n const routeRequest = new Request(url, { headers: request.headers });\n const routeMatch = matchRoute(manifest, pathname);\n\n if (!routeMatch) {\n const policy = await loadInheritedRoutePolicy(\n manifest,\n { fileSegments: [] },\n {},\n undefined,\n );\n\n return finishRouteAudit({\n cacheReads: [],\n kind: \"unmatched\",\n method: \"GET\",\n pathname,\n policy,\n request: routeRequest,\n scripts: [],\n });\n }\n\n const routeModule = await routeMatch.route.load();\n const method = selectMethod(routeModule);\n const capability = routeModule[method];\n const policy = await loadInheritedRoutePolicy(\n manifest,\n routeMatch.route,\n routeModule,\n capability,\n );\n const cacheReads: RouteAuditCacheRead[] = [];\n const page = capability?.kind === \"page\"\n ? await loadPageRoute(\n manifest,\n pathname,\n routeRequest,\n undefined,\n createRecordingCache(cacheReads),\n )\n : undefined;\n const match = page?.status === \"ready\" ? page.match : undefined;\n\n return finishRouteAudit({\n cacheReads,\n cors: capability && capability.kind !== \"page\"\n ? capability.cors\n : undefined,\n kind: capability?.kind === \"page\" ? \"page\" : \"resource\",\n metadata: match?.metadata,\n method,\n pathname,\n policy,\n request: routeRequest,\n route: {\n file: routeMatch.route.file,\n groups: routeMatch.route.fileSegments.filter(isRouteGroupSegment),\n layouts: manifest.layouts\n .filter((layout) => isAttachedFileForRoute(layout.fileSegments, routeMatch.route.fileSegments))\n .map((layout) => layout.file),\n methods: supportedMethods.filter((name) => routeModule[name]),\n middlewares: manifest.middlewares\n .filter((item) => isAttachedFileForRoute(item.fileSegments, routeMatch.route.fileSegments))\n .map((item) => item.file),\n params: routeMatch.path,\n pattern: toRoutePattern(routeMatch.route.segments),\n policies: manifest.policies\n .filter((item) => isAttachedFileForRoute(item.fileSegments, routeMatch.route.fileSegments))\n .map((item) => item.file),\n render: match?.render.mode,\n },\n scripts: match?.scripts ?? [],\n });\n}\n\nfunction finishRouteAudit(input: {\n cacheReads: RouteAuditCacheRead[];\n cors?: CorsPolicy;\n kind: RouteAudit[\"kind\"];\n metadata?: ResolvedMetadata;\n method: HttpMethod;\n pathname: string;\n policy: RoutePolicy;\n request: Request;\n route?: RouteAuditRoute;\n scripts: readonly ScriptTag[];\n}): RouteAudit {\n // The request handler renders the document policy for a page response only.\n // A resource route and an unmatched path therefore get no document headers\n // and no nonce.\n const document = input.kind === \"page\";\n // The document renderer gives each script the nonce of the document. The\n // audit reads the same values that the response carries.\n const nonce = document && securityPolicyRequiresNonce(input.policy.document)\n ? createCspNonce()\n : undefined;\n const scripts = input.scripts.map((script) => ({\n ...script,\n nonce: script.nonce ?? nonce,\n }));\n const auditOptions = {\n headers: { nonce, request: input.request },\n policy: input.policy.document ?? {},\n scriptDependencies: true,\n };\n const audit = createSecurityAudit({\n document: document ? { ...auditOptions, scripts } : undefined,\n route: {\n cors: input.cors,\n method: input.method,\n security: input.policy.security,\n },\n });\n\n return {\n audit,\n // A nonce makes a document unique for each response. The request handler\n // therefore replaces the cache directives of the application.\n cacheControl: nonce ? \"private, no-store\" : undefined,\n cacheReads: input.cacheReads,\n kind: input.kind,\n metadata: input.metadata,\n method: input.method,\n nonce,\n pathname: input.pathname,\n policy: input.policy,\n route: input.route,\n scripts: scripts.map((script) => ({\n // One audit for each script gives the status of that script alone. The\n // panel reads the same code path that the complete audit reads.\n findings: createSecurityAudit({\n document: { ...auditOptions, scripts: [script] },\n }).findings,\n integrity: script.integrity,\n nonce: script.nonce,\n purpose: script.purpose,\n src: script.src,\n strategy: script.strategy,\n })),\n };\n}\n\nfunction matchRoute(manifest: RouteManifest, pathname: string) {\n try {\n return findRouteMatch(manifest.routes, pathname);\n } catch (error) {\n if (error instanceof MalformedPathnameError) {\n return null;\n }\n\n throw error;\n }\n}\n\nfunction selectMethod(routeModule: RouteModule) {\n return supportedMethods.find((method) => routeModule[method]) ?? \"GET\";\n}\n\nfunction createRecordingCache(reads: RouteAuditCacheRead[]): Cache {\n const cache = createMemoryCache();\n\n return {\n get: async (request) => {\n reads.push({\n key: serializeCacheKey(request.key),\n scope: request.scope ?? \"request\",\n staleWhileRevalidate: formatDuration(request.staleWhileRevalidate),\n tags: (request.tags ?? []).map(serializeCacheTag),\n ttl: formatDuration(request.ttl),\n });\n\n return await cache.get(request);\n },\n invalidateKey: cache.invalidateKey,\n invalidateTags: cache.invalidateTags,\n };\n}\n\nfunction formatDuration(duration: number | string | undefined) {\n return duration === undefined ? undefined : String(duration);\n}\n\nexport function renderRouteAuditDocument(report: RouteAudit) {\n return `<!doctype html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Demiurge route audit</title>\n <style>${panelStyles}</style>\n </head>\n <body>\n <h1>Demiurge route audit</h1>\n <form method=\"get\" action=\"${ROUTE_AUDIT_PATH}\">\n <label for=\"path\">Path</label>\n <input id=\"path\" name=\"path\" value=\"${escapeHtml(report.pathname)}\" />\n <button type=\"submit\">Audit</button>\n </form>\n${renderRouteSection(report)}\n${renderFindingsSection(report.audit.findings)}\n${renderHeadersSection(report.audit.headers)}\n${renderPolicySection(report)}\n${renderMetadataSection(report.metadata)}\n${renderScriptsSection(report.scripts)}\n${renderCacheSection(report)}\n <p class=\"footer\">\n The development server serves this panel. A production build and a static\n export do not contain it.\n </p>\n </body>\n</html>\n`;\n}\n\nconst panelStyles = `\n :root { color-scheme: light dark; }\n body {\n font-family: ui-monospace, SFMono-Regular, Menlo, monospace;\n line-height: 1.5;\n margin: 0 auto;\n max-width: 60rem;\n padding: 2rem 1rem;\n }\n h1 { font-size: 1.25rem; }\n h2 { font-size: 1rem; margin-bottom: 0.25rem; }\n form { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }\n input { flex: 1; padding: 0.25rem 0.5rem; }\n section { border-top: 1px solid currentColor; padding: 0.75rem 0; }\n table { border-collapse: collapse; width: 100%; }\n td, th { padding: 0.25rem 0.5rem 0.25rem 0; text-align: left; vertical-align: top; }\n th { white-space: nowrap; width: 12rem; }\n ul { margin: 0; padding-left: 1.25rem; }\n .empty { opacity: 0.7; }\n .error { font-weight: 700; }\n .footer { opacity: 0.7; }\n`;\n\nfunction renderRouteSection(report: RouteAudit) {\n if (!report.route) {\n return section(\n \"Route\",\n `<p class=\"empty\">No route matches ${escapeHtml(report.pathname)}.</p>`,\n );\n }\n\n const route = report.route;\n\n return section(\n \"Route\",\n table([\n [\"Pathname\", escapeHtml(report.pathname)],\n [\"Pattern\", escapeHtml(route.pattern)],\n [\"File\", escapeHtml(route.file)],\n [\"Kind\", escapeHtml(report.kind)],\n [\"Method\", escapeHtml(report.method)],\n [\"Methods\", escapeHtml(route.methods.join(\", \"))],\n [\"Render mode\", route.render ? escapeHtml(route.render) : none()],\n [\"Path values\", entries(route.params)],\n [\"Route groups\", list(route.groups)],\n [\"Layouts\", list(route.layouts)],\n [\"Policies\", list(route.policies)],\n [\"Middleware\", list(route.middlewares)],\n ]),\n );\n}\n\nfunction renderFindingsSection(findings: SecurityAuditFinding[]) {\n if (findings.length === 0) {\n return section(\"Findings\", `<p class=\"empty\">No findings.</p>`);\n }\n\n return section(\n \"Findings\",\n `<ul>${findings.map(renderFinding).join(\"\")}</ul>`,\n );\n}\n\nfunction renderFinding(finding: SecurityAuditFinding) {\n const className = finding.severity === \"error\" ? ' class=\"error\"' : \"\";\n\n return `<li${className}>${escapeHtml(finding.severity)}: ${\n escapeHtml(finding.message)\n } <code>${escapeHtml(finding.code)}</code></li>`;\n}\n\nfunction renderHeadersSection(headers: Record<string, string>) {\n const names = Object.keys(headers).sort();\n\n if (names.length === 0) {\n return section(\n \"Response headers\",\n `<p class=\"empty\">The response carries no document header.</p>`,\n );\n }\n\n return section(\n \"Response headers\",\n table(names.map((name) => [name, escapeHtml(headers[name])])),\n );\n}\n\nfunction renderPolicySection(report: RouteAudit) {\n const policy = {\n cors: report.audit.route?.cors,\n document: report.policy.document,\n security: report.policy.security,\n };\n\n return section(\n \"Effective policy\",\n `<pre>${\n escapeHtml(JSON.stringify(policy, null, 2))\n }</pre>`,\n );\n}\n\nfunction renderMetadataSection(metadata: ResolvedMetadata | undefined) {\n if (!metadata) {\n return section(\"Metadata\", `<p class=\"empty\">No document metadata.</p>`);\n }\n\n return section(\n \"Metadata\",\n `<pre>${\n escapeHtml(JSON.stringify(metadata, null, 2))\n }</pre>`,\n );\n}\n\nfunction renderScriptsSection(scripts: RouteAuditScript[]) {\n if (scripts.length === 0) {\n return section(\"Scripts\", `<p class=\"empty\">No contributed scripts.</p>`);\n }\n\n return section(\n \"Scripts\",\n scripts.map((script) =>\n table([\n [\"Source\", escapeHtml(script.src)],\n [\"Strategy\", escapeHtml(script.strategy)],\n [\"Purpose\", script.purpose ? escapeHtml(script.purpose) : none()],\n [\"Integrity\", script.integrity ? escapeHtml(script.integrity) : none()],\n [\"Nonce\", script.nonce ? \"applied\" : none()],\n [\n \"Policy status\",\n script.findings.length === 0\n ? \"allowed\"\n : `<ul>${script.findings.map(renderFinding).join(\"\")}</ul>`,\n ],\n ])\n ).join(\"\"),\n );\n}\n\nfunction renderCacheSection(report: RouteAudit) {\n const rows: Array<[string, string]> = [\n [\n \"Response cache-control\",\n report.cacheControl ? escapeHtml(report.cacheControl) : none(),\n ],\n [\"Nonce\", report.nonce ? \"required\" : none()],\n ];\n\n if (report.cacheReads.length === 0) {\n return section(\n \"Cache behavior\",\n `${table(rows)}<p class=\"empty\">The request read no cache entry.</p>`,\n );\n }\n\n return section(\n \"Cache behavior\",\n `${table(rows)}${\n report.cacheReads.map((read) =>\n table([\n [\"Key\", escapeHtml(read.key)],\n [\"Scope\", escapeHtml(read.scope)],\n [\"Time to live\", read.ttl ? escapeHtml(read.ttl) : none()],\n [\n \"Stale while revalidate\",\n read.staleWhileRevalidate\n ? escapeHtml(read.staleWhileRevalidate)\n : none(),\n ],\n [\"Tags\", list(read.tags)],\n ])\n ).join(\"\")\n }`,\n );\n}\n\nfunction section(title: string, body: string) {\n return ` <section>\n <h2>${escapeHtml(title)}</h2>\n ${body}\n </section>`;\n}\n\nfunction table(rows: Array<[string, string]>) {\n return `<table><tbody>${\n rows.map(([name, value]) =>\n `<tr><th scope=\"row\">${escapeHtml(name)}</th><td>${value}</td></tr>`\n ).join(\"\")\n }</tbody></table>`;\n}\n\nfunction list(values: readonly string[]) {\n if (values.length === 0) {\n return none();\n }\n\n return `<ul>${\n values.map((value) => `<li>${escapeHtml(value)}</li>`).join(\"\")\n }</ul>`;\n}\n\nfunction entries(values: PathVars) {\n return list(\n Object.entries(values).map(([name, value]) => `${name} = ${String(value)}`),\n );\n}\n\nfunction none() {\n return `<span class=\"empty\">none</span>`;\n}\n\nfunction escapeHtml(value: string) {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll(\"\\\"\", \"&quot;\")\n .replaceAll(\"'\", \"&#39;\");\n}\n","import { existsSync } from \"node:fs\";\nimport type { IncomingMessage } from \"node:http\";\nimport { readFile, readdir } from \"node:fs/promises\";\nimport { dirname, join, resolve, relative, sep } from \"node:path\";\nimport MagicString from \"magic-string\";\nimport {\n type ConfigEnv,\n parseAst,\n type Plugin,\n type UserConfig,\n type ViteDevServer,\n} from \"vite\";\nimport { renderDocument } from \"../document\";\nimport type {\n LinkTag,\n ResolvedMetadata,\n ScriptTag,\n} from \"../document\";\nimport { PACKAGE_NAME } from \"../package-name\";\nimport { generateRoutes } from \"../routing/generate\";\nimport {\n createRouteManifest,\n findRouteMatch,\n type RouteManifest,\n} from \"../router\";\nimport {\n handleRequestWithManifest,\n renderNotFoundResponse,\n renderPageDocument,\n type PageRenderer,\n} from \"../server\";\nimport {\n type RouteImporter,\n type RouteModule,\n} from \"../route\";\nimport {\n UnsupportedMethodError,\n toWebRequest,\n writeNotImplemented,\n writeWebResponse,\n} from \"../node/http\";\nimport { createFontAssetHandler } from \"../node/font\";\nimport { createImageOptimizer } from \"../node/image\";\nimport { renderStreamingPageResponse } from \"../node/streaming\";\nimport type { FontContribution } from \"../platform/fonts\";\nimport { parseImageVariantPath } from \"../platform/image-url\";\nimport type { ImagePolicy } from \"../platform/images\";\nimport { createCspNonce } from \"../security/policy\";\nimport {\n verifyRoutePolicyFile,\n type StaticPolicyFinding,\n} from \"./policy-verification\";\nimport {\n createRouteAuditResponse,\n isRouteAuditRequest,\n} from \"./route-audit\";\nimport type {\n StaticFileHeaderPatternRule,\n VercelStaticDeployment,\n} from \"../static\";\n\nexport type DemiurgeVitePluginOptions = {\n // The route audit panel of the development server. The panel is available by\n // default. Set this option to false to remove the endpoint.\n devtools?: boolean;\n document?: {\n lang?: string;\n title?: string;\n };\n // The fonts that the application self-hosts. The development server serves\n // the same URLs that the build publishes.\n fonts?: FontContribution;\n // The image policy that the application passes to `planImageTransform` and\n // to `Image`. The development server serves the optimizer path from it.\n images?: ImagePolicy;\n routesDir?: string;\n static?: {\n deployment?: VercelStaticDeployment;\n headers?: readonly StaticFileHeaderPatternRule[];\n };\n styles?: false | string;\n typedRoutes?: boolean | {\n outputFile?: string;\n };\n};\n\nexport type DemiurgeVitePluginApi = {\n demiurge: true;\n fonts?: FontContribution;\n images?: ImagePolicy;\n staticDeployment?: VercelStaticDeployment;\n staticFileHeaders?: readonly StaticFileHeaderPatternRule[];\n};\n\nconst CLIENT_ENTRY_ID = \"virtual:demiurge/client-entry\";\nconst DEV_CLIENT_ENTRY_PATH = `/@id/${CLIENT_ENTRY_ID}`;\nconst RESOLVED_CLIENT_ENTRY_ID = `\\0${CLIENT_ENTRY_ID}`;\nconst SERVER_ENTRY_ID = \"virtual:demiurge/server-entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\nconst DEFAULT_TYPED_ROUTES_OUTPUT = \".demiurge/route-manifest.d.ts\";\nexport function demiurge(options: DemiurgeVitePluginOptions = {}): Plugin {\n let root = process.cwd();\n let isBuild = false;\n const viteNoncePlaceholder = `demiurge-${createCspNonce()}`;\n\n return {\n api: {\n demiurge: true,\n fonts: options.fonts,\n images: options.images,\n staticDeployment: options.static?.deployment,\n staticFileHeaders: options.static?.headers,\n } satisfies DemiurgeVitePluginApi,\n enforce: \"post\",\n name: \"demiurge\",\n config(config, environment) {\n return createViteConfig(config, environment, viteNoncePlaceholder);\n },\n configResolved(config) {\n root = config.root;\n isBuild = config.command === \"build\";\n },\n resolveId(id) {\n if (id === CLIENT_ENTRY_ID) {\n return RESOLVED_CLIENT_ENTRY_ID;\n }\n\n if (id === SERVER_ENTRY_ID) {\n return RESOLVED_SERVER_ENTRY_ID;\n }\n\n return null;\n },\n load(id) {\n if (id === RESOLVED_CLIENT_ENTRY_ID) {\n return createClientEntrySource(root, options);\n }\n\n if (id === RESOLVED_SERVER_ENTRY_ID) {\n return createServerEntrySource(root, options);\n }\n\n return null;\n },\n transform: {\n order: \"post\",\n handler(code, id, transformOptions) {\n if (!isRouteSource(root, options, id)) {\n return null;\n }\n\n if (transformOptions?.ssr) {\n return isBuild ? null : protectSsrImportMeta(code, id);\n }\n\n const transformed = stripClientPageData(code);\n return transformed === code ? null : { code: transformed, map: null };\n },\n },\n generateBundle(_outputOptions, bundle) {\n const entry = Object.values(bundle).find(\n (item) =>\n item.type === \"chunk\" &&\n item.isEntry &&\n item.facadeModuleId === RESOLVED_CLIENT_ENTRY_ID,\n );\n\n if (!entry) {\n return;\n }\n\n const styles = Object.values(bundle)\n .filter(\n (asset): asset is Extract<(typeof bundle)[string], { type: \"asset\" }> =>\n asset.type === \"asset\" && asset.fileName.endsWith(\".css\"),\n )\n .map((asset) => `/${asset.fileName}`);\n const clientEntry = `/${entry.fileName}`;\n\n this.emitFile({\n fileName: \"index.html\",\n source: createDocumentHtml({\n entrySrc: clientEntry,\n lang: options.document?.lang,\n styles,\n title: options.document?.title,\n }),\n type: \"asset\",\n });\n this.emitFile({\n fileName: \"demiurge-manifest.json\",\n source: JSON.stringify({ clientEntry, styles }, null, 2),\n type: \"asset\",\n });\n },\n async buildStart() {\n if (isBuild) {\n await assertRootNotFoundRoute(root, options);\n const findings = await verifyRoutePolicies(root, options);\n\n if (findings.length) {\n throw new Error(formatStaticPolicyFindings(findings));\n }\n }\n\n if (!options.typedRoutes) {\n return;\n }\n\n await generateTypedRoutes(root, options);\n },\n configureServer(server) {\n const reportPolicyFindings = async () => {\n const findings = await verifyRoutePolicies(server.config.root, options);\n\n for (const finding of findings) {\n server.config.logger.warn(formatStaticPolicyFinding(finding));\n }\n };\n // A single editor save can fire several watcher events, and a branch\n // switch fires one per route file. Collapse a burst into one scan, and\n // chain scans so two never walk the route tree at the same time.\n let policyVerificationTimer: ReturnType<typeof setTimeout> | undefined;\n let policyVerificationRun = Promise.resolve();\n const runPolicyVerification = () => {\n policyVerificationRun = policyVerificationRun\n .then(reportPolicyFindings)\n .catch(() => {\n // Vite reports route read and syntax errors through its module pipeline.\n });\n };\n const startPolicyVerification = () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n }\n\n policyVerificationTimer = setTimeout(() => {\n policyVerificationTimer = undefined;\n runPolicyVerification();\n }, policyVerificationDebounceMs);\n policyVerificationTimer.unref?.();\n };\n\n server.httpServer?.once(\"close\", () => {\n if (policyVerificationTimer) {\n clearTimeout(policyVerificationTimer);\n policyVerificationTimer = undefined;\n }\n });\n\n runPolicyVerification();\n if (options.typedRoutes) {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n\n void generateTypedRoutes(server.config.root, options);\n server.watcher.add(routesDir);\n server.watcher.on(\"add\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"change\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n server.watcher.on(\"unlink\", (file) => {\n if (isRouteFile(routesDir, file)) {\n void generateTypedRoutes(server.config.root, options);\n startPolicyVerification();\n }\n });\n } else {\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n server.watcher.add(routesDir);\n for (const event of [\"add\", \"change\", \"unlink\"] as const) {\n server.watcher.on(event, (file) => {\n if (isRouteFile(routesDir, file)) startPolicyVerification();\n });\n }\n }\n\n const routeAuditEnabled = isRouteAuditEnabled(options);\n const optimizeImage = createDevImageOptimizer(server, options);\n const serveFont = createFontAssetHandler({\n fonts: options.fonts,\n root: server.config.root,\n });\n\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n // Vite performs its own configured host allowlist check before\n // Demiurge's middleware runs. Production Node listeners require\n // an explicit application allowlist instead.\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n if (routeAuditEnabled && isRouteAuditRequest(webRequest)) {\n const manifest = await loadDevManifest(\n server,\n request,\n resolve(server.config.root, options.routesDir ?? \"src/routes\"),\n );\n\n await writeWebResponse(\n response,\n await createRouteAuditResponse(manifest, webRequest),\n );\n return;\n }\n\n const font = await serveFont(webRequest);\n\n if (font) {\n await writeWebResponse(response, font);\n return;\n }\n\n const image = await optimizeImage(webRequest);\n\n if (image) {\n await writeWebResponse(response, image);\n return;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const result = await handleDevRequest(\n manifest,\n webRequest,\n createDevRuntimeOptions(options, documentSecurity.transform),\n );\n\n if (result === \"next\") {\n // Vite owns its own asset URLs, so an unmatched request still\n // falls through. The post middleware below is what turns whatever\n // Vite could not serve into the same negotiated not-found\n // production returns.\n next();\n return;\n }\n\n applyDevDocumentSecurity(result, documentSecurity.nonce);\n await writeWebResponse(response, result);\n } catch (error) {\n next(error);\n }\n });\n\n // The returned hook registers this after the Vite middleware. It sees\n // only requests that Vite cannot serve. `appType` is \"custom\", so no SPA\n // fallback intercepts these requests. Development and production render\n // the same negotiated not-found response for an unmatched path.\n return () => {\n server.middlewares.use(async (request, response, next) => {\n try {\n let webRequest: Request;\n\n try {\n webRequest = toWebRequest(request, {\n allowedHosts: [request.headers.host ?? \"localhost\"],\n });\n } catch (error) {\n if (error instanceof UnsupportedMethodError) {\n writeNotImplemented(response);\n return;\n }\n\n throw error;\n }\n\n const routesDir = resolve(\n server.config.root,\n options.routesDir ?? \"src/routes\",\n );\n const manifest = await loadDevManifest(server, request, routesDir);\n\n warnMissingRootNotFound(manifest, routesDir);\n\n const documentSecurity = createDevDocumentSecurity(\n server,\n viteNoncePlaceholder,\n );\n const notFoundResponse = await renderNotFoundResponse(\n manifest,\n webRequest,\n createDevFallbackOptions(options, documentSecurity.transform),\n );\n applyDevDocumentSecurity(\n notFoundResponse,\n documentSecurity.nonce,\n );\n await writeWebResponse(response, notFoundResponse);\n } catch (error) {\n next(error);\n }\n });\n };\n },\n };\n}\n\ntype AstNode = {\n [key: string]: unknown;\n end: number;\n start: number;\n type: string;\n};\n\n// TYPE-EVIDENCE: rollup returns a generic program node. The local type is a loose access shape.\nfunction asAstNode(value: unknown): AstNode {\n // TYPE-EVIDENCE: the caller passes a rollup program node. The cast labels it with the loose access shape.\n return value as AstNode;\n}\n\n// Vite 6 treats the `meta` token in `import.meta` as an imported reference.\n// Give an imported `meta` binding a private name before development SSR runs.\nfunction protectSsrImportMeta(code: string, id: string) {\n if (!code.includes(\"import.meta\")) {\n return null;\n }\n\n const ast = asAstNode(parseAst(code));\n const declaration = asNodeArray(ast.body).find((node) =>\n node.type === \"ImportDeclaration\" &&\n asNodeArray(node.specifiers).some((specifier) =>\n asNode(specifier.local)?.type === \"Identifier\" &&\n asNode(specifier.local)?.name === \"meta\"\n )\n );\n const specifier = declaration &&\n asNodeArray(declaration.specifiers).find((candidate) =>\n asNode(candidate.local)?.type === \"Identifier\" &&\n asNode(candidate.local)?.name === \"meta\"\n );\n const local = specifier && asNode(specifier.local);\n\n if (!declaration || !specifier || !local) {\n return null;\n }\n\n let alias = \"__demiurge_imported_meta__\";\n while (new RegExp(`\\\\b${alias}\\\\b`).test(code)) {\n alias += \"_\";\n }\n\n const editor = new MagicString(code);\n const imported = asNode(specifier.imported);\n editor.overwrite(\n local.start,\n local.end,\n imported?.start === local.start ? `meta as ${alias}` : alias,\n );\n editor.appendLeft(declaration.end, `\\nconst meta = ${alias};`);\n\n return {\n code: editor.toString(),\n map: editor.generateMap({\n hires: \"boundary\",\n includeContent: true,\n source: id,\n }),\n };\n}\n\n// Page data and document contributions are server capabilities. Vite and React\n// first parse TypeScript and JSX. The plugin then removes these capabilities\n// before Rollup follows the final client graph. This sequence excludes request\n// code and server-only imports from browser chunks. The exported document\n// bindings remain as `undefined` so the\n// route module keeps a stable shape without evaluating their initializers.\nexport function stripClientPageData(code: string) {\n const ast = asAstNode(parseAst(code));\n const dataRanges: Array<{ end: number; start: number }> = [];\n const documentRanges = findDocumentContributionRanges(ast);\n const serverImports: AstNode[] = [];\n\n walkAst(ast, (node) => {\n if (node.type === \"ImportDeclaration\" && isServerOnlyImport(node)) {\n serverImports.push(node);\n return;\n }\n\n if (node.type !== \"CallExpression\" || !isPageCallee(node.callee)) {\n return;\n }\n\n const argument = asNodeArray(node.arguments)[0];\n if (argument?.type !== \"ObjectExpression\") {\n return;\n }\n\n for (const property of asNodeArray(argument.properties)) {\n if (property.type === \"Property\" && propertyName(property.key) === \"data\") {\n dataRanges.push({ end: property.end, start: property.start });\n }\n }\n });\n\n const serverRanges = [...dataRanges, ...documentRanges];\n\n if (serverRanges.length === 0) {\n return code;\n }\n\n const removalRanges = [...serverRanges];\n for (const declaration of serverImports) {\n const localNames = asNodeArray(declaration.specifiers)\n .map((specifier) => asNode(specifier.local))\n .filter((local): local is AstNode => local?.type === \"Identifier\")\n .map((local) => String(local.name));\n const masked = maskRanges(code, [\n ...serverRanges,\n { end: declaration.end, start: declaration.start },\n ]);\n const leakedName = localNames.find((name) =>\n new RegExp(`\\\\b${escapeRegExp(name)}\\\\b`).test(masked)\n );\n\n if (leakedName) {\n throw new Error(\n `Server-only import ${JSON.stringify(leakedName)} is used by client route code. Move that use into page data, a document contribution, or a client-safe module.`,\n );\n }\n\n removalRanges.push({ end: declaration.end, start: declaration.start });\n }\n\n return replaceRanges(code, removalRanges, (range) =>\n dataRanges.includes(range) ? \"data: undefined\" :\n documentRanges.includes(range) ? \"undefined\" : \"\"\n );\n}\n\nconst documentContributionNames = new Set([\"links\", \"metadata\", \"scripts\"]);\n\nfunction findDocumentContributionRanges(ast: AstNode) {\n const exportedLocals = new Set<string>();\n\n for (const statement of asNodeArray(ast.body)) {\n if (statement.type !== \"ExportNamedDeclaration\") continue;\n\n const declaration = asNode(statement.declaration);\n if (declaration?.type === \"VariableDeclaration\") {\n for (const declarator of asNodeArray(declaration.declarations)) {\n const id = asNode(declarator.id);\n if (\n id?.type === \"Identifier\" &&\n documentContributionNames.has(String(id.name))\n ) {\n exportedLocals.add(String(id.name));\n }\n }\n }\n\n for (const specifier of asNodeArray(statement.specifiers)) {\n const exported = propertyName(specifier.exported);\n const local = propertyName(specifier.local);\n if (exported && local && documentContributionNames.has(exported)) {\n exportedLocals.add(local);\n }\n }\n }\n\n const ranges: Array<{ end: number; start: number }> = [];\n walkAst(ast, (node) => {\n if (node.type !== \"VariableDeclarator\") return;\n const id = asNode(node.id);\n const init = asNode(node.init);\n if (\n id?.type === \"Identifier\" &&\n exportedLocals.has(String(id.name)) &&\n init\n ) {\n ranges.push({ end: init.end, start: init.start });\n }\n });\n\n return ranges;\n}\n\nfunction isRouteSource(\n root: string,\n options: DemiurgeVitePluginOptions,\n id: string,\n) {\n const file = id.split(\"?\", 1)[0] ?? id;\n const routesRoot = resolve(root, options.routesDir ?? \"src/routes\");\n const pathFromRoutes = relative(routesRoot, file);\n return pathFromRoutes !== \"\" &&\n pathFromRoutes !== \"..\" &&\n !pathFromRoutes.startsWith(`..${sep}`);\n}\n\nfunction walkAst(value: unknown, visit: (node: AstNode) => void) {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n\n // TYPE-EVIDENCE: the value was checked to be an object. The cast adds the loose AST node shape.\n const node = value as Partial<AstNode>;\n if (typeof node.type !== \"string\") return;\n // TYPE-EVIDENCE: the type field check above confirms the value is an AST node. The cast asserts that node shape.\n visit(node as AstNode);\n for (const [key, child] of Object.entries(node)) {\n if (!new Set([\"end\", \"loc\", \"start\", \"type\"]).has(key)) {\n walkAst(child, visit);\n }\n }\n}\n\nfunction asNode(value: unknown) {\n // TYPE-EVIDENCE: the type in value check confirms the value is an AST node. The cast asserts that node shape.\n return value && typeof value === \"object\" && \"type\" in value\n ? value as AstNode\n : undefined;\n}\n\nfunction asNodeArray(value: unknown) {\n return Array.isArray(value)\n ? value.map(asNode).filter((node): node is AstNode => Boolean(node))\n : [];\n}\n\nfunction isPageCallee(value: unknown) {\n const callee = asNode(value);\n if (callee?.type === \"Identifier\") return callee.name === \"page\";\n return callee?.type === \"MemberExpression\" &&\n propertyName(callee.property) === \"page\";\n}\n\nfunction propertyName(value: unknown) {\n const property = asNode(value);\n return property?.type === \"Identifier\" || property?.type === \"Literal\"\n ? String(property.name ?? property.value)\n : undefined;\n}\n\nfunction isServerOnlyImport(node: AstNode) {\n const source = asNode(node.source)?.value;\n return typeof source === \"string\" &&\n /(?:^|[/.-])server(?:[/.-]|$)/.test(source);\n}\n\nfunction maskRanges(code: string, ranges: Array<{ end: number; start: number }>) {\n const characters = [...code];\n for (const { end, start } of ranges) {\n characters.fill(\" \", start, end);\n }\n return characters.join(\"\");\n}\n\nfunction replaceRanges(\n code: string,\n ranges: Array<{ end: number; start: number }>,\n replacement: (range: { end: number; start: number }) => string,\n) {\n return [...ranges]\n .sort((left, right) => right.start - left.start)\n .reduce(\n (result, range) =>\n `${result.slice(0, range.start)}${replacement(range)}${result.slice(range.end)}`,\n code,\n );\n}\n\nfunction escapeRegExp(value: string) {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction createViteConfig(\n config: UserConfig,\n environment: ConfigEnv,\n viteNoncePlaceholder: string,\n): UserConfig {\n return {\n appType: \"custom\",\n build: {\n assetsInlineLimit: config.build?.assetsInlineLimit ?? 0,\n ...(environment.isSsrBuild &&\n config.build?.target === undefined &&\n config.ssr?.target !== \"webworker\"\n ? { target: \"node22.13\" }\n : {}),\n rollupOptions: {\n input: config.build?.rollupOptions?.input ?? CLIENT_ENTRY_ID,\n },\n },\n ...(environment.command === \"serve\"\n ? {\n html: { cspNonce: viteNoncePlaceholder },\n ssr: { external: [PACKAGE_NAME] },\n }\n : {}),\n };\n}\n\nexport function createClientEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n const stylesImport = createStylesImport(root, options);\n\n return `import { hydrateFileRouter } from \"${PACKAGE_NAME}\";\n${stylesImport}\n\n${createRouteMapSource(routesDir, {\n exportRoutes: false,\n includeServerOnly: false,\n })}\n\nvoid hydrateFileRouter({ routes });\n`;\n}\n\nexport function createServerEntrySource(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = options.routesDir ?? \"src/routes\";\n\n return `import { createRequestHandler } from \"${PACKAGE_NAME}\";\n\n${createRouteMapSource(routesDir, {\n exportRoutes: true,\n includeServerOnly: true,\n eagerModules: true,\n })}\n\nexport function createHandler(options = {}) {\n const { clientEntry, lang, styles, title, ...handlerOptions } = options;\n\n return createRequestHandler({\n ...handlerOptions,\n routes,\n routeModules,\n ssr: {\n clientEntry,\n lang: lang ?? ${JSON.stringify(options.document?.lang)},\n styles,\n title: title ?? ${JSON.stringify(options.document?.title)},\n },\n });\n}\n`;\n}\n\n// Both virtual entries use this function. Therefore, their prefix removal and\n// route-key formats stay equal. The server entry requires framework-attached\n// `.ts` files such as `@policy.ts` and `@middleware.ts`. Previously, a\n// `.tsx`-only glob omitted these files from production. Development still found\n// and applied them.\nfunction createRouteMapSource(\n routesDir: string,\n {\n exportRoutes,\n eagerModules = false,\n includeServerOnly,\n }: {\n eagerModules?: boolean;\n exportRoutes: boolean;\n includeServerOnly: boolean;\n },\n) {\n const routesGlobs = toRootAbsoluteGlobs(routesDir, includeServerOnly);\n const routesPrefix = toRootAbsolutePrefix(routesDir);\n\n return eagerModules\n ? `const eagerRouteModules = import.meta.glob(${JSON.stringify(routesGlobs)}, { eager: true });\nconst routePrefix = ${JSON.stringify(routesPrefix)};\nexport const routeModules = Object.fromEntries(\n Object.entries(eagerRouteModules).map(([file, module]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n module,\n ]),\n);\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, module]) => [\n file,\n async () => module,\n ]),\n);`\n : `const routeModules = import.meta.glob(${JSON.stringify(routesGlobs)});\nconst routePrefix = ${JSON.stringify(routesPrefix)};\n${exportRoutes ? \"export \" : \"\"}const routes = Object.fromEntries(\n Object.entries(routeModules).map(([file, load]) => [\n \\`./routes/\\${file.slice(routePrefix.length)}\\`,\n load,\n ]),\n);`;\n}\n\n// These two files run only on the server. They control a request before the\n// route runs and do not render. A client glob would create public chunks in\n// `dist/client`. These chunks could expose credentials, authorization logic, or\n// internal host names from a middleware or policy closure.\nconst serverOnlyRouteFiles = [\"@middleware.ts\", \"@policy.ts\"];\n\nfunction toRootAbsoluteGlobs(routesDir: string, includeServerOnly: boolean) {\n const base = `/${routesDir.replace(/^\\/|\\/$/g, \"\")}`;\n const globs = [`${base}/**/*.{ts,tsx}`];\n\n if (!includeServerOnly) {\n globs.push(\n ...serverOnlyRouteFiles.flatMap((fileName) => [\n `!${base}/${fileName}`,\n `!${base}/**/${fileName}`,\n ]),\n );\n }\n\n return globs;\n}\n\nfunction toRootAbsolutePrefix(routesDir: string) {\n return `/${routesDir.replace(/^\\/|\\/$/g, \"\")}/`;\n}\n\nfunction createStylesImport(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n if (options.styles === false) {\n return \"\";\n }\n\n const stylesFile = options.styles ?? \"src/styles.css\";\n const resolvedStylesFile = resolve(root, stylesFile);\n\n return existsSync(resolvedStylesFile)\n ? `import ${JSON.stringify(`/${stylesFile.replace(/^\\/+/, \"\")}`)};`\n : \"\";\n}\n\n// Development serves the same image URLs that production serves. A static\n// loader path describes its own transform, so the same optimizer answers\n// both loaders without any build output.\n// Only `configureServer` registers the route audit panel, and Vite runs that\n// hook for the development server alone. A production environment removes the\n// panel as well, because a build or a start script can set that environment.\nexport function isRouteAuditEnabled(options: DemiurgeVitePluginOptions) {\n return options.devtools !== false && process.env.NODE_ENV !== \"production\";\n}\n\nexport function createDevImageOptimizer(\n server: ViteDevServer,\n options: DemiurgeVitePluginOptions,\n) {\n const publicDir = server.config.publicDir;\n const optimizerPath = options.images?.optimizerPath ?? \"/_demiurge/image\";\n\n if (!publicDir) {\n return async () => null;\n }\n\n return createImageOptimizer({\n policy: options.images,\n resolveVariant: (pathname) =>\n parseImageVariantPath(pathname, optimizerPath),\n root: publicDir,\n });\n}\n\n// Development renders through the production pipeline. It adds the virtual\n// client entry, the Vite HTML transform, and a development flag for stack\n// traces. The shared handler makes all security and routing decisions.\nfunction createDevRuntimeOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n dev: true,\n ssr: createDevSsrOptions(options),\n transformDocument,\n renderPage: async (\n match: Parameters<PageRenderer>[0],\n renderOptions: Parameters<PageRenderer>[1],\n ) => {\n if (match.render.mode === \"streaming\") {\n return await renderStreamingPageResponse(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n transformDocument,\n });\n }\n\n const html = await transformDocument(\n renderPageDocument(match, {\n ...renderOptions,\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n }),\n );\n\n return new Response(html, {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n },\n };\n}\n\nfunction createDevDocumentSecurity(\n server: ViteDevServer,\n viteNoncePlaceholder: string,\n) {\n const nonce = createCspNonce();\n const shieldNonce = createCspNonce();\n\n return {\n nonce,\n transform: async (html: string) => {\n const shielded = shieldViteNonceTargets(html, shieldNonce);\n const transformed = await server.transformIndexHtml(\"/\", shielded);\n\n return replaceNonceAttribute(\n replaceNonceAttribute(transformed, shieldNonce),\n viteNoncePlaceholder,\n nonce,\n );\n },\n };\n}\n\nfunction shieldViteNonceTargets(html: string, nonce: string) {\n const lowerHtml = html.toLowerCase();\n let cursor = 0;\n let output = \"\";\n\n while (cursor < html.length) {\n const tagStart = html.indexOf(\"<\", cursor);\n\n if (tagStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, tagStart);\n\n if (lowerHtml.startsWith(\"<!--\", tagStart)) {\n const commentEnd = lowerHtml.indexOf(\"-->\", tagStart + 4);\n const end = commentEnd === -1 ? html.length : commentEnd + 3;\n output += html.slice(tagStart, end);\n cursor = end;\n continue;\n }\n\n const name = lowerHtml.slice(tagStart).match(/^<\\s*(script|style|link)\\b/)?.[1];\n\n if (!name) {\n output += \"<\";\n cursor = tagStart + 1;\n continue;\n }\n\n const tagEnd = findHtmlTagEnd(html, tagStart);\n\n if (tagEnd === -1) {\n return output + html.slice(tagStart);\n }\n\n const openingTag = html.slice(tagStart, tagEnd + 1);\n output += /(?:^|\\s)nonce(?:\\s|=|>)/i.test(openingTag)\n ? openingTag\n : addNonceAttribute(openingTag, nonce);\n cursor = tagEnd + 1;\n\n if (name === \"script\" || name === \"style\") {\n const closeStart = lowerHtml.indexOf(`</${name}`, cursor);\n\n if (closeStart === -1) {\n return output + html.slice(cursor);\n }\n\n output += html.slice(cursor, closeStart);\n cursor = closeStart;\n }\n }\n\n return output;\n}\n\nfunction findHtmlTagEnd(html: string, start: number) {\n let quote: \"\\\"\" | \"'\" | undefined;\n\n for (let index = start + 1; index < html.length; index++) {\n const character = html[index];\n\n if (quote) {\n if (character === quote) quote = undefined;\n continue;\n }\n\n if (character === \"\\\"\" || character === \"'\") {\n quote = character;\n } else if (character === \">\") {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction addNonceAttribute(openingTag: string, nonce: string) {\n const insertion = /\\/\\s*>$/.test(openingTag)\n ? openingTag.lastIndexOf(\"/\")\n : openingTag.length - 1;\n\n return `${openingTag.slice(0, insertion)} nonce=\"${nonce}\"${openingTag.slice(insertion)}`;\n}\n\nfunction replaceNonceAttribute(\n html: string,\n current: string,\n replacement?: string,\n) {\n const pattern = new RegExp(\n `(\\\\snonce\\\\s*=\\\\s*)([\"'])${escapeRegExp(current)}\\\\2`,\n \"g\",\n );\n\n return html.replace(\n pattern,\n replacement ? `$1\"${replacement}\"` : \"\",\n );\n}\n\nfunction applyDevDocumentSecurity(response: Response, nonce: string) {\n const contentType = response.headers.get(\"content-type\");\n const csp = response.headers.get(\"content-security-policy\");\n\n if (!contentType?.toLowerCase().startsWith(\"text/html\") || !csp) {\n return;\n }\n\n const source = `'nonce-${nonce}'`;\n const withScriptNonce = addCspSource(\n csp,\n [\"script-src-elem\", \"script-src\"],\n \"script-src\",\n source,\n );\n const withStyleNonce = allowsUnsafeInline(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n )\n ? withScriptNonce\n : addCspSource(\n withScriptNonce,\n [\"style-src-elem\", \"style-src\"],\n \"style-src\",\n source,\n );\n\n response.headers.set(\"content-security-policy\", withStyleNonce);\n response.headers.set(\"cache-control\", \"private, no-store\");\n}\n\nfunction addCspSource(\n csp: string,\n directiveNames: readonly string[],\n fallbackDirectiveName: \"script-src\" | \"style-src\",\n source: string,\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n\n const defaultDirective = directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n );\n\n if (directiveIndex === -1 && !defaultDirective) return csp;\n\n const [currentName, ...currentSources] =\n (directiveIndex === -1 ? defaultDirective! : directives[directiveIndex]!)\n .split(/\\s+/);\n const updatedDirective = [\n directiveIndex === -1 ? fallbackDirectiveName : currentName!,\n ...new Set([\n ...currentSources.filter((current) => current !== \"'none'\"),\n source,\n ]),\n ].join(\" \");\n\n if (directiveIndex === -1) {\n directives.push(updatedDirective);\n } else {\n directives[directiveIndex] = updatedDirective;\n }\n\n return directives.join(\"; \");\n}\n\nfunction allowsUnsafeInline(\n csp: string,\n directiveNames: readonly string[],\n) {\n const directives = csp.split(\";\").map((directive) => directive.trim());\n const directiveIndex = findCspDirectiveIndex(directives, directiveNames);\n const effectiveDirective = directiveIndex === -1\n ? directives.find((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === \"default-src\"\n )\n : directives[directiveIndex];\n const sources = effectiveDirective?.split(/\\s+/).slice(1) ?? [];\n\n return sources.includes(\"'unsafe-inline'\") &&\n !sources.some((source) => /^'(?:nonce-|sha(?:256|384|512)-)/i.test(source));\n}\n\nfunction findCspDirectiveIndex(\n directives: readonly string[],\n directiveNames: readonly string[],\n) {\n for (const name of directiveNames) {\n const index = directives.findIndex((directive) =>\n directive.split(/\\s+/, 1)[0]?.toLowerCase() === name\n );\n\n if (index !== -1) return index;\n }\n\n return -1;\n}\n\n// Both dev middlewares need the manifest for the same request, and building\n// it walks the routes directory. The pre middleware always runs, so the post\n// middleware reuses what it already produced rather than scanning twice on\n// every unmatched request.\nconst DEV_MANIFEST = Symbol.for(\"demiurge.devManifest\");\n\ntype DevManifestCarrier = { [DEV_MANIFEST]?: RouteManifest };\n\nasync function loadDevManifest(\n server: ViteDevServer,\n request: IncomingMessage,\n routesDir: string,\n) {\n // TYPE-EVIDENCE: the cast adds the symbol-keyed manifest carrier field used for request-local caching.\n const carrier = request as IncomingMessage & DevManifestCarrier;\n const cached = carrier[DEV_MANIFEST];\n\n if (cached) {\n return cached;\n }\n\n const manifest = createRouteManifest(\n await createDevRouteImporters(server, routesDir),\n );\n\n carrier[DEV_MANIFEST] = manifest;\n\n return manifest;\n}\n\nfunction createDevSsrOptions(options: DemiurgeVitePluginOptions) {\n return {\n clientEntry: DEV_CLIENT_ENTRY_PATH,\n lang: options.document?.lang,\n title: options.document?.title,\n };\n}\n\nfunction createDevFallbackOptions(\n options: DemiurgeVitePluginOptions,\n transformDocument: (html: string) => Promise<string>,\n) {\n return {\n ...createDevSsrOptions(options),\n dev: true,\n transformDocument,\n };\n}\n\nconst warnedRoots = new Set<string>();\n\n// The framework built-in is a temporary fallback, not a production 404. The\n// build gate enforces this rule. This warning gives the same message earlier.\nfunction warnMissingRootNotFound(manifest: RouteManifest, routesDir: string) {\n if (\n warnedRoots.has(routesDir) ||\n manifest.fallbacks.notFound.some(\n (fallback) => fallback.fileSegments.length === 0,\n )\n ) {\n return;\n }\n\n warnedRoots.add(routesDir);\n console.warn(missingRootNotFoundMessage(join(routesDir, \"@not-found.tsx\")));\n}\n\n// The framework ships a working 404 so nothing is ever blank, and refuses to\n// let an app reach production still rendering it. A generic framework page in\n// front of real users is a failure of the framework, not of the app that never\n// got around to it.\nexport async function assertRootNotFoundRoute(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDirOption = options.routesDir ?? \"src/routes\";\n const routesDir = resolve(root, routesDirOption);\n\n if (!existsSync(routesDir)) {\n return;\n }\n\n const files = await findRouteFiles(routesDir);\n const names = files.map((file) =>\n relative(routesDir, file).split(sep).join(\"/\"),\n );\n\n if (names.some((name) => /^@not-found\\.tsx?$/.test(name))) {\n return;\n }\n\n const pageRoute = await findPageRouteFile(files);\n\n // An API-only app never wants an HTML not-found document, and nagging it\n // would be user hostile. It builds clean and gets problem+json.\n if (!pageRoute) {\n return;\n }\n\n throw new Error(\n missingRootNotFoundBuildMessage(\n routesDirOption,\n relative(routesDir, pageRoute).split(sep).join(\"/\"),\n ),\n );\n}\n\n// Page detection is a source scan rather than a module evaluation: the plugin\n// cannot execute route modules at build time. A page route is a file that\n// calls `page(...)`, which is the only way to declare one.\nasync function findPageRouteFile(files: string[]) {\n for (const file of files) {\n // Framework-attached files own no address, so they are never page routes.\n if (relative(dirname(file), file).startsWith(\"@\")) {\n continue;\n }\n\n if (declaresPageRoute(await readFile(file, \"utf8\"))) {\n return file;\n }\n }\n\n return undefined;\n}\n\n// Escaped because a package name may contain `.`, which the regex would\n// otherwise read as a wildcard.\nconst PACKAGE_NAME_PATTERN = PACKAGE_NAME.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\nconst DEMIURGE_NAMED_IMPORT = new RegExp(\n `import\\\\s*\\\\{([^}]*)\\\\}\\\\s*from\\\\s*[\"']${PACKAGE_NAME_PATTERN}[\"']`,\n \"g\",\n);\n\n// The plugin cannot evaluate route modules during the build. Therefore, page\n// detection reads the source. It checks the import, not only the word. An API\n// application can call `db.users.page(2)` without serving an HTML document.\n// Only a page route imports `page` from the framework package.\nexport function declaresPageRoute(source: string) {\n const locals = [...source.matchAll(DEMIURGE_NAMED_IMPORT)].flatMap((match) =>\n match[1].split(\",\").flatMap((binding) => {\n const [imported, local] = binding.trim().split(/\\s+as\\s+/);\n\n // `import type { page }` cannot be called, and an alias renames what the\n // call site looks like.\n return imported.replace(/^type\\s+/, \"\") === \"page\"\n ? [local ?? imported]\n : [];\n }),\n );\n\n if (locals.length === 0) {\n return false;\n }\n\n // Strip the import statements first so the binding list is not itself\n // mistaken for a call.\n const body = source.replace(DEMIURGE_NAMED_IMPORT, \"\");\n\n return locals.some((local) => new RegExp(`\\\\b${local}\\\\s*\\\\(`).test(body));\n}\n\nexport function missingRootNotFoundBuildMessage(\n routesDir: string,\n pageRoute: string,\n) {\n return `Demiurge will not build an app with page routes and no ${routesDir}/@not-found.tsx.\n\n\"${pageRoute}\" declares a page, so a browser can reach a path this app does not serve. Decide what that looks like rather than shipping the framework built-in.\n\nCreate ${routesDir}/@not-found.tsx:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n\nIt renders inside the layouts above the requested path. Opt out with \"export const layout = false\".`;\n}\n\nexport function missingRootNotFoundMessage(notFoundFile: string) {\n return `Demiurge is serving its built-in 404 because ${notFoundFile} does not exist.\n\nCreate it before building for production:\n\n export default function NotFound({ pathname }: { pathname: string }) {\n return <h1>Nothing at {pathname}</h1>;\n }\n`;\n}\n\nexport function createDocumentHtml({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n}: {\n entrySrc: string;\n lang?: string;\n links?: LinkTag[];\n metadata?: ResolvedMetadata;\n nonce?: string;\n scripts?: ScriptTag[];\n styles?: string[];\n title?: string;\n}) {\n return renderDocument({\n entrySrc,\n lang,\n links,\n metadata,\n nonce,\n scripts,\n styles,\n title,\n });\n}\n\nasync function generateTypedRoutes(\n root: string,\n options: DemiurgeVitePluginOptions,\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n const outputFile = resolve(\n root,\n typeof options.typedRoutes === \"object\"\n ? options.typedRoutes.outputFile ?? DEFAULT_TYPED_ROUTES_OUTPUT\n : DEFAULT_TYPED_ROUTES_OUTPUT,\n );\n\n await generateRoutes({ outputFile, routesDir });\n}\n\nfunction isRouteFile(routesDir: string, file: string) {\n return (\n file.startsWith(routesDir) &&\n /\\.tsx?$/.test(file)\n );\n}\n\nexport async function createDevRouteImporters(\n server: ViteDevServer,\n routesDir: string,\n) {\n const files = await findRouteFiles(routesDir);\n const routes: Record<string, RouteImporter> = {};\n\n for (const file of files) {\n const routeKey = toRouteKey(routesDir, file);\n // TYPE-EVIDENCE: the SSR loader returns a module record for a route file. The cast labels it as a route module.\n routes[routeKey] = async () =>\n (await server.ssrLoadModule(file)) as RouteModule;\n }\n\n return routes;\n}\n\nexport async function handleDevRequest(\n manifest: RouteManifest,\n request: Request,\n options: Parameters<typeof handleRequestWithManifest>[2] = {},\n) {\n const url = new URL(request.url);\n const routeMatch = findRouteMatch(manifest.routes, url.pathname);\n\n if (!routeMatch) {\n return \"next\" as const;\n }\n\n return await handleRequestWithManifest(manifest, request, options);\n}\n\nasync function findRouteFiles(directory: string) {\n const entries = await readdir(directory, {\n recursive: true,\n withFileTypes: true,\n });\n\n return entries\n .filter((entry) => entry.isFile() && /\\.tsx?$/.test(entry.name))\n .map((entry) => resolve(entry.parentPath, entry.name));\n}\n\n// Every route file is read and parsed. Without a cap, a large route tree opens\n// one descriptor per file at once, which is how this hits EMFILE rather than a\n// CPU limit.\nconst policyVerificationConcurrency = 8;\nconst policyVerificationDebounceMs = 50;\n\nasync function mapWithConcurrency<Item, Result>(\n items: readonly Item[],\n limit: number,\n task: (item: Item) => Promise<Result>,\n) {\n const results = new Array<Result>(items.length);\n let next = 0;\n\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (next < items.length) {\n const index = next++;\n results[index] = await task(items[index]!);\n }\n },\n );\n\n await Promise.all(workers);\n\n return results;\n}\n\nexport async function verifyRoutePolicies(\n root: string,\n options: DemiurgeVitePluginOptions = {},\n) {\n const routesDir = resolve(root, options.routesDir ?? \"src/routes\");\n\n if (!existsSync(routesDir)) return [];\n const findings = (await mapWithConcurrency(\n await findRouteFiles(routesDir),\n policyVerificationConcurrency,\n verifyRoutePolicyFile,\n )).flat();\n\n return findings.sort((left, right) =>\n left.file.localeCompare(right.file) ||\n (left.exportName ?? \"\").localeCompare(right.exportName ?? \"\") ||\n left.code.localeCompare(right.code)\n );\n}\n\nexport function formatStaticPolicyFindings(findings: StaticPolicyFinding[]) {\n return [\n \"Demiurge found invalid static route policy:\",\n ...findings.map(formatStaticPolicyFinding),\n ].join(\"\\n\");\n}\n\nfunction formatStaticPolicyFinding(finding: StaticPolicyFinding) {\n const source = finding.exportName\n ? `${finding.file} export ${finding.exportName}`\n : finding.file;\n return `${source}: [${finding.code}] ${finding.message}`;\n}\n\nfunction toRouteKey(routesDir: string, file: string) {\n const relativePath = relative(routesDir, file).split(sep).join(\"/\");\n return `./routes/${relativePath}`;\n}\n"],"names":["PACKAGE_NAME","generateRoutes","options","routeFiles","findRouteFiles","middleware","file","toMiddlewareInfo","value","routes","toRouteInfo","route","a","b","source","renderRoutesModule","mkdir","dirname","writeFile","directory","readdir","entry","resolve","routesDir","fileSegments","relative","sep","urlSegments","segment","isRouteGroupSegment","pathVars","isAttachedFileForRoute","importPath","attachedFileSegments","routeFileSegments","index","renderMiddlewareImport","_entry","renderMiddlewareContextAlias","renderPathVarsEntry","renderConcretePathEntry","renderRequestContextEntry","pathType","name","toConcretePathType","contexts","context","pattern","part","escapeTemplate","httpMethods","responseHelpers","verifyRoutePolicyFile","readFile","verifyRoutePolicySource","loader","transformed","transformWithEsbuild","extracted","extractRouteModule","validateExtractedRouteModule","code","ast","parseAst","imports","collectCoreImports","constants","collectConstants","declarations","collectVariableInitializers","exports","collectNamedExports","capabilities","declaredMethods","policy","exportName","localName","initializer","extractRoutePolicy","isHttpMethod","capability","extractCapability","statement","asNodeArray","declaration","asNode","declarator","identifierName","specifier","exported","propertyName","local","node","helper","arguments_","optionsNode","cors","evaluateObjectProperty","securityPolicy","isRecord","property","unresolved","item","evaluateLiteral","argument","result","valueNode","document","extractSecurityPolicy","callee","objectName","preset","security","routeModule","findings","availableMethods","validateCorsPolicy","error","finding","errorMessage","method","validateRateLimit","createSecurityHeaders","toFragmentDocument","endpoints","declaresEndpoints","reportTo","validateRateLimitPolicy","message","imported","quasi","values","element","child","fallback","ROUTE_AUDIT_PATH","supportedMethods","isRouteAuditRequest","request","createRouteAuditResponse","manifest","url","report","createRouteAudit","json","renderRouteAuditDocument","target","origin","pathname","routeRequest","routeMatch","matchRoute","loadInheritedRoutePolicy","finishRouteAudit","selectMethod","cacheReads","page","loadPageRoute","createRecordingCache","match","layout","toRoutePattern","input","nonce","securityPolicyRequiresNonce","createCspNonce","scripts","script","auditOptions","createSecurityAudit","findRouteMatch","MalformedPathnameError","reads","cache","createMemoryCache","serializeCacheKey","formatDuration","serializeCacheTag","duration","panelStyles","escapeHtml","renderRouteSection","renderFindingsSection","renderHeadersSection","renderPolicySection","renderMetadataSection","renderScriptsSection","renderCacheSection","section","table","none","entries","list","renderFinding","headers","names","metadata","rows","read","title","body","CLIENT_ENTRY_ID","DEV_CLIENT_ENTRY_PATH","RESOLVED_CLIENT_ENTRY_ID","SERVER_ENTRY_ID","RESOLVED_SERVER_ENTRY_ID","DEFAULT_TYPED_ROUTES_OUTPUT","demiurge","root","isBuild","viteNoncePlaceholder","config","environment","createViteConfig","id","createClientEntrySource","createServerEntrySource","transformOptions","isRouteSource","protectSsrImportMeta","stripClientPageData","_outputOptions","bundle","styles","asset","clientEntry","createDocumentHtml","assertRootNotFoundRoute","verifyRoutePolicies","formatStaticPolicyFindings","generateTypedRoutes","server","reportPolicyFindings","formatStaticPolicyFinding","policyVerificationTimer","policyVerificationRun","runPolicyVerification","startPolicyVerification","policyVerificationDebounceMs","isRouteFile","event","routeAuditEnabled","isRouteAuditEnabled","optimizeImage","createDevImageOptimizer","serveFont","createFontAssetHandler","response","next","webRequest","toWebRequest","UnsupportedMethodError","writeNotImplemented","loadDevManifest","writeWebResponse","font","image","documentSecurity","createDevDocumentSecurity","handleDevRequest","createDevRuntimeOptions","applyDevDocumentSecurity","warnMissingRootNotFound","notFoundResponse","renderNotFoundResponse","createDevFallbackOptions","candidate","alias","editor","MagicString","dataRanges","documentRanges","findDocumentContributionRanges","serverImports","walkAst","isServerOnlyImport","isPageCallee","serverRanges","removalRanges","localNames","masked","maskRanges","leakedName","escapeRegExp","replaceRanges","range","documentContributionNames","exportedLocals","ranges","init","routesRoot","pathFromRoutes","visit","key","characters","end","start","replacement","left","right","stylesImport","createStylesImport","createRouteMapSource","exportRoutes","eagerModules","includeServerOnly","routesGlobs","toRootAbsoluteGlobs","routesPrefix","toRootAbsolutePrefix","serverOnlyRouteFiles","base","globs","fileName","stylesFile","resolvedStylesFile","existsSync","publicDir","optimizerPath","createImageOptimizer","parseImageVariantPath","transformDocument","createDevSsrOptions","renderOptions","renderStreamingPageResponse","html","renderPageDocument","shieldNonce","shielded","shieldViteNonceTargets","replaceNonceAttribute","lowerHtml","cursor","output","tagStart","commentEnd","tagEnd","findHtmlTagEnd","openingTag","addNonceAttribute","closeStart","quote","character","insertion","current","contentType","csp","withScriptNonce","addCspSource","withStyleNonce","allowsUnsafeInline","directiveNames","fallbackDirectiveName","directives","directive","directiveIndex","findCspDirectiveIndex","defaultDirective","currentName","currentSources","updatedDirective","sources","DEV_MANIFEST","carrier","cached","createRouteManifest","createDevRouteImporters","warnedRoots","missingRootNotFoundMessage","join","routesDirOption","files","pageRoute","findPageRouteFile","missingRootNotFoundBuildMessage","declaresPageRoute","PACKAGE_NAME_PATTERN","DEMIURGE_NAMED_IMPORT","locals","binding","notFoundFile","entrySrc","lang","links","renderDocument","outputFile","routeKey","toRouteKey","handleRequestWithManifest","policyVerificationConcurrency","mapWithConcurrency","items","limit","task","results","workers"],"mappings":";;;;;;;;;;;;AASO,MAAMA,IAAe;ACa5B,eAAsBC,GAAeC,GAAgC;AACnE,QAAMC,IAAa,MAAMC,GAAeF,EAAQ,SAAS,GACnDG,IAAaF,EAChB,IAAI,CAACG,MAASC,GAAiBL,GAASI,CAAI,CAAC,EAC7C,OAAO,CAACE,MAAmC,EAAQA,CAAM,GACtDC,IAASN,EACZ,IAAI,CAACG,MAASI,GAAYR,EAAQ,WAAWI,GAAMD,CAAU,CAAC,EAC9D,OAAO,CAACM,MAA8B,EAAQA,CAAM,EACpD,KAAK,CAACC,GAAGC,MAAMD,EAAE,QAAQ,cAAcC,EAAE,OAAO,CAAC,GAE9CC,IAASC,GAAmBN,GAAQJ,CAAU;AAEpD,eAAMW,GAAMC,GAAQf,EAAQ,UAAU,GAAG,EAAE,WAAW,IAAM,GAC5D,MAAMgB,GAAUhB,EAAQ,YAAYY,CAAM,GAEnC;AAAA,IACL,QAAAL;AAAA,IACA,QAAAK;AAAA,EAAA;AAEJ;AAEA,eAAeV,GAAee,GAAmB;AAM/C,UALgB,MAAMC,GAAQD,GAAW;AAAA,IACvC,WAAW;AAAA,IACX,eAAe;AAAA,EAAA,CAChB,GAGE,OAAO,CAACE,MAAUA,EAAM,O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