@warlock.js/web 5.5.0 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +27 -5
  2. package/esm/build/contribution.d.mts +2 -2
  3. package/esm/build/contribution.mjs.map +1 -1
  4. package/esm/build/discover-pages.mjs +127 -205
  5. package/esm/build/discover-pages.mjs.map +1 -1
  6. package/esm/build/generate-pages-barrel.mjs +5 -3
  7. package/esm/build/generate-pages-barrel.mjs.map +1 -1
  8. package/esm/build/public-files.mjs +29 -1
  9. package/esm/build/public-files.mjs.map +1 -1
  10. package/esm/build/read-metadata-keys.mjs +225 -0
  11. package/esm/build/read-metadata-keys.mjs.map +1 -0
  12. package/esm/build/read-route-exports.mjs.map +1 -1
  13. package/esm/client/build-hydrated-tree.mjs +1 -1
  14. package/esm/client/build-hydrated-tree.mjs.map +1 -1
  15. package/esm/client/navigation/document-metadata.mjs +108 -0
  16. package/esm/client/navigation/document-metadata.mjs.map +1 -0
  17. package/esm/client/navigation/navigation-root.mjs +23 -103
  18. package/esm/client/navigation/navigation-root.mjs.map +1 -1
  19. package/esm/client/navigation/scroll-to-fragment.mjs.map +1 -1
  20. package/esm/client/navigation/use-query-string.d.mts +35 -0
  21. package/esm/client/navigation/use-query-string.mjs +68 -0
  22. package/esm/client/navigation/use-query-string.mjs.map +1 -0
  23. package/esm/client/runtime/index.d.mts +1 -1
  24. package/esm/client/runtime/index.mjs +1 -1
  25. package/esm/client/runtime/manifest.mjs.map +1 -1
  26. package/esm/client/runtime/matcher.mjs.map +1 -1
  27. package/esm/client/runtime/types.d.mts +1 -1
  28. package/esm/components/link.mjs.map +1 -1
  29. package/esm/core/src/router/normalize-route-path.mjs +33 -0
  30. package/esm/core/src/router/normalize-route-path.mjs.map +1 -0
  31. package/esm/{hydration → entry}/index.mjs +1 -1
  32. package/esm/entry/index.mjs.map +1 -0
  33. package/esm/hydration-payload.mjs.map +1 -1
  34. package/esm/index.d.mts +3 -2
  35. package/esm/index.mjs +3 -2
  36. package/esm/loaders.d.mts +10 -3
  37. package/esm/localization.mjs.map +1 -1
  38. package/esm/metadata.d.mts +4 -4
  39. package/esm/metadata.mjs.map +1 -1
  40. package/esm/node_modules/.pnpm/@mongez_concat-route@1.2.0/node_modules/@mongez/concat-route/esm/index.mjs +33 -0
  41. package/esm/node_modules/.pnpm/@mongez_concat-route@1.2.0/node_modules/@mongez/concat-route/esm/index.mjs.map +1 -0
  42. package/esm/{runtime/register-modules.d.mts → register-modules.d.mts} +1 -1
  43. package/esm/{runtime/register-modules.mjs → register-modules.mjs} +1 -1
  44. package/esm/register-modules.mjs.map +1 -0
  45. package/esm/route.d.mts +35 -2
  46. package/esm/routing/duplicate-route-path.mjs +22 -0
  47. package/esm/routing/duplicate-route-path.mjs.map +1 -0
  48. package/esm/routing/layout-level.mjs +50 -0
  49. package/esm/routing/layout-level.mjs.map +1 -0
  50. package/esm/routing/layout-policy.mjs.map +1 -1
  51. package/esm/routing/query-string.d.mts +23 -1
  52. package/esm/routing/query-string.mjs +23 -1
  53. package/esm/routing/query-string.mjs.map +1 -1
  54. package/esm/routing/route-identity.mjs +27 -2
  55. package/esm/routing/route-identity.mjs.map +1 -1
  56. package/esm/routing/route-table.mjs.map +1 -1
  57. package/esm/routing/router-events.d.mts +5 -4
  58. package/esm/routing/router-events.mjs.map +1 -1
  59. package/esm/server/create-page-route-handler.d.mts +2 -2
  60. package/esm/server/create-page-route-handler.mjs +6 -6
  61. package/esm/server/create-page-route-handler.mjs.map +1 -1
  62. package/esm/server/{dev-server.mjs → dev-error-transport.mjs} +2 -2
  63. package/esm/server/dev-error-transport.mjs.map +1 -0
  64. package/esm/server/execute-page-request.mjs +87 -23
  65. package/esm/server/execute-page-request.mjs.map +1 -1
  66. package/esm/server/execute-page-request.types.d.mts +10 -1
  67. package/esm/server/fold-layout-loaders.mjs +36 -0
  68. package/esm/server/fold-layout-loaders.mjs.map +1 -0
  69. package/esm/server/hydration-client-url.mjs +2 -2
  70. package/esm/server/hydration-client-url.mjs.map +1 -1
  71. package/esm/server/index.d.mts +2 -2
  72. package/esm/server/index.mjs +2 -2
  73. package/esm/server/install-page-routes-from-manifest.d.mts +1 -1
  74. package/esm/server/install-page-routes-from-manifest.mjs +43 -40
  75. package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
  76. package/esm/server/install-page-routes.d.mts +22 -2
  77. package/esm/server/install-page-routes.mjs +108 -42
  78. package/esm/server/install-page-routes.mjs.map +1 -1
  79. package/esm/server/install-production-page-routes.mjs.map +1 -1
  80. package/esm/server/match-page-route.mjs.map +1 -1
  81. package/esm/server/page-file-change.mjs.map +1 -1
  82. package/esm/server/page-route-reload.mjs +4 -3
  83. package/esm/server/page-route-reload.mjs.map +1 -1
  84. package/esm/server/register-production-public-files.mjs +25 -1
  85. package/esm/server/register-production-public-files.mjs.map +1 -1
  86. package/esm/server/render-page.d.mts +11 -48
  87. package/esm/server/render-page.mjs +13 -55
  88. package/esm/server/render-page.mjs.map +1 -1
  89. package/esm/server/resolve-page-metadata.mjs.map +1 -1
  90. package/esm/server/resolve-route-validation-input.mjs +11 -0
  91. package/esm/server/resolve-route-validation-input.mjs.map +1 -0
  92. package/esm/server/route-validation-error.mjs +32 -0
  93. package/esm/server/route-validation-error.mjs.map +1 -0
  94. package/esm/server/settle-page-response.mjs +5 -3
  95. package/esm/server/settle-page-response.mjs.map +1 -1
  96. package/esm/server/unregistered-pages.mjs +2 -1
  97. package/esm/server/unregistered-pages.mjs.map +1 -1
  98. package/esm/server/web-connector-factory.mjs +1 -1
  99. package/esm/server/web-connector-factory.mjs.map +1 -1
  100. package/esm/server/web-connector.mjs +24 -321
  101. package/esm/server/web-connector.mjs.map +1 -1
  102. package/esm/shared/module-key.mjs +15 -0
  103. package/esm/shared/module-key.mjs.map +1 -0
  104. package/esm/shared/to-posix.mjs +13 -0
  105. package/esm/shared/to-posix.mjs.map +1 -0
  106. package/esm/shared.mjs +24 -0
  107. package/esm/shared.mjs.map +1 -1
  108. package/esm/vite/build-client.mjs.map +1 -1
  109. package/esm/vite/dev-server-config.mjs +240 -0
  110. package/esm/vite/dev-server-config.mjs.map +1 -0
  111. package/esm/vite/gate-a-resolve.d.mts +5 -4
  112. package/esm/vite/gate-a-resolve.mjs +31 -70
  113. package/esm/vite/gate-a-resolve.mjs.map +1 -1
  114. package/esm/vite/gate-b-secrets.mjs.map +1 -1
  115. package/esm/vite/gate-c-verify.d.mts +1 -1
  116. package/esm/vite/gate-c-verify.mjs +1 -1
  117. package/esm/vite/gate-c-verify.mjs.map +1 -1
  118. package/esm/vite/hydration-entries.mjs +5 -7
  119. package/esm/vite/hydration-entries.mjs.map +1 -1
  120. package/esm/vite/index.d.mts +1 -1
  121. package/esm/vite/index.mjs +4 -110
  122. package/esm/vite/index.mjs.map +1 -1
  123. package/esm/vite/page-registry-plugin.mjs +9 -26
  124. package/esm/vite/page-registry-plugin.mjs.map +1 -1
  125. package/esm/vite/projection.mjs.map +1 -1
  126. package/esm/vite/react-refresh-preamble.mjs +90 -0
  127. package/esm/vite/react-refresh-preamble.mjs.map +1 -0
  128. package/esm/vite/ssr-client-view.mjs +135 -0
  129. package/esm/vite/ssr-client-view.mjs.map +1 -0
  130. package/llms-full.txt +558 -482
  131. package/llms.txt +2 -2
  132. package/package.json +6 -6
  133. package/skills/create-a-page/SKILL.md +348 -295
  134. package/skills/navigate-on-the-client/SKILL.md +212 -189
  135. package/esm/hydration/index.mjs.map +0 -1
  136. package/esm/runtime/register-modules.mjs.map +0 -1
  137. package/esm/server/dev-server.mjs.map +0 -1
  138. /package/esm/{hydration → entry}/index.d.mts +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"gate-c-verify.mjs","names":[],"sources":["../../../../../../../web/src/vite/gate-c-verify.ts"],"sourcesContent":["/**\r\n * Gate C — emitted-output verification.\r\n *\r\n * Projection removes the six server exports before the client graph forms.\r\n * Gate A refuses forbidden import PATHS. Gate B refuses inline secret reads.\r\n * All three act BEFORE or DURING the build, on source or the module graph —\r\n * none of them ever looks at what actually came out the other end. Gate C\r\n * is that check: a build-time assertion on the EMITTED client bundle for\r\n * every page, verifying:\r\n *\r\n * 1. The emitted code contains none of the six server export names\r\n * (`route`, `middleware`, `validation`, `loader`, `metadata`, `prefix`) as a\r\n * top-level binding, exported or not — `findLeakedServerExports`.\r\n * 2. The emitted module graph (Rollup's `OutputBundle`, as seen in\r\n * `generateBundle`) contains no import edge into a\r\n * `warlock.environment: \"server\"` (or absent-defaulting-to-server)\r\n * package — re-derived from the exact classifier Gate A uses\r\n * (`gate-a-resolve.ts`'s `createEnvironmentClassifier`), never a second,\r\n * independently-drifting classification scheme — `findLeakedServerImportEdges`.\r\n *\r\n * This is defense in depth: if projection or Gate A has a bug that lets\r\n * something through, Gate C is what turns \"shipped a leak\" into \"build\r\n * fails.\" Both check functions are exported as PURE functions over a bundle\r\n * object precisely so a test can construct a bundle where projection/Gate A\r\n * are bypassed entirely (a hand-built leaked chunk, never produced by a real\r\n * pipeline run) and still prove Gate C catches it independently — re-running\r\n * the D.1-D.5 happy-path fixtures through the composed pipeline only proves\r\n * the happy path, never that Gate C itself has teeth.\r\n *\r\n * Gate C also emits the inlined-`PUBLIC_*`-value manifest — see\r\n * `buildPublicEnvManifest` below — and is the only\r\n * one of the three gates that runs exclusively at `generateBundle` time: it\r\n * has nothing to say about source, only about output.\r\n */\r\nimport { parse } from \"@babel/parser\";\r\nimport type { Plugin } from \"vite\";\r\nimport {\r\n createEnvironmentClassifier,\r\n type EnvironmentClassifier,\r\n type EnvironmentClassifierOptions,\r\n} from \"./gate-a-resolve\";\r\nimport { createPublicEnvTracker, type PublicEnvTracker } from \"./gate-b-secrets\";\r\nimport { SERVER_EXPORT_NAMES } from \"./projection\";\r\n\r\nexport interface ServerExportLeak {\r\n fileName: string;\r\n exportName: string;\r\n line?: number;\r\n}\r\n\r\nexport interface ServerImportEdgeLeak {\r\n fileName: string;\r\n moduleId: string;\r\n packageName: string;\r\n}\r\n\r\nexport interface PublicEnvManifestEntry {\r\n key: string;\r\n /** `null` when `redacted` is true — see `isSafeToShowValue`. */\r\n value: string | null;\r\n redacted: boolean;\r\n}\r\n\r\n/**\r\n * A structurally-minimal view of Rollup's `OutputBundle` — only the fields\r\n * Gate C actually reads. Deliberately NOT the real `OutputBundle`/`OutputChunk`\r\n * types: Part 1's own discipline requires proving Gate C catches a bundle\r\n * that a real pipeline could never produce (a hand-built leaked chunk), and\r\n * forcing every test fixture to satisfy Rollup's full chunk shape would\r\n * fight that requirement for no safety benefit — Vite's real `generateBundle`\r\n * hook still hands Gate C a real `OutputBundle`, which is a structural\r\n * superset of this.\r\n */\r\ntype BundleLike = Record<\r\n string,\r\n {\r\n type?: string;\r\n fileName?: string;\r\n code?: string;\r\n moduleIds?: readonly string[];\r\n }\r\n>;\r\n\r\n/**\r\n * Recursively collects every top-level statement's bound name(s), matching:\r\n * - `const route = ...` / `function loader() {}` (exported or not — the\r\n * check is on top-level BINDINGS, not top-level exports).\r\n * - `export const route = ...` / `export function loader() {}` (the\r\n * `ExportNamedDeclaration` wrapper form).\r\n * - `export { route }` (the bare re-export-specifier form Rollup sometimes\r\n * emits instead of inlining the declaration itself).\r\n */\r\nfunction collectServerExportNames(stmt: any): Array<{ name: string; line: number }> {\r\n const matches: Array<{ name: string; line: number }> = [];\r\n const line = stmt.loc?.start?.line as number | undefined;\r\n\r\n function record(name: string | undefined) {\r\n if (name && SERVER_EXPORT_NAMES.has(name)) matches.push({ name, line: line ?? 0 });\r\n }\r\n\r\n if (stmt.type === \"VariableDeclaration\") {\r\n for (const decl of stmt.declarations) {\r\n if (decl.id?.type === \"Identifier\") record(decl.id.name);\r\n }\r\n } else if (stmt.type === \"FunctionDeclaration\") {\r\n record(stmt.id?.name);\r\n } else if (stmt.type === \"ExportNamedDeclaration\") {\r\n if (stmt.declaration) matches.push(...collectServerExportNames(stmt.declaration));\r\n for (const specifier of stmt.specifiers ?? []) {\r\n record(specifier.exported?.name ?? specifier.exported?.value);\r\n }\r\n }\r\n\r\n return matches;\r\n}\r\n\r\n/**\r\n * Thrown when an emitted chunk cannot be parsed, which means Gate C could not\r\n * inspect it. A gate that skips what it cannot read reports \"no violation\r\n * found\" on precisely the input it failed to look at — the one input where\r\n * that answer is worthless. So an unreadable chunk fails the build instead.\r\n */\r\nexport class UnverifiableChunkError extends Error {\r\n readonly fileName: string;\r\n\r\n constructor(fileName: string, cause?: unknown) {\r\n super(\r\n [\r\n `Warlock stopped this build: a file in your client bundle could not be checked for server-only code.`,\r\n ``,\r\n `File: ${fileName}`,\r\n `Cause: this file could not be parsed as JavaScript, so the client/server boundary check could not be performed on it. Warlock cannot confirm that the server-only exports (route, middleware, validation, loader, metadata, prefix) were kept out of it.`,\r\n `Fix: the build is being stopped rather than passed, because a file that was never checked is not a file known to be safe. This emitted file is outside the JavaScript syntax Warlock can currently verify. Two things commonly put it there, and this error cannot tell which: the output uses syntax newer than the parser Warlock ships with, or a plugin or loader emitted non-standard syntax into the client bundle. Check the compatibility of whatever produced this file, then build again.`,\r\n ].join(\"\\n\"),\r\n );\r\n this.name = \"UnverifiableChunkError\";\r\n this.fileName = fileName;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\n/**\r\n * Part 1, item 1: parses each emitted chunk's ACTUAL code (never pre-transform\r\n * source) and looks for a top-level binding named one of the five server\r\n * exports. A parse failure on an emitted chunk FAILS the gate\r\n * (`UnverifiableChunkError`) — it is never skipped. Skipping would report the\r\n * bundle clean on the one chunk the gate did not actually inspect, which is a\r\n * safety check failing open; a build stopped on an unreadable chunk is\r\n * recoverable, a boundary silently unenforced is not.\r\n *\r\n * This SURVIVES real minification (pinned by the `gate-c-verify.spec.ts`\r\n * \"D.8\" describe block). A minifier (esbuild,\r\n * Vite's default) is only free to rename LOCAL bindings; the exported name\r\n * itself is part of the module's public interface and is never mangled — a\r\n * minified `export const route = ...` still emits `export { e as route }`,\r\n * with the local identifier renamed (`e`) but `route` intact as the specifier's\r\n * `exported` name, which is exactly the field `collectServerExportNames`\r\n * reads for the `ExportNamedDeclaration` specifier form. No name-independent\r\n * redesign needed here — verified against a real `build.minify: true` output,\r\n * not assumed.\r\n */\r\nexport function findLeakedServerExports(bundle: BundleLike): ServerExportLeak[] {\r\n const leaks: ServerExportLeak[] = [];\r\n\r\n for (const file of Object.values(bundle)) {\r\n if (!file || file.type !== \"chunk\" || typeof file.code !== \"string\") continue;\r\n\r\n let ast: any;\r\n try {\r\n ast = parse(file.code, { sourceType: \"module\", plugins: [\"typescript\", \"jsx\"] });\r\n } catch (error) {\r\n throw new UnverifiableChunkError(file.fileName ?? \"(unnamed chunk)\", error);\r\n }\r\n\r\n for (const stmt of ast.program.body as any[]) {\r\n for (const match of collectServerExportNames(stmt)) {\r\n leaks.push({ fileName: file.fileName as string, exportName: match.name, line: match.line });\r\n }\r\n }\r\n }\r\n\r\n return leaks;\r\n}\r\n\r\n/**\r\n * Part 1, item 2: walks every emitted chunk's `moduleIds` (the resolved,\r\n * absolute file paths of every source module Rollup actually bundled into\r\n * that chunk) and classifies each one via the SAME `EnvironmentClassifier`\r\n * Gate A's `resolveId` uses, re-derived from `gate-a-resolve.ts` rather than\r\n * hand-rolled a second time. A moduleId that maps to a governed-scope\r\n * package classified `\"server\"` is an import edge Gate A should already\r\n * have refused — if it's here anyway, the earlier gate has a bug.\r\n *\r\n * D.8 verdict: this SURVIVES real minification unconditionally, and for a\r\n * stronger reason than item 1 above — it never reads emitted code text or\r\n * identifier names at all. `moduleIds` is Rollup's own bundling metadata\r\n * (which resolved source files ended up in this chunk), untouched by\r\n * minification, which only rewrites code, not that metadata. Verified\r\n * against a real `build.minify: true` output in `gate-c-verify.spec.ts`.\r\n */\r\nexport function findLeakedServerImportEdges(\r\n bundle: BundleLike,\r\n classifier: Pick<EnvironmentClassifier, \"environmentOf\" | \"packageNameForFilePath\">,\r\n): ServerImportEdgeLeak[] {\r\n const leaks: ServerImportEdgeLeak[] = [];\r\n\r\n for (const file of Object.values(bundle)) {\r\n if (!file || file.type !== \"chunk\") continue;\r\n\r\n for (const moduleId of file.moduleIds ?? []) {\r\n const packageName = classifier.packageNameForFilePath(moduleId);\r\n if (!packageName) continue;\r\n if (classifier.environmentOf(packageName) === \"server\") {\r\n leaks.push({ fileName: file.fileName as string, moduleId, packageName });\r\n }\r\n }\r\n }\r\n\r\n return leaks;\r\n}\r\n\r\n/**\r\n * Conservative \"does this PUBLIC_* value look safe to print in the reviewable\r\n * manifest\" heuristic: if genuinely unsure, show the key only — never guess\r\n * that a value is safe. The whole point of this manifest is that the `PUBLIC_`\r\n * prefix rule alone is not trustworthy — someone can and will name an actual\r\n * secret `PUBLIC_STRIPE_KEY` — so a value that LOOKS like a credential is\r\n * redacted regardless of what its key is named. Non-string values (booleans,\r\n * numbers) are never secret-shaped and always shown.\r\n */\r\nconst CREDENTIALED_URL_RE = /:\\/\\/[^/\\s]+:[^/\\s@]+@/; // scheme://user:pass@host\r\nconst KNOWN_SECRET_PREFIX_RES = [\r\n /^sk_(live|test)_/i, // Stripe secret key (pk_ publishable is a different prefix)\r\n /^rk_(live|test)_/i, // Stripe restricted key\r\n /^AKIA[0-9A-Z]{12,}/, // AWS access key id\r\n /^gh[pousr]_[A-Za-z0-9]{20,}/, // GitHub personal/OAuth/user/server tokens\r\n /^glpat-[A-Za-z0-9_-]{20,}/, // GitLab personal access token\r\n /^xox[baprs]-[A-Za-z0-9-]{10,}/, // Slack tokens\r\n /^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT (3 base64url segments)\r\n];\r\n// A long opaque token made up only of base64url/hex-ish characters, with both\r\n// letters and digits, and no separators a human-authored public value (a\r\n// URL, a short id) would normally contain — conservatively treated as a\r\n// secret-shaped random token even though it might genuinely be safe.\r\nconst HIGH_ENTROPY_TOKEN_RE = /^[A-Za-z0-9+/_=-]{32,}$/;\r\n\r\nfunction isSafeToShowValue(value: unknown): boolean {\r\n if (typeof value !== \"string\" || value.length === 0) return true;\r\n if (CREDENTIALED_URL_RE.test(value)) return false;\r\n if (KNOWN_SECRET_PREFIX_RES.some((re) => re.test(value))) return false;\r\n if (HIGH_ENTROPY_TOKEN_RE.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value)) return false;\r\n return true;\r\n}\r\n\r\nfunction stringifyEnvValue(value: unknown): string {\r\n if (typeof value === \"string\") return value;\r\n return JSON.stringify(value) ?? \"undefined\";\r\n}\r\n\r\n/**\r\n * The enumerated, human-reviewable list of\r\n * every `PUBLIC_*` key actually inlined into the client bundle. Built\r\n * directly from `tracker.referencedKeys` — the exact same `Set` Gate B's own\r\n * `generateBundle` unread-key check (`gate-b-secrets.ts`) reads from — so\r\n * this manifest and that exclusion logic agree BY CONSTRUCTION: they are two\r\n * readers of one Set, not two independent recomputations of \"which keys were\r\n * read\" that could drift apart. A key only reaches `referencedKeys` once\r\n * `findViolation` in `gate-b-secrets.ts` has seen a statically-resolved\r\n * `import.meta.env.PUBLIC_X` read for it, which is also precisely the\r\n * condition under which Gate B allows its value to be inlined at all — an\r\n * unread key that somehow leaked in anyway is a Gate B `generateBundle`\r\n * BUILD FAILURE (see `gate-b-secrets.ts`), never silently listed here.\r\n */\r\nexport function buildPublicEnvManifest(tracker: PublicEnvTracker): PublicEnvManifestEntry[] {\r\n return [...tracker.referencedKeys]\r\n .sort()\r\n .map((key) => {\r\n const value = tracker.declaredEnv[key];\r\n const safe = isSafeToShowValue(value);\r\n return { key, value: safe ? stringifyEnvValue(value) : null, redacted: !safe };\r\n });\r\n}\r\n\r\nexport interface GateCOptions extends EnvironmentClassifierOptions {\r\n /**\r\n * Shared with `gateBSecrets({ tracker })` — required for the manifest to\r\n * reflect what THIS build's Gate B pass actually saw. Defaults to a\r\n * private, unshared tracker (always empty) if omitted, which is only ever\r\n * correct when Gate C runs standalone in a test.\r\n */\r\n tracker?: PublicEnvTracker;\r\n /** Defaults to `\"warlock-env-manifest.json\"` (Suki's suggested name). */\r\n manifestFileName?: string;\r\n}\r\n\r\n/**\r\n * The client-build Vite plugin. Runs only at `generateBundle` — Gate C has\r\n * nothing to say about source, only about the bundle Rollup actually wrote.\r\n * Skipped for the SSR/server build, same as Gate B (`gate-b-secrets.ts`):\r\n * a page's server exports are meant to survive in that build; only the\r\n * client build is judged.\r\n */\r\nexport function gateCVerify(options: GateCOptions = {}): Plugin {\r\n const classifier = createEnvironmentClassifier(options);\r\n const tracker = options.tracker ?? createPublicEnvTracker();\r\n const manifestFileName = options.manifestFileName ?? \"warlock-env-manifest.json\";\r\n\r\n return {\r\n name: \"warlock:gate-c-verify\",\r\n generateBundle(_outputOptions, bundle) {\r\n if (this.environment?.config?.consumer === \"server\") return;\r\n\r\n const exportLeak = findLeakedServerExports(bundle)[0];\r\n if (exportLeak) {\r\n this.error(\r\n [\r\n `Gate C refused a build: a server export survived into the emitted client bundle.`,\r\n ``,\r\n `File: ${exportLeak.fileName}${exportLeak.line ? `:${exportLeak.line}` : \"\"}`,\r\n `Export: ${exportLeak.exportName}`,\r\n `Cause: \"${exportLeak.exportName}\" is one of the six server exports (route, middleware, validation, loader, metadata, prefix) and is still present as a top-level binding in the EMITTED client chunk — projection and/or Gate A should have removed or refused it before the bundle was written.`,\r\n `Fix: this should already be impossible if projection and Gate A ran correctly — investigate why \"${exportLeak.exportName}\" reached the emitted output (a projection bug, a build config that bypasses these plugins, or a plugin ordering change) rather than assuming this build is a one-off; Gate C is defense in depth, not the primary fence.`,\r\n ].join(\"\\n\"),\r\n );\r\n }\r\n\r\n const importEdgeLeak = findLeakedServerImportEdges(bundle, classifier)[0];\r\n if (importEdgeLeak) {\r\n this.error(\r\n [\r\n `Gate C refused a build: a server-only import edge survived into the emitted client bundle's module graph.`,\r\n ``,\r\n `File: ${importEdgeLeak.fileName}`,\r\n `Module: ${importEdgeLeak.moduleId}`,\r\n `Cause: \"${importEdgeLeak.moduleId}\" belongs to ${importEdgeLeak.packageName}, a server-only package (it declares \"warlock\": { \"environment\": \"server\" } in its package.json), and is present among the bundled modules of the emitted client chunk \"${importEdgeLeak.fileName}\" — Gate A's resolveId should have refused this import before it ever reached the bundle.`,\r\n `Fix: this should already be impossible if Gate A ran on this build — investigate why ${importEdgeLeak.packageName} reached the emitted output (a Gate A bypass, a custom resolveId/external override, or a plugin ordering change) rather than assuming this build is a one-off; Gate C is defense in depth, not the primary fence.`,\r\n ].join(\"\\n\"),\r\n );\r\n }\r\n\r\n const manifest = buildPublicEnvManifest(tracker);\r\n\r\n // EMITTED through `this.emitFile`, not written into `bundle` by hand.\r\n //\r\n // This used to assign a hand-built record directly:\r\n //\r\n // bundle[manifestFileName] = { type: \"asset\", fileName, name, source } as any;\r\n //\r\n // and the `as any` was load-bearing, which was the warning sign. A Rollup\r\n // asset record carries `names` and `originalFileNames` ARRAYS; that object\r\n // had neither, so it was not the shape Rollup produces — it merely\r\n // type-asserted its way into the bundle.\r\n //\r\n // Nothing noticed until the production build got far enough to render\r\n // chunks, at which point Vite's own `vite:manifest` plugin read\r\n // `chunk.names.length` on every asset and died on `undefined`:\r\n //\r\n // [vite:manifest] Cannot read properties of undefined (reading 'length')\r\n //\r\n // `emitFile` makes Rollup construct the record, so the shape is correct by\r\n // construction and stays correct when Rollup adds fields. Hand-building a\r\n // bundle entry is signing up to track someone else's internal type forever.\r\n this.emitFile({\r\n type: \"asset\",\r\n fileName: manifestFileName,\r\n source: JSON.stringify(manifest, null, 2),\r\n });\r\n },\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,SAAS,yBAAyB,MAAkD;CAClF,MAAM,UAAiD,CAAC;CACxD,MAAM,OAAO,KAAK,KAAK,OAAO;CAE9B,SAAS,OAAO,MAA0B;EACxC,IAAI,QAAQ,oBAAoB,IAAI,IAAI,GAAG,QAAQ,KAAK;GAAE;GAAM,MAAM,QAAQ;EAAE,CAAC;CACnF;CAEA,IAAI,KAAK,SAAS,uBAChB;OAAK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MAAM,aAAa,4BAA4B,OAAO;CACtD,MAAM,UAAU,QAAQ,WAAW,uBAAuB;CAC1D,MAAM,mBAAmB,QAAQ,oBAAoB;CAErD,OAAO;EACL,MAAM;EACN,eAAe,gBAAgB,QAAQ;GACrC,IAAI,KAAK,aAAa,QAAQ,aAAa,UAAU;GAErD,MAAM,aAAa,wBAAwB,MAAM,CAAC,CAAC;GACnD,IAAI,YACF,KAAK,MACH;IACE;IACA;IACA,SAAS,WAAW,WAAW,WAAW,OAAO,IAAI,WAAW,SAAS;IACzE,WAAW,WAAW;IACtB,WAAW,WAAW,WAAW;IACjC,oGAAoG,WAAW,WAAW;GAC5H,CAAC,CAAC,KAAK,IAAI,CACb;GAGF,MAAM,iBAAiB,4BAA4B,QAAQ,UAAU,CAAC,CAAC;GACvE,IAAI,gBACF,KAAK,MACH;IACE;IACA;IACA,SAAS,eAAe;IACxB,WAAW,eAAe;IAC1B,WAAW,eAAe,SAAS,eAAe,eAAe,YAAY,0KAA0K,eAAe,SAAS;IAC/Q,wFAAwF,eAAe,YAAY;GACrH,CAAC,CAAC,KAAK,IAAI,CACb;GAGF,MAAM,WAAW,uBAAuB,OAAO;GAsB/C,KAAK,SAAS;IACZ,MAAM;IACN,UAAU;IACV,QAAQ,KAAK,UAAU,UAAU,MAAM,CAAC;GAC1C,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"gate-c-verify.mjs","names":[],"sources":["../../../../../../../web/src/vite/gate-c-verify.ts"],"sourcesContent":["/**\r\n * Gate C — emitted-output verification.\r\n *\r\n * Projection removes the six server exports before the client graph forms.\r\n * Gate A refuses forbidden import PATHS. Gate B refuses inline secret reads.\r\n * All three act BEFORE or DURING the build, on source or the module graph —\r\n * none of them ever looks at what actually came out the other end. Gate C\r\n * is that check: a build-time assertion on the EMITTED client bundle for\r\n * every page, verifying:\r\n *\r\n * 1. The emitted code contains none of the six server export names\r\n * (`route`, `middleware`, `validation`, `loader`, `metadata`, `prefix`) as a\r\n * top-level binding, exported or not — `findLeakedServerExports`.\r\n * 2. The emitted module graph (Rollup's `OutputBundle`, as seen in\r\n * `generateBundle`) contains no import edge into a\r\n * `warlock.environment: \"server\"` (or absent-defaulting-to-server)\r\n * package — re-derived from the exact classifier Gate A uses\r\n * (`gate-a-resolve.ts`'s `createEnvironmentClassifier`), never a second,\r\n * independently-drifting classification scheme — `findLeakedServerImportEdges`.\r\n *\r\n * This is defense in depth: if projection or Gate A has a bug that lets\r\n * something through, Gate C is what turns \"shipped a leak\" into \"build\r\n * fails.\" Both check functions are exported as PURE functions over a bundle\r\n * object precisely so a test can construct a bundle where projection/Gate A\r\n * are bypassed entirely (a hand-built leaked chunk, never produced by a real\r\n * pipeline run) and still prove Gate C catches it independently — re-running\r\n * the D.1-D.5 happy-path fixtures through the composed pipeline only proves\r\n * the happy path, never that Gate C itself has teeth.\r\n *\r\n * Gate C also emits the inlined-`PUBLIC_*`-value manifest — see\r\n * `buildPublicEnvManifest` below — and is the only\r\n * one of the three gates that runs exclusively at `generateBundle` time: it\r\n * has nothing to say about source, only about output.\r\n */\r\nimport { parse } from \"@babel/parser\";\r\nimport type { Plugin } from \"vite\";\r\nimport {\r\n createEnvironmentClassifier,\r\n type EnvironmentClassifier,\r\n type EnvironmentClassifierOptions,\r\n} from \"./gate-a-resolve\";\r\nimport { createPublicEnvTracker, type PublicEnvTracker } from \"./gate-b-secrets\";\r\nimport { SERVER_EXPORT_NAMES } from \"./projection\";\r\n\r\nexport interface ServerExportLeak {\r\n fileName: string;\r\n exportName: string;\r\n line?: number;\r\n}\r\n\r\nexport interface ServerImportEdgeLeak {\r\n fileName: string;\r\n moduleId: string;\r\n packageName: string;\r\n}\r\n\r\nexport interface PublicEnvManifestEntry {\r\n key: string;\r\n /** `null` when `redacted` is true — see `isSafeToShowValue`. */\r\n value: string | null;\r\n redacted: boolean;\r\n}\r\n\r\n/**\r\n * A structurally-minimal view of Rollup's `OutputBundle` — only the fields\r\n * Gate C actually reads. Deliberately NOT the real `OutputBundle`/`OutputChunk`\r\n * types: Part 1's own discipline requires proving Gate C catches a bundle\r\n * that a real pipeline could never produce (a hand-built leaked chunk), and\r\n * forcing every test fixture to satisfy Rollup's full chunk shape would\r\n * fight that requirement for no safety benefit — Vite's real `generateBundle`\r\n * hook still hands Gate C a real `OutputBundle`, which is a structural\r\n * superset of this.\r\n */\r\ntype BundleLike = Record<\r\n string,\r\n {\r\n type?: string;\r\n fileName?: string;\r\n code?: string;\r\n moduleIds?: readonly string[];\r\n }\r\n>;\r\n\r\n/**\r\n * Recursively collects every top-level statement's bound name(s), matching:\r\n * - `const route = ...` / `function loader() {}` (exported or not — the\r\n * check is on top-level BINDINGS, not top-level exports).\r\n * - `export const route = ...` / `export function loader() {}` (the\r\n * `ExportNamedDeclaration` wrapper form).\r\n * - `export { route }` (the bare re-export-specifier form Rollup sometimes\r\n * emits instead of inlining the declaration itself).\r\n */\r\nfunction collectServerExportNames(stmt: any): Array<{ name: string; line: number }> {\r\n const matches: Array<{ name: string; line: number }> = [];\r\n const line = stmt.loc?.start?.line as number | undefined;\r\n\r\n function record(name: string | undefined) {\r\n if (name && SERVER_EXPORT_NAMES.has(name)) matches.push({ name, line: line ?? 0 });\r\n }\r\n\r\n if (stmt.type === \"VariableDeclaration\") {\r\n for (const decl of stmt.declarations) {\r\n if (decl.id?.type === \"Identifier\") record(decl.id.name);\r\n }\r\n } else if (stmt.type === \"FunctionDeclaration\") {\r\n record(stmt.id?.name);\r\n } else if (stmt.type === \"ExportNamedDeclaration\") {\r\n if (stmt.declaration) matches.push(...collectServerExportNames(stmt.declaration));\r\n for (const specifier of stmt.specifiers ?? []) {\r\n record(specifier.exported?.name ?? specifier.exported?.value);\r\n }\r\n }\r\n\r\n return matches;\r\n}\r\n\r\n/**\r\n * Thrown when an emitted chunk cannot be parsed, which means Gate C could not\r\n * inspect it. A gate that skips what it cannot read reports \"no violation\r\n * found\" on precisely the input it failed to look at — the one input where\r\n * that answer is worthless. So an unreadable chunk fails the build instead.\r\n */\r\nexport class UnverifiableChunkError extends Error {\r\n readonly fileName: string;\r\n\r\n constructor(fileName: string, cause?: unknown) {\r\n super(\r\n [\r\n `Warlock stopped this build: a file in your client bundle could not be checked for server-only code.`,\r\n ``,\r\n `File: ${fileName}`,\r\n `Cause: this file could not be parsed as JavaScript, so the client/server boundary check could not be performed on it. Warlock cannot confirm that the server-only exports (route, middleware, validation, loader, metadata, prefix) were kept out of it.`,\r\n `Fix: the build is being stopped rather than passed, because a file that was never checked is not a file known to be safe. This emitted file is outside the JavaScript syntax Warlock can currently verify. Two things commonly put it there, and this error cannot tell which: the output uses syntax newer than the parser Warlock ships with, or a plugin or loader emitted non-standard syntax into the client bundle. Check the compatibility of whatever produced this file, then build again.`,\r\n ].join(\"\\n\"),\r\n );\r\n this.name = \"UnverifiableChunkError\";\r\n this.fileName = fileName;\r\n if (cause !== undefined) (this as { cause?: unknown }).cause = cause;\r\n }\r\n}\r\n\r\n/**\r\n * Part 1, item 1: parses each emitted chunk's ACTUAL code (never pre-transform\r\n * source) and looks for a top-level binding named one of the six server\r\n * exports. A parse failure on an emitted chunk FAILS the gate\r\n * (`UnverifiableChunkError`) — it is never skipped. Skipping would report the\r\n * bundle clean on the one chunk the gate did not actually inspect, which is a\r\n * safety check failing open; a build stopped on an unreadable chunk is\r\n * recoverable, a boundary silently unenforced is not.\r\n *\r\n * This SURVIVES real minification (pinned by the `gate-c-verify.spec.ts`\r\n * \"D.8\" describe block). A minifier (esbuild,\r\n * Vite's default) is only free to rename LOCAL bindings; the exported name\r\n * itself is part of the module's public interface and is never mangled — a\r\n * minified `export const route = ...` still emits `export { e as route }`,\r\n * with the local identifier renamed (`e`) but `route` intact as the specifier's\r\n * `exported` name, which is exactly the field `collectServerExportNames`\r\n * reads for the `ExportNamedDeclaration` specifier form. No name-independent\r\n * redesign needed here — verified against a real `build.minify: true` output,\r\n * not assumed.\r\n */\r\nexport function findLeakedServerExports(bundle: BundleLike): ServerExportLeak[] {\r\n const leaks: ServerExportLeak[] = [];\r\n\r\n for (const file of Object.values(bundle)) {\r\n if (!file || file.type !== \"chunk\" || typeof file.code !== \"string\") continue;\r\n\r\n let ast: any;\r\n try {\r\n ast = parse(file.code, { sourceType: \"module\", plugins: [\"typescript\", \"jsx\"] });\r\n } catch (error) {\r\n throw new UnverifiableChunkError(file.fileName ?? \"(unnamed chunk)\", error);\r\n }\r\n\r\n for (const stmt of ast.program.body as any[]) {\r\n for (const match of collectServerExportNames(stmt)) {\r\n leaks.push({ fileName: file.fileName as string, exportName: match.name, line: match.line });\r\n }\r\n }\r\n }\r\n\r\n return leaks;\r\n}\r\n\r\n/**\r\n * Part 1, item 2: walks every emitted chunk's `moduleIds` (the resolved,\r\n * absolute file paths of every source module Rollup actually bundled into\r\n * that chunk) and classifies each one via the SAME `EnvironmentClassifier`\r\n * Gate A's `resolveId` uses, re-derived from `gate-a-resolve.ts` rather than\r\n * hand-rolled a second time. A moduleId that maps to a governed-scope\r\n * package classified `\"server\"` is an import edge Gate A should already\r\n * have refused — if it's here anyway, the earlier gate has a bug.\r\n *\r\n * D.8 verdict: this SURVIVES real minification unconditionally, and for a\r\n * stronger reason than item 1 above — it never reads emitted code text or\r\n * identifier names at all. `moduleIds` is Rollup's own bundling metadata\r\n * (which resolved source files ended up in this chunk), untouched by\r\n * minification, which only rewrites code, not that metadata. Verified\r\n * against a real `build.minify: true` output in `gate-c-verify.spec.ts`.\r\n */\r\nexport function findLeakedServerImportEdges(\r\n bundle: BundleLike,\r\n classifier: Pick<EnvironmentClassifier, \"environmentOf\" | \"packageNameForFilePath\">,\r\n): ServerImportEdgeLeak[] {\r\n const leaks: ServerImportEdgeLeak[] = [];\r\n\r\n for (const file of Object.values(bundle)) {\r\n if (!file || file.type !== \"chunk\") continue;\r\n\r\n for (const moduleId of file.moduleIds ?? []) {\r\n const packageName = classifier.packageNameForFilePath(moduleId);\r\n if (!packageName) continue;\r\n if (classifier.environmentOf(packageName) === \"server\") {\r\n leaks.push({ fileName: file.fileName as string, moduleId, packageName });\r\n }\r\n }\r\n }\r\n\r\n return leaks;\r\n}\r\n\r\n/**\r\n * Conservative \"does this PUBLIC_* value look safe to print in the reviewable\r\n * manifest\" heuristic: if genuinely unsure, show the key only — never guess\r\n * that a value is safe. The whole point of this manifest is that the `PUBLIC_`\r\n * prefix rule alone is not trustworthy — someone can and will name an actual\r\n * secret `PUBLIC_STRIPE_KEY` — so a value that LOOKS like a credential is\r\n * redacted regardless of what its key is named. Non-string values (booleans,\r\n * numbers) are never secret-shaped and always shown.\r\n */\r\nconst CREDENTIALED_URL_RE = /:\\/\\/[^/\\s]+:[^/\\s@]+@/; // scheme://user:pass@host\r\nconst KNOWN_SECRET_PREFIX_RES = [\r\n /^sk_(live|test)_/i, // Stripe secret key (pk_ publishable is a different prefix)\r\n /^rk_(live|test)_/i, // Stripe restricted key\r\n /^AKIA[0-9A-Z]{12,}/, // AWS access key id\r\n /^gh[pousr]_[A-Za-z0-9]{20,}/, // GitHub personal/OAuth/user/server tokens\r\n /^glpat-[A-Za-z0-9_-]{20,}/, // GitLab personal access token\r\n /^xox[baprs]-[A-Za-z0-9-]{10,}/, // Slack tokens\r\n /^eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+$/, // JWT (3 base64url segments)\r\n];\r\n// A long opaque token made up only of base64url/hex-ish characters, with both\r\n// letters and digits, and no separators a human-authored public value (a\r\n// URL, a short id) would normally contain — conservatively treated as a\r\n// secret-shaped random token even though it might genuinely be safe.\r\nconst HIGH_ENTROPY_TOKEN_RE = /^[A-Za-z0-9+/_=-]{32,}$/;\r\n\r\nfunction isSafeToShowValue(value: unknown): boolean {\r\n if (typeof value !== \"string\" || value.length === 0) return true;\r\n if (CREDENTIALED_URL_RE.test(value)) return false;\r\n if (KNOWN_SECRET_PREFIX_RES.some((re) => re.test(value))) return false;\r\n if (HIGH_ENTROPY_TOKEN_RE.test(value) && /[0-9]/.test(value) && /[a-zA-Z]/.test(value))\r\n return false;\r\n return true;\r\n}\r\n\r\nfunction stringifyEnvValue(value: unknown): string {\r\n if (typeof value === \"string\") return value;\r\n return JSON.stringify(value) ?? \"undefined\";\r\n}\r\n\r\n/**\r\n * The enumerated, human-reviewable list of\r\n * every `PUBLIC_*` key actually inlined into the client bundle. Built\r\n * directly from `tracker.referencedKeys` — the exact same `Set` Gate B's own\r\n * `generateBundle` unread-key check (`gate-b-secrets.ts`) reads from — so\r\n * this manifest and that exclusion logic agree BY CONSTRUCTION: they are two\r\n * readers of one Set, not two independent recomputations of \"which keys were\r\n * read\" that could drift apart. A key only reaches `referencedKeys` once\r\n * `findViolation` in `gate-b-secrets.ts` has seen a statically-resolved\r\n * `import.meta.env.PUBLIC_X` read for it, which is also precisely the\r\n * condition under which Gate B allows its value to be inlined at all — an\r\n * unread key that somehow leaked in anyway is a Gate B `generateBundle`\r\n * BUILD FAILURE (see `gate-b-secrets.ts`), never silently listed here.\r\n */\r\nexport function buildPublicEnvManifest(tracker: PublicEnvTracker): PublicEnvManifestEntry[] {\r\n return [...tracker.referencedKeys].sort().map((key) => {\r\n const value = tracker.declaredEnv[key];\r\n const safe = isSafeToShowValue(value);\r\n return { key, value: safe ? stringifyEnvValue(value) : null, redacted: !safe };\r\n });\r\n}\r\n\r\nexport interface GateCOptions extends EnvironmentClassifierOptions {\r\n /**\r\n * Shared with `gateBSecrets({ tracker })` — required for the manifest to\r\n * reflect what THIS build's Gate B pass actually saw. Defaults to a\r\n * private, unshared tracker (always empty) if omitted, which is only ever\r\n * correct when Gate C runs standalone in a test.\r\n */\r\n tracker?: PublicEnvTracker;\r\n /** Defaults to `\"warlock-env-manifest.json\"` (Suki's suggested name). */\r\n manifestFileName?: string;\r\n}\r\n\r\n/**\r\n * The client-build Vite plugin. Runs only at `generateBundle` — Gate C has\r\n * nothing to say about source, only about the bundle Rollup actually wrote.\r\n * Skipped for the SSR/server build, same as Gate B (`gate-b-secrets.ts`):\r\n * a page's server exports are meant to survive in that build; only the\r\n * client build is judged.\r\n */\r\nexport function gateCVerify(options: GateCOptions = {}): Plugin {\r\n const classifier = createEnvironmentClassifier(options);\r\n const tracker = options.tracker ?? createPublicEnvTracker();\r\n const manifestFileName = options.manifestFileName ?? \"warlock-env-manifest.json\";\r\n\r\n return {\r\n name: \"warlock:gate-c-verify\",\r\n generateBundle(_outputOptions, bundle) {\r\n if (this.environment?.config?.consumer === \"server\") return;\r\n\r\n const exportLeak = findLeakedServerExports(bundle)[0];\r\n if (exportLeak) {\r\n this.error(\r\n [\r\n `Gate C refused a build: a server export survived into the emitted client bundle.`,\r\n ``,\r\n `File: ${exportLeak.fileName}${exportLeak.line ? `:${exportLeak.line}` : \"\"}`,\r\n `Export: ${exportLeak.exportName}`,\r\n `Cause: \"${exportLeak.exportName}\" is one of the six server exports (route, middleware, validation, loader, metadata, prefix) and is still present as a top-level binding in the EMITTED client chunk — projection and/or Gate A should have removed or refused it before the bundle was written.`,\r\n `Fix: this should already be impossible if projection and Gate A ran correctly — investigate why \"${exportLeak.exportName}\" reached the emitted output (a projection bug, a build config that bypasses these plugins, or a plugin ordering change) rather than assuming this build is a one-off; Gate C is defense in depth, not the primary fence.`,\r\n ].join(\"\\n\"),\r\n );\r\n }\r\n\r\n const importEdgeLeak = findLeakedServerImportEdges(bundle, classifier)[0];\r\n if (importEdgeLeak) {\r\n this.error(\r\n [\r\n `Gate C refused a build: a server-only import edge survived into the emitted client bundle's module graph.`,\r\n ``,\r\n `File: ${importEdgeLeak.fileName}`,\r\n `Module: ${importEdgeLeak.moduleId}`,\r\n `Cause: \"${importEdgeLeak.moduleId}\" belongs to ${importEdgeLeak.packageName}, a server-only package (it declares \"warlock\": { \"environment\": \"server\" } in its package.json), and is present among the bundled modules of the emitted client chunk \"${importEdgeLeak.fileName}\" — Gate A's resolveId should have refused this import before it ever reached the bundle.`,\r\n `Fix: this should already be impossible if Gate A ran on this build — investigate why ${importEdgeLeak.packageName} reached the emitted output (a Gate A bypass, a custom resolveId/external override, or a plugin ordering change) rather than assuming this build is a one-off; Gate C is defense in depth, not the primary fence.`,\r\n ].join(\"\\n\"),\r\n );\r\n }\r\n\r\n const manifest = buildPublicEnvManifest(tracker);\r\n\r\n // EMITTED through `this.emitFile`, not written into `bundle` by hand.\r\n //\r\n // This used to assign a hand-built record directly:\r\n //\r\n // bundle[manifestFileName] = { type: \"asset\", fileName, name, source } as any;\r\n //\r\n // and the `as any` was load-bearing, which was the warning sign. A Rollup\r\n // asset record carries `names` and `originalFileNames` ARRAYS; that object\r\n // had neither, so it was not the shape Rollup produces — it merely\r\n // type-asserted its way into the bundle.\r\n //\r\n // Nothing noticed until the production build got far enough to render\r\n // chunks, at which point Vite's own `vite:manifest` plugin read\r\n // `chunk.names.length` on every asset and died on `undefined`:\r\n //\r\n // [vite:manifest] Cannot read properties of undefined (reading 'length')\r\n //\r\n // `emitFile` makes Rollup construct the record, so the shape is correct by\r\n // construction and stays correct when Rollup adds fields. Hand-building a\r\n // bundle entry is signing up to track someone else's internal type forever.\r\n this.emitFile({\r\n type: \"asset\",\r\n fileName: manifestFileName,\r\n source: JSON.stringify(manifest, null, 2),\r\n });\r\n },\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,SAAS,yBAAyB,MAAkD;CAClF,MAAM,UAAiD,CAAC;CACxD,MAAM,OAAO,KAAK,KAAK,OAAO;CAE9B,SAAS,OAAO,MAA0B;EACxC,IAAI,QAAQ,oBAAoB,IAAI,IAAI,GAAG,QAAQ,KAAK;GAAE;GAAM,MAAM,QAAQ;EAAE,CAAC;CACnF;CAEA,IAAI,KAAK,SAAS,uBAChB;OAAK,MAAM,QAAQ,KAAK,cACtB,IAAI,KAAK,IAAI,SAAS,cAAc,OAAO,KAAK,GAAG,IAAI;CACzD,OACK,IAAI,KAAK,SAAS,uBACvB,OAAO,KAAK,IAAI,IAAI;MACf,IAAI,KAAK,SAAS,0BAA0B;EACjD,IAAI,KAAK,aAAa,QAAQ,KAAK,GA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wBAAwB,MAAM,CAAC,CAAC;GACnD,IAAI,YACF,KAAK,MACH;IACE;IACA;IACA,SAAS,WAAW,WAAW,WAAW,OAAO,IAAI,WAAW,SAAS;IACzE,WAAW,WAAW;IACtB,WAAW,WAAW,WAAW;IACjC,oGAAoG,WAAW,WAAW;GAC5H,CAAC,CAAC,KAAK,IAAI,CACb;GAGF,MAAM,iBAAiB,4BAA4B,QAAQ,UAAU,CAAC,CAAC;GACvE,IAAI,gBACF,KAAK,MACH;IACE;IACA;IACA,SAAS,eAAe;IACxB,WAAW,eAAe;IAC1B,WAAW,eAAe,SAAS,eAAe,eAAe,YAAY,0KAA0K,eAAe,SAAS;IAC/Q,wFAAwF,eAAe,YAAY;GACrH,CAAC,CAAC,KAAK,IAAI,CACb;GAGF,MAAM,WAAW,uBAAuB,OAAO;GAsB/C,KAAK,SAAS;IACZ,MAAM;IACN,UAAU;IACV,QAAQ,KAAK,UAAU,UAAU,MAAM,CAAC;GAC1C,CAAC;EACH;CACF;AACF"}
@@ -1,12 +1,10 @@
1
+ import { toPosix } from "../shared/to-posix.mjs";
1
2
  import { existsSync } from "node:fs";
2
3
  import path from "node:path";
3
4
 
4
5
  //#region ../web/src/vite/hydration-entries.ts
5
6
  /** Stable Rollup/Vite entry name shared by development and production wiring. */
6
7
  const HYDRATION_CLIENT_ENTRY_NAME = "hydration";
7
- function normalizeFileSystemPath(filePath) {
8
- return filePath.replace(/\\/g, "/");
9
- }
10
8
  /**
11
9
  * Where the hydration entry lives inside an INSTALLED `@warlock.js/web`, and
12
10
  * where it lives inside this checkout — in that order of preference.
@@ -16,7 +14,7 @@ function normalizeFileSystemPath(filePath) {
16
14
  * `@warlock.js/web@5.0.2`: 191 files, none under `src/`. Note the published
17
15
  * `package.json` carries no `files` key at all; the release tooling rewrites
18
16
  * the manifest, so do not treat this repo's `files` field as the mechanism.)
19
- * Resolving the entry to `<webRoot>/src/hydration/index.ts` unconditionally
17
+ * Resolving the entry to `<webRoot>/src/entry/index.ts` unconditionally
20
18
  * therefore worked in this monorepo and failed for every consumer, with
21
19
  * `warlock build` unable to emit a client bundle at all.
22
20
  *
@@ -26,8 +24,8 @@ function normalizeFileSystemPath(filePath) {
26
24
  * through `esm/`, the hydration entry's relative imports through `src/`.
27
25
  * `publishRouteTable()` would write to one and `<Link>` would read the other.
28
26
  */
29
- const PACKAGED_ENTRY = "esm/hydration/index.mjs";
30
- const CHECKOUT_ENTRY = "src/hydration/index.ts";
27
+ const PACKAGED_ENTRY = "esm/entry/index.mjs";
28
+ const CHECKOUT_ENTRY = "src/entry/index.ts";
31
29
  /**
32
30
  * Describes the single framework hydration entry without importing Vite.
33
31
  * Vite's `/@fs/` prefix accepts an absolute normalized file-system path;
@@ -36,7 +34,7 @@ const CHECKOUT_ENTRY = "src/hydration/index.ts";
36
34
  function createHydrationClientEntry(webRoot) {
37
35
  if (typeof webRoot !== "string" || webRoot.trim().length === 0) throw new TypeError("Cannot create the hydration client entry: webRoot must be a non-empty path.");
38
36
  const packagedPath = path.resolve(webRoot, PACKAGED_ENTRY);
39
- const sourcePath = normalizeFileSystemPath(existsSync(packagedPath) ? packagedPath : path.resolve(webRoot, CHECKOUT_ENTRY));
37
+ const sourcePath = toPosix(existsSync(packagedPath) ? packagedPath : path.resolve(webRoot, CHECKOUT_ENTRY));
40
38
  return {
41
39
  name: HYDRATION_CLIENT_ENTRY_NAME,
42
40
  sourcePath,
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-entries.mjs","names":[],"sources":["../../../../../../../web/src/vite/hydration-entries.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** Stable Rollup/Vite entry name shared by development and production wiring. */\nexport const HYDRATION_CLIENT_ENTRY_NAME = \"hydration\";\n\nexport type HydrationClientEntry = Readonly<{\n name: typeof HYDRATION_CLIENT_ENTRY_NAME;\n sourcePath: string;\n devUrl: string;\n}>;\n\nfunction normalizeFileSystemPath(filePath: string): string {\n return filePath.replace(/\\\\/g, \"/\");\n}\n\n/**\n * Where the hydration entry lives inside an INSTALLED `@warlock.js/web`, and\n * where it lives inside this checkout — in that order of preference.\n *\n * The published tarball ships `esm/`, `skills/` and the docs files — no `src/`\n * — so `src/` is absent from every real install. (Verified against\n * `@warlock.js/web@5.0.2`: 191 files, none under `src/`. Note the published\n * `package.json` carries no `files` key at all; the release tooling rewrites\n * the manifest, so do not treat this repo's `files` field as the mechanism.)\n * Resolving the entry to `<webRoot>/src/hydration/index.ts` unconditionally\n * therefore worked in this monorepo and failed for every consumer, with\n * `warlock build` unable to emit a client bundle at all.\n *\n * The built artifact is preferred rather than the source being published,\n * because shipping `src/` beside `esm/` would put TWO instances of\n * `routing/route-table` in one client bundle — the app's own imports resolve\n * through `esm/`, the hydration entry's relative imports through `src/`.\n * `publishRouteTable()` would write to one and `<Link>` would read the other.\n */\nconst PACKAGED_ENTRY = \"esm/hydration/index.mjs\";\nconst CHECKOUT_ENTRY = \"src/hydration/index.ts\";\n\n/**\n * Describes the single framework hydration entry without importing Vite.\n * Vite's `/@fs/` prefix accepts an absolute normalized file-system path;\n * keeping the drive colon produces `/@fs/D:/...` consistently on Windows.\n */\nexport function createHydrationClientEntry(webRoot: string): HydrationClientEntry {\n if (typeof webRoot !== \"string\" || webRoot.trim().length === 0) {\n throw new TypeError(\"Cannot create the hydration client entry: webRoot must be a non-empty path.\");\n }\n\n const packagedPath = path.resolve(webRoot, PACKAGED_ENTRY);\n const sourcePath = normalizeFileSystemPath(\n existsSync(packagedPath) ? packagedPath : path.resolve(webRoot, CHECKOUT_ENTRY),\n );\n\n return {\n name: HYDRATION_CLIENT_ENTRY_NAME,\n sourcePath,\n devUrl: `/@fs/${sourcePath}`,\n };\n}\n"],"mappings":";;;;;AAIA,MAAa,8BAA8B;AAQ3C,SAAS,wBAAwB,UAA0B;CACzD,OAAO,SAAS,QAAQ,OAAO,GAAG;AACpC;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;;;;;;AAOvB,SAAgB,2BAA2B,SAAuC;CAChF,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,CAAC,CAAC,WAAW,GAC3D,MAAM,IAAI,UAAU,6EAA6E;CAGnG,MAAM,eAAe,KAAK,QAAQ,SAAS,cAAc;CACzD,MAAM,aAAa,wBACjB,WAAW,YAAY,IAAI,eAAe,KAAK,QAAQ,SAAS,cAAc,CAChF;CAEA,OAAO;EACL,MAAM;EACN;EACA,QAAQ,QAAQ;CAClB;AACF"}
1
+ {"version":3,"file":"hydration-entries.mjs","names":[],"sources":["../../../../../../../web/src/vite/hydration-entries.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { toPosix } from \"../shared/to-posix\";\n\n/** Stable Rollup/Vite entry name shared by development and production wiring. */\nexport const HYDRATION_CLIENT_ENTRY_NAME = \"hydration\";\n\nexport type HydrationClientEntry = Readonly<{\n name: typeof HYDRATION_CLIENT_ENTRY_NAME;\n sourcePath: string;\n devUrl: string;\n}>;\n\n/**\n * Where the hydration entry lives inside an INSTALLED `@warlock.js/web`, and\n * where it lives inside this checkout — in that order of preference.\n *\n * The published tarball ships `esm/`, `skills/` and the docs files — no `src/`\n * — so `src/` is absent from every real install. (Verified against\n * `@warlock.js/web@5.0.2`: 191 files, none under `src/`. Note the published\n * `package.json` carries no `files` key at all; the release tooling rewrites\n * the manifest, so do not treat this repo's `files` field as the mechanism.)\n * Resolving the entry to `<webRoot>/src/entry/index.ts` unconditionally\n * therefore worked in this monorepo and failed for every consumer, with\n * `warlock build` unable to emit a client bundle at all.\n *\n * The built artifact is preferred rather than the source being published,\n * because shipping `src/` beside `esm/` would put TWO instances of\n * `routing/route-table` in one client bundle — the app's own imports resolve\n * through `esm/`, the hydration entry's relative imports through `src/`.\n * `publishRouteTable()` would write to one and `<Link>` would read the other.\n */\nconst PACKAGED_ENTRY = \"esm/entry/index.mjs\";\nconst CHECKOUT_ENTRY = \"src/entry/index.ts\";\n\n/**\n * Describes the single framework hydration entry without importing Vite.\n * Vite's `/@fs/` prefix accepts an absolute normalized file-system path;\n * keeping the drive colon produces `/@fs/D:/...` consistently on Windows.\n */\nexport function createHydrationClientEntry(webRoot: string): HydrationClientEntry {\n if (typeof webRoot !== \"string\" || webRoot.trim().length === 0) {\n throw new TypeError(\n \"Cannot create the hydration client entry: webRoot must be a non-empty path.\",\n );\n }\n\n const packagedPath = path.resolve(webRoot, PACKAGED_ENTRY);\n const sourcePath = toPosix(\n existsSync(packagedPath) ? packagedPath : path.resolve(webRoot, CHECKOUT_ENTRY),\n );\n\n return {\n name: HYDRATION_CLIENT_ENTRY_NAME,\n sourcePath,\n devUrl: `/@fs/${sourcePath}`,\n };\n}\n"],"mappings":";;;;;;AAKA,MAAa,8BAA8B;;;;;;;;;;;;;;;;;;;;AA2B3C,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;;;;;;AAOvB,SAAgB,2BAA2B,SAAuC;CAChF,IAAI,OAAO,YAAY,YAAY,QAAQ,KAAK,CAAC,CAAC,WAAW,GAC3D,MAAM,IAAI,UACR,6EACF;CAGF,MAAM,eAAe,KAAK,QAAQ,SAAS,cAAc;CACzD,MAAM,aAAa,QACjB,WAAW,YAAY,IAAI,eAAe,KAAK,QAAQ,SAAS,cAAc,CAChF;CAEA,OAAO;EACL,MAAM;EACN;EACA,QAAQ,QAAQ;CAClB;AACF"}
@@ -21,7 +21,7 @@ type BuildWarlockHydrationClientOptions = Readonly<{
21
21
  }>;
22
22
  /**
23
23
  * The composed client-build pipeline: projection
24
- * strips the 5 server exports first, THEN Gate B's `transform` checks
24
+ * strips the 6 server exports first, THEN Gate B's `transform` checks
25
25
  * whatever source remains for inline secret reads, THEN Gate A's
26
26
  * `resolveId` judges whatever imports remain. Array order here is
27
27
  * `[projection(), gateBSecrets(), gateAResolve()]` to match Vite's own
@@ -1,12 +1,12 @@
1
1
  import { HYDRATION_CLIENT_ENTRY_NAME, createHydrationClientEntry } from "./hydration-entries.mjs";
2
2
  import { buildHydrationClient } from "./build-client.mjs";
3
- import { gateAResolve, isAppSourcePath, isRecognizedUniversalSurface, isServerFile, isWithinModuleWebFolder } from "./gate-a-resolve.mjs";
3
+ import { gateAResolve } from "./gate-a-resolve.mjs";
4
4
  import { createPublicEnvTracker, gateBSecrets } from "./gate-b-secrets.mjs";
5
- import { ProjectionAmbiguityError, isProjectableFile, projectModule, projection } from "./projection.mjs";
5
+ import { ProjectionAmbiguityError, projection } from "./projection.mjs";
6
6
  import { buildPublicEnvManifest, findLeakedServerExports, findLeakedServerImportEdges, gateCVerify } from "./gate-c-verify.mjs";
7
7
  import { CLIENT_PAGE_REGISTRY_ID, RESOLVED_CLIENT_PAGE_REGISTRY_ID, clientPageRegistry, invalidateClientPageRegistry } from "./page-registry-plugin.mjs";
8
+ import { clientEnvironmentOnly } from "./ssr-client-view.mjs";
8
9
  import path from "node:path";
9
- import { parse } from "@babel/parser";
10
10
 
11
11
  //#region ../web/src/vite/index.ts
12
12
  /**
@@ -14,115 +14,9 @@ import { parse } from "@babel/parser";
14
14
  * runtime barrel (`@warlock.js/web`) so importing it never pulls `vite` into
15
15
  * a project that doesn't build with Vite.
16
16
  */
17
- function moduleKey(id) {
18
- return id.split("?")[0].replace(/\\/g, "/");
19
- }
20
- const CODE_MODULE_EXTENSION = /\.([cm]?[jt]sx?)$/;
21
- function isStatelessClientSurface(id, appRoot) {
22
- const bare = moduleKey(id);
23
- if (!isAppSourcePath(bare, appRoot)) return false;
24
- if (isServerFile(bare, appRoot)) return false;
25
- return isProjectableFile(bare) || isRecognizedUniversalSurface(bare) || isWithinModuleWebFolder(bare, appRoot);
26
- }
27
- function collectImportSpecifiers(code) {
28
- const ast = parse(code, {
29
- sourceType: "module",
30
- plugins: ["typescript", "jsx"]
31
- });
32
- const imports = /* @__PURE__ */ new Set();
33
- function walk(node) {
34
- if (!node || typeof node !== "object") return;
35
- if (Array.isArray(node)) {
36
- for (const child of node) walk(child);
37
- return;
38
- }
39
- const record = node;
40
- if ((record.type === "ImportDeclaration" || record.type === "ExportNamedDeclaration" || record.type === "ExportAllDeclaration") && record.source?.type === "StringLiteral") imports.add(record.source.value);
41
- if (record.type === "CallExpression" && record.callee?.type === "Import" && record.arguments?.[0]?.type === "StringLiteral") imports.add(record.arguments[0].value);
42
- if (record.type === "ImportExpression" && record.source?.type === "StringLiteral") imports.add(record.source.value);
43
- for (const [key, child] of Object.entries(record)) {
44
- if (key === "type" || key === "start" || key === "end" || key === "loc" || key === "range" || key.endsWith("Comments") || key === "extra") continue;
45
- walk(child);
46
- }
47
- }
48
- walk(ast.program);
49
- return imports;
50
- }
51
- function clientViewOf(state, code, id) {
52
- const key = moduleKey(id);
53
- if (!state.clientBoundModules.has(key) && !isStatelessClientSurface(key, state.appRoot)) return;
54
- state.clientBoundModules.add(key);
55
- if (!CODE_MODULE_EXTENSION.test(key)) {
56
- state.clientImportsByModule.set(key, /* @__PURE__ */ new Set());
57
- return code;
58
- }
59
- const clientCode = isProjectableFile(key) ? projectModule(code, key).code : code;
60
- state.clientImportsByModule.set(key, collectImportSpecifiers(clientCode));
61
- return clientCode;
62
- }
63
- function markResolvedClientModule(state, resolved) {
64
- if (!resolved) return;
65
- const id = typeof resolved === "string" ? resolved : resolved.id;
66
- if (!id.includes("\0")) state.clientBoundModules.add(moduleKey(id));
67
- }
68
- function isServerEnvironment(context) {
69
- return context.environment?.config.consumer === "server";
70
- }
71
- /**
72
- * Keeps the production/client pipeline byte-identical, while giving Gate A
73
- * and Gate B a validation-only view in Vite's development SSR environment.
74
- * SSR still evaluates the original source: only the gates receive the
75
- * projected client view, so loader/server exports retain their legitimate
76
- * server access while component-visible code is refused before evaluation.
77
- */
78
- function clientEnvironmentOnly(plugin, ssrState) {
79
- const validatesDevSsr = plugin.name === "warlock:gate-a-resolve" || plugin.name === "warlock:gate-b-secrets";
80
- const originalTransform = typeof plugin.transform === "function" ? plugin.transform : plugin.transform?.handler;
81
- const originalResolveId = typeof plugin.resolveId === "function" ? plugin.resolveId : plugin.resolveId?.handler;
82
- const originalBuildStart = typeof plugin.buildStart === "function" ? plugin.buildStart : plugin.buildStart?.handler;
83
- return {
84
- ...plugin,
85
- applyToEnvironment(environment) {
86
- return environment.config.consumer === "client" || validatesDevSsr && environment.config.consumer === "server";
87
- },
88
- buildStart: originalBuildStart ? function(...args) {
89
- if (isServerEnvironment(this)) return;
90
- return originalBuildStart.apply(this, args);
91
- } : void 0,
92
- transform: originalTransform ? async function(code, id, options) {
93
- if (!isServerEnvironment(this)) return originalTransform.call(this, code, id, options);
94
- const clientCode = clientViewOf(ssrState, code, id);
95
- if (clientCode === void 0) return null;
96
- const transformed = await originalTransform.call(this, clientCode, id, {
97
- ...options,
98
- ssr: false
99
- });
100
- if (plugin.name === "warlock:gate-a-resolve" && originalResolveId) for (const source of ssrState.clientImportsByModule.get(moduleKey(id)) ?? []) markResolvedClientModule(ssrState, await originalResolveId.call(this, source, id, {
101
- attributes: {},
102
- isEntry: false,
103
- ssr: false
104
- }));
105
- return transformed;
106
- } : void 0,
107
- resolveId: originalResolveId ? async function(source, importer, options) {
108
- if (!isServerEnvironment(this)) return originalResolveId.call(this, source, importer, options);
109
- if (!importer) return null;
110
- const importerKey = moduleKey(importer);
111
- if (!(ssrState.clientBoundModules.has(importerKey) || isStatelessClientSurface(importerKey, ssrState.appRoot))) return null;
112
- const survivingImports = ssrState.clientImportsByModule.get(importerKey);
113
- if (survivingImports && !survivingImports.has(source)) return null;
114
- const resolved = await originalResolveId.call(this, source, importer, {
115
- ...options,
116
- ssr: false
117
- });
118
- markResolvedClientModule(ssrState, resolved);
119
- return resolved;
120
- } : void 0
121
- };
122
- }
123
17
  /**
124
18
  * The composed client-build pipeline: projection
125
- * strips the 5 server exports first, THEN Gate B's `transform` checks
19
+ * strips the 6 server exports first, THEN Gate B's `transform` checks
126
20
  * whatever source remains for inline secret reads, THEN Gate A's
127
21
  * `resolveId` judges whatever imports remain. Array order here is
128
22
  * `[projection(), gateBSecrets(), gateAResolve()]` to match Vite's own
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../web/src/vite/index.ts"],"sourcesContent":["/**\n * `@warlock.js/web/vite` — build-tooling subpath, kept separate from the\n * runtime barrel (`@warlock.js/web`) so importing it never pulls `vite` into\n * a project that doesn't build with Vite.\n */\nimport { parse } from \"@babel/parser\";\nimport path from \"node:path\";\nimport type { Plugin } from \"vite\";\nimport {\n buildHydrationClient,\n type BuildHydrationClientOptions,\n type BuildHydrationClientResult,\n} from \"./build-client\";\nimport {\n gateAResolve,\n isAppSourcePath,\n isRecognizedUniversalSurface,\n isServerFile,\n isWithinModuleWebFolder,\n} from \"./gate-a-resolve\";\nimport { createPublicEnvTracker, gateBSecrets } from \"./gate-b-secrets\";\nimport { gateCVerify } from \"./gate-c-verify\";\nimport {\n clientPageRegistry,\n type ClientPageRegistryPluginOptions,\n} from \"./page-registry-plugin\";\nimport { isProjectableFile, projectModule, projection } from \"./projection\";\n\nexport { buildHydrationClient } from \"./build-client\";\nexport type {\n BuildHydrationClientOptions,\n BuildHydrationClientResult,\n HydrationClientBuildOutput,\n} from \"./build-client\";\nexport { gateAResolve } from \"./gate-a-resolve\";\nexport type {\n EnvironmentClassifier,\n EnvironmentClassifierOptions,\n WarlockEnvironment,\n} from \"./gate-a-resolve\";\nexport { createPublicEnvTracker, gateBSecrets } from \"./gate-b-secrets\";\nexport type { PublicEnvTracker } from \"./gate-b-secrets\";\nexport {\n buildPublicEnvManifest,\n findLeakedServerExports,\n findLeakedServerImportEdges,\n gateCVerify,\n} from \"./gate-c-verify\";\nexport type {\n GateCOptions,\n PublicEnvManifestEntry,\n ServerExportLeak,\n ServerImportEdgeLeak,\n} from \"./gate-c-verify\";\nexport {\n HYDRATION_CLIENT_ENTRY_NAME,\n createHydrationClientEntry,\n} from \"./hydration-entries\";\nexport type { HydrationClientEntry } from \"./hydration-entries\";\nexport {\n CLIENT_PAGE_REGISTRY_ID,\n clientPageRegistry,\n invalidateClientPageRegistry,\n RESOLVED_CLIENT_PAGE_REGISTRY_ID,\n} from \"./page-registry-plugin\";\nexport type { ClientPageRegistryPluginOptions } from \"./page-registry-plugin\";\nexport { projection, ProjectionAmbiguityError } from \"./projection\";\nexport type { ProjectionResult } from \"./projection\";\n\nexport type WarlockClientBoundaryOptions = Parameters<\n typeof gateAResolve\n>[0] & {\n beforePageHotUpdate?: ClientPageRegistryPluginOptions[\"beforePageHotUpdate\"];\n};\n\nexport type BuildWarlockHydrationClientOptions = Readonly<{\n appRoot: string;\n webRoot: string;\n /** Absolute client output dir — threaded to `buildHydrationClient` (`<outdir>/client`). */\n outDir: string;\n resolveAliases: BuildHydrationClientOptions[\"resolveAliases\"];\n external?: BuildHydrationClientOptions[\"external\"];\n /** App-configured plugins, appended after Warlock's client-boundary pipeline. */\n plugins?: BuildHydrationClientOptions[\"plugins\"];\n}>;\n\ntype SsrBoundaryState = {\n readonly appRoot: string;\n readonly clientBoundModules: Set<string>;\n readonly clientImportsByModule: Map<string, Set<string>>;\n};\n\nfunction moduleKey(id: string): string {\n return id.split(\"?\")[0].replace(/\\\\/g, \"/\");\n}\n\nconst CODE_MODULE_EXTENSION = /\\.([cm]?[jt]sx?)$/;\n\nfunction isStatelessClientSurface(id: string, appRoot: string): boolean {\n const bare = moduleKey(id);\n if (!isAppSourcePath(bare, appRoot)) return false;\n if (isServerFile(bare, appRoot)) return false;\n\n return (\n isProjectableFile(bare) ||\n isRecognizedUniversalSurface(bare) ||\n isWithinModuleWebFolder(bare, appRoot)\n );\n}\n\nfunction collectImportSpecifiers(code: string): Set<string> {\n const ast = parse(code, {\n sourceType: \"module\",\n plugins: [\"typescript\", \"jsx\"],\n });\n const imports = new Set<string>();\n\n function walk(node: unknown): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const child of node) walk(child);\n return;\n }\n\n const record = node as Record<string, any>;\n if (\n (record.type === \"ImportDeclaration\" ||\n record.type === \"ExportNamedDeclaration\" ||\n record.type === \"ExportAllDeclaration\") &&\n record.source?.type === \"StringLiteral\"\n ) {\n imports.add(record.source.value);\n }\n if (\n record.type === \"CallExpression\" &&\n record.callee?.type === \"Import\" &&\n record.arguments?.[0]?.type === \"StringLiteral\"\n ) {\n imports.add(record.arguments[0].value);\n }\n if (\n record.type === \"ImportExpression\" &&\n record.source?.type === \"StringLiteral\"\n ) {\n imports.add(record.source.value);\n }\n\n for (const [key, child] of Object.entries(record)) {\n if (\n key === \"type\" ||\n key === \"start\" ||\n key === \"end\" ||\n key === \"loc\" ||\n key === \"range\" ||\n key.endsWith(\"Comments\") ||\n key === \"extra\"\n ) {\n continue;\n }\n walk(child);\n }\n }\n\n walk(ast.program);\n return imports;\n}\n\nfunction clientViewOf(\n state: SsrBoundaryState,\n code: string,\n id: string,\n): string | undefined {\n const key = moduleKey(id);\n if (\n !state.clientBoundModules.has(key) &&\n !isStatelessClientSurface(key, state.appRoot)\n ) {\n return undefined;\n }\n\n state.clientBoundModules.add(key);\n if (!CODE_MODULE_EXTENSION.test(key)) {\n state.clientImportsByModule.set(key, new Set());\n return code;\n }\n\n const clientCode = isProjectableFile(key)\n ? projectModule(code, key).code\n : code;\n state.clientImportsByModule.set(key, collectImportSpecifiers(clientCode));\n return clientCode;\n}\n\nfunction markResolvedClientModule(\n state: SsrBoundaryState,\n resolved: { id: string } | string | null | false | void,\n): void {\n if (!resolved) return;\n const id = typeof resolved === \"string\" ? resolved : resolved.id;\n if (!id.includes(\"\\0\")) state.clientBoundModules.add(moduleKey(id));\n}\n\nfunction isServerEnvironment(context: {\n environment?: { config: { consumer?: string } };\n}): boolean {\n return context.environment?.config.consumer === \"server\";\n}\n\n/**\n * Keeps the production/client pipeline byte-identical, while giving Gate A\n * and Gate B a validation-only view in Vite's development SSR environment.\n * SSR still evaluates the original source: only the gates receive the\n * projected client view, so loader/server exports retain their legitimate\n * server access while component-visible code is refused before evaluation.\n */\nfunction clientEnvironmentOnly(\n plugin: Plugin,\n ssrState: SsrBoundaryState,\n): Plugin {\n const validatesDevSsr =\n plugin.name === \"warlock:gate-a-resolve\" ||\n plugin.name === \"warlock:gate-b-secrets\";\n const originalTransform =\n typeof plugin.transform === \"function\"\n ? plugin.transform\n : plugin.transform?.handler;\n const originalResolveId =\n typeof plugin.resolveId === \"function\"\n ? plugin.resolveId\n : plugin.resolveId?.handler;\n const originalBuildStart =\n typeof plugin.buildStart === \"function\"\n ? plugin.buildStart\n : plugin.buildStart?.handler;\n\n return {\n ...plugin,\n applyToEnvironment(environment) {\n return (\n environment.config.consumer === \"client\" ||\n (validatesDevSsr && environment.config.consumer === \"server\")\n );\n },\n buildStart: originalBuildStart\n ? function (...args) {\n if (isServerEnvironment(this)) return;\n return originalBuildStart.apply(this, args);\n }\n : undefined,\n transform: originalTransform\n ? async function (code, id, options) {\n if (!isServerEnvironment(this)) {\n return originalTransform.call(this, code, id, options);\n }\n\n const clientCode = clientViewOf(ssrState, code, id);\n if (clientCode === undefined) return null;\n\n const transformed = await originalTransform.call(\n this,\n clientCode,\n id,\n {\n ...options,\n ssr: false,\n },\n );\n\n // Vite can externalize a package in the SSR environment before its\n // normal resolver walk offers that edge to a plugin. Gate A cannot\n // wait for that walk: validate every import that survived projection\n // now, while the original TypeScript source and importer are known.\n if (plugin.name === \"warlock:gate-a-resolve\" && originalResolveId) {\n for (const source of ssrState.clientImportsByModule.get(\n moduleKey(id),\n ) ?? []) {\n const resolved = await originalResolveId.call(this, source, id, {\n attributes: {},\n isEntry: false,\n ssr: false,\n });\n markResolvedClientModule(ssrState, resolved);\n }\n }\n\n return transformed;\n }\n : undefined,\n resolveId: originalResolveId\n ? async function (source, importer, options) {\n if (!isServerEnvironment(this)) {\n return originalResolveId.call(this, source, importer, options);\n }\n\n if (!importer) return null;\n const importerKey = moduleKey(importer);\n const isClientBound =\n ssrState.clientBoundModules.has(importerKey) ||\n isStatelessClientSurface(importerKey, ssrState.appRoot);\n if (!isClientBound) return null;\n\n const survivingImports =\n ssrState.clientImportsByModule.get(importerKey);\n if (survivingImports && !survivingImports.has(source)) return null;\n\n const resolved = await originalResolveId.call(\n this,\n source,\n importer,\n {\n ...options,\n ssr: false,\n },\n );\n markResolvedClientModule(ssrState, resolved);\n return resolved;\n }\n : undefined,\n };\n}\n\n/**\n * The composed client-build pipeline: projection\n * strips the 5 server exports first, THEN Gate B's `transform` checks\n * whatever source remains for inline secret reads, THEN Gate A's\n * `resolveId` judges whatever imports remain. Array order here is\n * `[projection(), gateBSecrets(), gateAResolve()]` to match Vite's own\n * pipeline shape (`transform` before `resolveId`), but array order alone\n * does not guarantee this — see the hook-ordering fact below, which is what\n * actually makes the composition correct.\n *\n * Empirically observed fact (via an instrumented real `vite.build()`, not\n * assumed from plugin array order): for a given module M, Vite/Rollup calls\n * `transform(M)` BEFORE it calls `resolveId` for any of M's own import\n * specifiers — because Rollup must parse M's post-transform source to even\n * discover which specifiers to resolve next. Concretely: `transform` ran on\n * `entry.page.tsx` first, and only after that did `resolveId(\"./dep\", ...)`\n * fire for the import statement still present in the transformed code. A\n * consequence follows directly: if projection's `transform` removes an\n * import statement from a page module entirely (e.g. `loader`'s\n * `@warlock.js/core` import, stripped because `loader` itself is removed),\n * `resolveId` is never invoked for that specifier at all — Gate A doesn't\n * \"let it pass\", it never sees it. Gate A's `resolveId` only fires for\n * imports that survive projection's `transform`, which is exactly why a\n * component-level `@warlock.js/core` import (never touched by projection)\n * still reaches and is refused by Gate A.\n *\n * This is OBSERVED Rollup behavior, not a documented contract — a future\n * Vite/Rollup upgrade could invert it. Pinned by a\n * regression test (`index.spec.ts`, \"D.3 hook ordering pin\") that fails\n * loudly if the ordering ever inverts, and by the `vite` peer floor in\n * `web/package.json` (`>=7.3.5`, the version this was verified against). If\n * that test ever fails after a Vite bump: the failure mode of the ordering\n * assumption breaking is SAFE — projection would stop removing an import\n * statement Gate A still sees, so Gate A would refuse an import it used to\n * silently let a stripped server export take with it. That is a loud build\n * failure (\"Gate A refused an import\"), never a silent client-bundle leak.\n * Do NOT \"fix\" an apparent Gate A false-positive after a Vite upgrade by\n * weakening Gate A (e.g. widening what it lets through) — investigate\n * whether this ordering assumption broke instead; loosening Gate A to work\n * around it would turn a loud failure into the exact silent leak this\n * pipeline exists to prevent.\n *\n * Gate B is placed between the two for the same reason, but for a `transform`\n * hook rather than `resolveId`: within a plugin array, Rollup runs each\n * module's registered `transform` hooks in array order, each one receiving\n * the PREVIOUS plugin's output. Running Gate B after projection means it\n * inspects the POST-projection source — a `process.env.SECRET` read inside\n * `loader` (a server export, legitimately reading a real secret server-side)\n * is invisible to Gate B once projection has already removed `loader`\n * entirely, exactly as it should be: Gate B's job is to fence client-bound\n * code, and projection is what decides what counts as client-bound. A\n * component-level secret read is untouched by projection and still reaches\n * Gate B, which refuses it. Gate B does not depend on Gate A's `resolveId`\n * output at all (orthogonal concern, raw source vs. import paths), so its\n * position relative to Gate A is not load-bearing — it is placed before Gate\n * A only to keep both `transform` hooks adjacent in the array.\n *\n * Gate C (`gate-c-verify.ts`) runs last and only at `generateBundle` — after\n * the entire `transform`/`resolveId` build phase has completed for every\n * plugin, regardless of array position (a Rollup lifecycle fact, not\n * something this array order enforces). It verifies the EMITTED output the\n * other three produced: no server export survived as a top-level binding, no\n * import edge into a server-only package survived into the module graph, and\n * it emits the reviewable `PUBLIC_*` inlined-value manifest. `gateBSecrets` and `gateCVerify` share\n * one `PublicEnvTracker` instance so the manifest and Gate B's own unread-key\n * exclusion check agree by construction, not by coincidence.\n *\n * `clientPageRegistry()` is FIRST, ahead of projection. It contributes no\n * `transform` at all — only a `resolveId`/`load` pair for one synthetic id —\n * so it cannot displace or pre-empt any gate's inspection of any real file.\n * Two reasons for the position, one of which is not load-bearing and is\n * labelled as such:\n *\n * 1. Load-bearing: it must own `virtual:warlock/pages` before Gate A's\n * `resolveId` (also `enforce: \"pre\"`) reaches its `this.resolve(...)` call\n * for that specifier. Gate A's nested resolve would find it anyway, but\n * routing the id through Gate A's importer-chain bookkeeping only to have\n * it come back means a synthetic id can surface in a user-facing \"Import\n * chain:\" message. Resolving it first keeps ownership of the id in one\n * place.\n * 2. NOT load-bearing: the position relative to `projection()`. Projection is\n * `enforce: \"pre\"` and selects by file BASENAME (`projection.ts:242-248`),\n * so it transforms every `*.page.tsx` / `layout.tsx` / `root.tsx` that\n * enters the graph regardless of who imported it or where this plugin sits.\n * The registry emits absolute POSIX specifiers that Rollup resolves and\n * loads as ORDINARY file modules — they are not inlined into the virtual\n * module — so each one is transformed exactly as a page imported from a\n * real file would be. Projection declines the virtual module itself\n * (`\\0virtual:warlock/pages` has no matching basename), which is correct:\n * generated code has no server exports to strip.\n *\n * Point 2 is asserted, not assumed, by a real `vite.build()` in\n * `page-registry-plugin.spec.ts`: a fixture page whose `loader` — and only its\n * `loader` — imports a marker module that Gate A independently PERMITS, built\n * through this exact array, with the marker proven absent from every emitted\n * chunk while the page's own component text is proven present. Inspecting this\n * array's order would prove nothing about what reaches the browser.\n */\nexport function warlockClientBoundary(\n options: WarlockClientBoundaryOptions = {},\n): Plugin[] {\n const tracker = createPublicEnvTracker();\n const ssrState: SsrBoundaryState = {\n appRoot: path.resolve(options.appRoot ?? process.cwd()),\n clientBoundModules: new Set(),\n clientImportsByModule: new Map(),\n };\n return [\n clientPageRegistry({\n appRoot: options.appRoot,\n beforePageHotUpdate: options.beforePageHotUpdate,\n }),\n projection(),\n gateBSecrets({ tracker }),\n gateAResolve(options),\n gateCVerify({ ...options, tracker }),\n ].map((plugin) => clientEnvironmentOnly(plugin, ssrState));\n}\n\n/**\n * Callable production seam: callers own their exact source aliases and the\n * app-root classification boundary, while this module owns the one canonical\n * projection/Gate B/Gate A/Gate C composition.\n */\nexport async function buildWarlockHydrationClient(\n options: BuildWarlockHydrationClientOptions,\n): Promise<BuildHydrationClientResult> {\n return buildHydrationClient({\n webRoot: options.webRoot,\n outDir: options.outDir,\n resolveAliases: options.resolveAliases,\n external: options.external,\n plugins: [\n ...warlockClientBoundary({ appRoot: options.appRoot }),\n ...(options.plugins ?? []),\n ],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA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ACd,UAAwC,CAAC,GAC/B;CACV,MAAM,UAAU,uBAAuB;CACvC,MAAM,WAA6B;EACjC,SAAS,KAAK,QAAQ,QAAQ,WAAW,QAAQ,IAAI,CAAC;EACtD,oCAAoB,IAAI,IAAI;EAC5B,uCAAuB,IAAI,IAAI;CACjC;CACA,OAAO;EACL,mBAAmB;GACjB,SAAS,QAAQ;GACjB,qBAAqB,QAAQ;EAC/B,CAAC;EACD,WAAW;EACX,aAAa,EAAE,QAAQ,CAAC;EACxB,aAAa,OAAO;EACpB,YAAY;GAAE,GAAG;GAAS;EAAQ,CAAC;CACrC,CAAC,CAAC,KAAK,WAAW,sBAAsB,QAAQ,QAAQ,CAAC;AAC3D;;;;;;AAOA,eAAsB,4BACpB,SACqC;CACrC,OAAO,qBAAqB;EAC1B,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,SAAS,CACP,GAAG,sBAAsB,EAAE,SAAS,QAAQ,QAAQ,CAAC,GACrD,GAAI,QAAQ,WAAW,CAAC,CAC1B;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../../../../../web/src/vite/index.ts"],"sourcesContent":["/**\r\n * `@warlock.js/web/vite` — build-tooling subpath, kept separate from the\r\n * runtime barrel (`@warlock.js/web`) so importing it never pulls `vite` into\r\n * a project that doesn't build with Vite.\r\n */\r\nimport path from \"node:path\";\r\nimport type { Plugin } from \"vite\";\r\nimport {\r\n buildHydrationClient,\r\n type BuildHydrationClientOptions,\r\n type BuildHydrationClientResult,\r\n} from \"./build-client\";\r\nimport { gateAResolve } from \"./gate-a-resolve\";\r\nimport { createPublicEnvTracker, gateBSecrets } from \"./gate-b-secrets\";\r\nimport { gateCVerify } from \"./gate-c-verify\";\r\nimport { clientPageRegistry, type ClientPageRegistryPluginOptions } from \"./page-registry-plugin\";\r\nimport { projection } from \"./projection\";\r\nimport { clientEnvironmentOnly, type SsrBoundaryState } from \"./ssr-client-view\";\r\n\r\nexport { buildHydrationClient } from \"./build-client\";\r\nexport type {\r\n BuildHydrationClientOptions,\r\n BuildHydrationClientResult,\r\n HydrationClientBuildOutput,\r\n} from \"./build-client\";\r\nexport { gateAResolve } from \"./gate-a-resolve\";\r\nexport type {\r\n EnvironmentClassifier,\r\n EnvironmentClassifierOptions,\r\n WarlockEnvironment,\r\n} from \"./gate-a-resolve\";\r\nexport { createPublicEnvTracker, gateBSecrets } from \"./gate-b-secrets\";\r\nexport type { PublicEnvTracker } from \"./gate-b-secrets\";\r\nexport {\r\n buildPublicEnvManifest,\r\n findLeakedServerExports,\r\n findLeakedServerImportEdges,\r\n gateCVerify,\r\n} from \"./gate-c-verify\";\r\nexport type {\r\n GateCOptions,\r\n PublicEnvManifestEntry,\r\n ServerExportLeak,\r\n ServerImportEdgeLeak,\r\n} from \"./gate-c-verify\";\r\nexport { HYDRATION_CLIENT_ENTRY_NAME, createHydrationClientEntry } from \"./hydration-entries\";\r\nexport type { HydrationClientEntry } from \"./hydration-entries\";\r\nexport {\r\n CLIENT_PAGE_REGISTRY_ID,\r\n clientPageRegistry,\r\n invalidateClientPageRegistry,\r\n RESOLVED_CLIENT_PAGE_REGISTRY_ID,\r\n} from \"./page-registry-plugin\";\r\nexport type { ClientPageRegistryPluginOptions } from \"./page-registry-plugin\";\r\nexport { projection, ProjectionAmbiguityError } from \"./projection\";\r\nexport type { ProjectionResult } from \"./projection\";\r\n\r\nexport type WarlockClientBoundaryOptions = Parameters<typeof gateAResolve>[0] & {\r\n beforePageHotUpdate?: ClientPageRegistryPluginOptions[\"beforePageHotUpdate\"];\r\n};\r\n\r\nexport type BuildWarlockHydrationClientOptions = Readonly<{\r\n appRoot: string;\r\n webRoot: string;\r\n /** Absolute client output dir — threaded to `buildHydrationClient` (`<outdir>/client`). */\r\n outDir: string;\r\n resolveAliases: BuildHydrationClientOptions[\"resolveAliases\"];\r\n external?: BuildHydrationClientOptions[\"external\"];\r\n /** App-configured plugins, appended after Warlock's client-boundary pipeline. */\r\n plugins?: BuildHydrationClientOptions[\"plugins\"];\r\n}>;\r\n\r\n/**\r\n * The composed client-build pipeline: projection\r\n * strips the 6 server exports first, THEN Gate B's `transform` checks\r\n * whatever source remains for inline secret reads, THEN Gate A's\r\n * `resolveId` judges whatever imports remain. Array order here is\r\n * `[projection(), gateBSecrets(), gateAResolve()]` to match Vite's own\r\n * pipeline shape (`transform` before `resolveId`), but array order alone\r\n * does not guarantee this — see the hook-ordering fact below, which is what\r\n * actually makes the composition correct.\r\n *\r\n * Empirically observed fact (via an instrumented real `vite.build()`, not\r\n * assumed from plugin array order): for a given module M, Vite/Rollup calls\r\n * `transform(M)` BEFORE it calls `resolveId` for any of M's own import\r\n * specifiers — because Rollup must parse M's post-transform source to even\r\n * discover which specifiers to resolve next. Concretely: `transform` ran on\r\n * `entry.page.tsx` first, and only after that did `resolveId(\"./dep\", ...)`\r\n * fire for the import statement still present in the transformed code. A\r\n * consequence follows directly: if projection's `transform` removes an\r\n * import statement from a page module entirely (e.g. `loader`'s\r\n * `@warlock.js/core` import, stripped because `loader` itself is removed),\r\n * `resolveId` is never invoked for that specifier at all — Gate A doesn't\r\n * \"let it pass\", it never sees it. Gate A's `resolveId` only fires for\r\n * imports that survive projection's `transform`, which is exactly why a\r\n * component-level `@warlock.js/core` import (never touched by projection)\r\n * still reaches and is refused by Gate A.\r\n *\r\n * This is OBSERVED Rollup behavior, not a documented contract — a future\r\n * Vite/Rollup upgrade could invert it. Pinned by a\r\n * regression test (`index.spec.ts`, \"D.3 hook ordering pin\") that fails\r\n * loudly if the ordering ever inverts, and by the `vite` peer floor in\r\n * `web/package.json` (`>=7.3.5`, the version this was verified against). If\r\n * that test ever fails after a Vite bump: the failure mode of the ordering\r\n * assumption breaking is SAFE — projection would stop removing an import\r\n * statement Gate A still sees, so Gate A would refuse an import it used to\r\n * silently let a stripped server export take with it. That is a loud build\r\n * failure (\"Gate A refused an import\"), never a silent client-bundle leak.\r\n * Do NOT \"fix\" an apparent Gate A false-positive after a Vite upgrade by\r\n * weakening Gate A (e.g. widening what it lets through) — investigate\r\n * whether this ordering assumption broke instead; loosening Gate A to work\r\n * around it would turn a loud failure into the exact silent leak this\r\n * pipeline exists to prevent.\r\n *\r\n * Gate B is placed between the two for the same reason, but for a `transform`\r\n * hook rather than `resolveId`: within a plugin array, Rollup runs each\r\n * module's registered `transform` hooks in array order, each one receiving\r\n * the PREVIOUS plugin's output. Running Gate B after projection means it\r\n * inspects the POST-projection source — a `process.env.SECRET` read inside\r\n * `loader` (a server export, legitimately reading a real secret server-side)\r\n * is invisible to Gate B once projection has already removed `loader`\r\n * entirely, exactly as it should be: Gate B's job is to fence client-bound\r\n * code, and projection is what decides what counts as client-bound. A\r\n * component-level secret read is untouched by projection and still reaches\r\n * Gate B, which refuses it. Gate B does not depend on Gate A's `resolveId`\r\n * output at all (orthogonal concern, raw source vs. import paths), so its\r\n * position relative to Gate A is not load-bearing — it is placed before Gate\r\n * A only to keep both `transform` hooks adjacent in the array.\r\n *\r\n * Gate C (`gate-c-verify.ts`) runs last and only at `generateBundle` — after\r\n * the entire `transform`/`resolveId` build phase has completed for every\r\n * plugin, regardless of array position (a Rollup lifecycle fact, not\r\n * something this array order enforces). It verifies the EMITTED output the\r\n * other three produced: no server export survived as a top-level binding, no\r\n * import edge into a server-only package survived into the module graph, and\r\n * it emits the reviewable `PUBLIC_*` inlined-value manifest. `gateBSecrets` and `gateCVerify` share\r\n * one `PublicEnvTracker` instance so the manifest and Gate B's own unread-key\r\n * exclusion check agree by construction, not by coincidence.\r\n *\r\n * `clientPageRegistry()` is FIRST, ahead of projection. It contributes no\r\n * `transform` at all — only a `resolveId`/`load` pair for one synthetic id —\r\n * so it cannot displace or pre-empt any gate's inspection of any real file.\r\n * Two reasons for the position, one of which is not load-bearing and is\r\n * labelled as such:\r\n *\r\n * 1. Load-bearing: it must own `virtual:warlock/pages` before Gate A's\r\n * `resolveId` (also `enforce: \"pre\"`) reaches its `this.resolve(...)` call\r\n * for that specifier. Gate A's nested resolve would find it anyway, but\r\n * routing the id through Gate A's importer-chain bookkeeping only to have\r\n * it come back means a synthetic id can surface in a user-facing \"Import\r\n * chain:\" message. Resolving it first keeps ownership of the id in one\r\n * place.\r\n * 2. NOT load-bearing: the position relative to `projection()`. Projection is\r\n * `enforce: \"pre\"` and selects by file BASENAME (`projection.ts:242-248`),\r\n * so it transforms every `*.page.tsx` / `layout.tsx` / `root.tsx` that\r\n * enters the graph regardless of who imported it or where this plugin sits.\r\n * The registry emits absolute POSIX specifiers that Rollup resolves and\r\n * loads as ORDINARY file modules — they are not inlined into the virtual\r\n * module — so each one is transformed exactly as a page imported from a\r\n * real file would be. Projection declines the virtual module itself\r\n * (`\\0virtual:warlock/pages` has no matching basename), which is correct:\r\n * generated code has no server exports to strip.\r\n *\r\n * Point 2 is asserted, not assumed, by a real `vite.build()` in\r\n * `page-registry-plugin.spec.ts`: a fixture page whose `loader` — and only its\r\n * `loader` — imports a marker module that Gate A independently PERMITS, built\r\n * through this exact array, with the marker proven absent from every emitted\r\n * chunk while the page's own component text is proven present. Inspecting this\r\n * array's order would prove nothing about what reaches the browser.\r\n */\r\nexport function warlockClientBoundary(options: WarlockClientBoundaryOptions = {}): Plugin[] {\r\n const tracker = createPublicEnvTracker();\r\n const ssrState: SsrBoundaryState = {\r\n appRoot: path.resolve(options.appRoot ?? process.cwd()),\r\n clientBoundModules: new Set(),\r\n clientImportsByModule: new Map(),\r\n };\r\n return [\r\n clientPageRegistry({\r\n appRoot: options.appRoot,\r\n beforePageHotUpdate: options.beforePageHotUpdate,\r\n }),\r\n projection(),\r\n gateBSecrets({ tracker }),\r\n gateAResolve(options),\r\n gateCVerify({ ...options, tracker }),\r\n ].map((plugin) => clientEnvironmentOnly(plugin, ssrState));\r\n}\r\n\r\n/**\r\n * Callable production seam: callers own their exact source aliases and the\r\n * app-root classification boundary, while this module owns the one canonical\r\n * projection/Gate B/Gate A/Gate C composition.\r\n */\r\nexport async function buildWarlockHydrationClient(\r\n options: BuildWarlockHydrationClientOptions,\r\n): Promise<BuildHydrationClientResult> {\r\n return buildHydrationClient({\r\n webRoot: options.webRoot,\r\n outDir: options.outDir,\r\n resolveAliases: options.resolveAliases,\r\n external: options.external,\r\n plugins: [...warlockClientBoundary({ appRoot: options.appRoot }), ...(options.plugins ?? [])],\r\n });\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0KA,SAAgB,sBAAsB,UAAwC,CAAC,GAAa;CAC1F,MAAM,UAAU,uBAAuB;CACvC,MAAM,WAA6B;EACjC,SAAS,KAAK,QAAQ,QAAQ,WAAW,QAAQ,IAAI,CAAC;EACtD,oCAAoB,IAAI,IAAI;EAC5B,uCAAuB,IAAI,IAAI;CACjC;CACA,OAAO;EACL,mBAAmB;GACjB,SAAS,QAAQ;GACjB,qBAAqB,QAAQ;EAC/B,CAAC;EACD,WAAW;EACX,aAAa,EAAE,QAAQ,CAAC;EACxB,aAAa,OAAO;EACpB,YAAY;GAAE,GAAG;GAAS;EAAQ,CAAC;CACrC,CAAC,CAAC,KAAK,WAAW,sBAAsB,QAAQ,QAAQ,CAAC;AAC3D;;;;;;AAOA,eAAsB,4BACpB,SACqC;CACrC,OAAO,qBAAqB;EAC1B,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,gBAAgB,QAAQ;EACxB,UAAU,QAAQ;EAClB,SAAS,CAAC,GAAG,sBAAsB,EAAE,SAAS,QAAQ,QAAQ,CAAC,GAAG,GAAI,QAAQ,WAAW,CAAC,CAAE;CAC9F,CAAC;AACH"}
@@ -1,5 +1,6 @@
1
- import { discoverPages, toPosix } from "../build/discover-pages.mjs";
2
- import { SERVER_EXPORT_NAMES } from "./projection.mjs";
1
+ import { toPosix } from "../shared/to-posix.mjs";
2
+ import { discoverPages } from "../build/discover-pages.mjs";
3
+ import { SERVER_EXPORT_NAMES, isProjectableFile } from "./projection.mjs";
3
4
  import { generateClientRegistry } from "../build/generate-client-registry.mjs";
4
5
  import path from "node:path";
5
6
  import { parse } from "@babel/parser";
@@ -59,11 +60,9 @@ function invalidateClientPageRegistry(vite) {
59
60
  * directory. `./blog.page.tsx` from that importer resolves to nonsense that
60
61
  * fails at bundle time with a path no user authored and no user can act on.
61
62
  *
62
- * Separator normalization is `hydration-entries.ts`'s
63
- * (`hydration-entries.ts:12-14`) and `discover-pages.ts`'s single
64
- * `.replace(/\\/g, "/")` rule, reused via the already-exported `toPosix` rather
65
- * than spelled a third time — keeping the drive colon (`D:/...`) is exactly
66
- * what Vite's resolver wants on Windows.
63
+ * Separator normalization goes through the one shared `toPosix`
64
+ * (`../shared/to-posix`) keeping the drive colon (`D:/...`) is exactly what
65
+ * Vite's resolver wants on Windows.
67
66
  */
68
67
  function toImportSpecifier(absoluteFilePath) {
69
68
  return toPosix(path.resolve(absoluteFilePath));
@@ -113,22 +112,6 @@ function eraseTypes(source) {
113
112
  return magic.toString();
114
113
  }
115
114
  /**
116
- * The four file shapes that carry SERVER data (`metadata` chief among them)
117
- * and are therefore projected before the client graph forms — the exact set
118
- * `projection.ts`'s `isProjectableFile` matches, spelled here by BASENAME so
119
- * the two agree by construction on what "a server-side page module" is. A
120
- * change to one of these is the only kind of change whose SERVER half
121
- * (`metadata`, `loader`, …) can move without the client half moving at all.
122
- */
123
- function isServerPageModule(file) {
124
- const base = path.basename(file.split("?")[0]);
125
- if (/\.page\.tsx?$/.test(base)) return true;
126
- if (base === "layout.tsx" || base === "layout.ts") return true;
127
- if (/\.layout\.tsx?$/.test(base)) return true;
128
- if (base === "root.tsx") return true;
129
- return false;
130
- }
131
- /**
132
115
  * What replaces a refresh-safe body in the skeleton. Its content is irrelevant —
133
116
  * only that it is CONSTANT, so two sources that differ solely inside a masked
134
117
  * body serialise identically.
@@ -336,7 +319,7 @@ function clientPageRegistry(options = {}) {
336
319
  */
337
320
  transform(code, id) {
338
321
  if (this.environment?.mode !== "dev") return void 0;
339
- if (!isServerPageModule(id)) return void 0;
322
+ if (!isProjectableFile(id)) return void 0;
340
323
  const skeleton = captureSkeleton(code);
341
324
  if (skeleton !== void 0) skeletonCache.set(id, skeleton);
342
325
  },
@@ -355,14 +338,14 @@ function clientPageRegistry(options = {}) {
355
338
  * construction.
356
339
  */
357
340
  async hotUpdate(context) {
358
- if (isServerPageModule(context.file)) {
341
+ if (isProjectableFile(context.file)) {
359
342
  if (await options.beforePageHotUpdate?.({
360
343
  file: context.file,
361
344
  type: context.type
362
345
  })) return [];
363
346
  }
364
347
  if (context.type !== "update") return void 0;
365
- if (!isServerPageModule(context.file)) return void 0;
348
+ if (!isProjectableFile(context.file)) return void 0;
366
349
  const next = captureSkeleton(await context.read());
367
350
  const prev = skeletonCache.get(context.file);
368
351
  if (next !== void 0) skeletonCache.set(context.file, next);