@warlock.js/web 5.2.3 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/esm/build/contribution.mjs.map +1 -1
  2. package/esm/build/discover-pages.mjs +5 -7
  3. package/esm/build/discover-pages.mjs.map +1 -1
  4. package/esm/build/generate-client-registry.mjs.map +1 -1
  5. package/esm/build/generate-pages-barrel.mjs.map +1 -1
  6. package/esm/build/page-default-export.mjs.map +1 -1
  7. package/esm/build/page-routes-manifest.mjs.map +1 -1
  8. package/esm/build/public-files.mjs.map +1 -1
  9. package/esm/build/read-route-exports.mjs.map +1 -1
  10. package/esm/client/build-hydrated-tree.mjs.map +1 -1
  11. package/esm/client/hydrate-page.mjs +4 -3
  12. package/esm/client/hydrate-page.mjs.map +1 -1
  13. package/esm/client/navigation/fetch-page-data.mjs +2 -2
  14. package/esm/client/navigation/fetch-page-data.mjs.map +1 -1
  15. package/esm/client/navigation/navigation-root.mjs +5 -1
  16. package/esm/client/navigation/navigation-root.mjs.map +1 -1
  17. package/esm/client/navigation/prefetch.mjs.map +1 -1
  18. package/esm/client/runtime/manifest.mjs.map +1 -1
  19. package/esm/client/runtime/matcher.mjs.map +1 -1
  20. package/esm/components/document-context.mjs.map +1 -1
  21. package/esm/components/link.mjs.map +1 -1
  22. package/esm/hydration-payload.mjs +6 -2
  23. package/esm/hydration-payload.mjs.map +1 -1
  24. package/esm/index.d.mts +4 -2
  25. package/esm/index.mjs +2 -1
  26. package/esm/localization.d.mts +21 -0
  27. package/esm/localization.mjs +28 -0
  28. package/esm/localization.mjs.map +1 -0
  29. package/esm/routing/data-request.mjs +5 -3
  30. package/esm/routing/data-request.mjs.map +1 -1
  31. package/esm/routing/filesystem-route.mjs +36 -7
  32. package/esm/routing/filesystem-route.mjs.map +1 -1
  33. package/esm/routing/layout-policy.mjs.map +1 -1
  34. package/esm/routing/page-file-segment.mjs +66 -0
  35. package/esm/routing/page-file-segment.mjs.map +1 -0
  36. package/esm/routing/page-route-grammar.mjs +79 -0
  37. package/esm/routing/page-route-grammar.mjs.map +1 -0
  38. package/esm/routing/query-string.mjs.map +1 -1
  39. package/esm/routing/route-identity.d.mts +69 -0
  40. package/esm/routing/route-identity.mjs +100 -44
  41. package/esm/routing/route-identity.mjs.map +1 -1
  42. package/esm/routing/route-table.mjs.map +1 -1
  43. package/esm/server/build-hydration-payload.mjs +3 -2
  44. package/esm/server/build-hydration-payload.mjs.map +1 -1
  45. package/esm/server/create-page-route-handler.d.mts +34 -1
  46. package/esm/server/create-page-route-handler.mjs +35 -4
  47. package/esm/server/create-page-route-handler.mjs.map +1 -1
  48. package/esm/server/execute-page-request.mjs.map +1 -1
  49. package/esm/server/framework-default-not-found-stylesheet.mjs +102 -0
  50. package/esm/server/framework-default-not-found-stylesheet.mjs.map +1 -0
  51. package/esm/server/install-page-routes-from-manifest.mjs +13 -16
  52. package/esm/server/install-page-routes-from-manifest.mjs.map +1 -1
  53. package/esm/server/install-page-routes.d.mts +3 -1
  54. package/esm/server/install-page-routes.mjs +11 -11
  55. package/esm/server/install-page-routes.mjs.map +1 -1
  56. package/esm/server/match-page-route.mjs.map +1 -1
  57. package/esm/server/not-found-page.d.mts +1 -13
  58. package/esm/server/not-found-page.mjs +50 -5
  59. package/esm/server/not-found-page.mjs.map +1 -1
  60. package/esm/server/page-file-change.mjs.map +1 -1
  61. package/esm/server/page-route-reload.mjs.map +1 -1
  62. package/esm/server/register-production-public-files.mjs +16 -1
  63. package/esm/server/register-production-public-files.mjs.map +1 -1
  64. package/esm/server/render-page.d.mts +1 -8
  65. package/esm/server/render-page.mjs +24 -21
  66. package/esm/server/render-page.mjs.map +1 -1
  67. package/esm/server/response-cache-floor.mjs +79 -0
  68. package/esm/server/response-cache-floor.mjs.map +1 -0
  69. package/esm/server/set-cookie-cache-floor-hook.mjs +41 -0
  70. package/esm/server/set-cookie-cache-floor-hook.mjs.map +1 -0
  71. package/esm/server/settle-page-response.mjs.map +1 -1
  72. package/esm/server/stylesheet-urls.mjs.map +1 -1
  73. package/esm/server/unregistered-pages.mjs.map +1 -1
  74. package/esm/server/web-connector-factory.mjs.map +1 -1
  75. package/esm/server/web-connector.d.mts +1 -1
  76. package/esm/server/web-connector.mjs +23 -4
  77. package/esm/server/web-connector.mjs.map +1 -1
  78. package/esm/shared.mjs.map +1 -1
  79. package/esm/vite/build-client.mjs.map +1 -1
  80. package/esm/vite/gate-a-resolve.mjs.map +1 -1
  81. package/esm/vite/gate-b-secrets.mjs.map +1 -1
  82. package/esm/vite/gate-c-verify.mjs.map +1 -1
  83. package/esm/vite/hydration-entries.mjs.map +1 -1
  84. package/esm/vite/index.mjs.map +1 -1
  85. package/esm/vite/page-registry-plugin.mjs.map +1 -1
  86. package/esm/vite/projection.mjs.map +1 -1
  87. package/llms-full.txt +62 -33
  88. package/llms.txt +1 -1
  89. package/package.json +4 -3
  90. package/skills/create-a-page/SKILL.md +59 -28
  91. package/skills/navigate-on-the-client/SKILL.md +16 -11
  92. package/skills/serve-styles/SKILL.md +2 -1
  93. package/skills/use-layouts/SKILL.md +3 -6
  94. package/skills/write-the-root/SKILL.md +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"document-context.mjs","names":[],"sources":["../../../../../../../web/src/components/document-context.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport type { MetadataOutput } from \"../metadata\";\n\n/**\n * The JSON-safe error shape carried from the server document to browser\n * hydration.\n *\n * This is deliberately NOT the original thrown object. Error prototypes,\n * identity, non-enumerable fields and arbitrary custom values do not survive a\n * JSON boundary reliably. The server renders `ErrorPageProps` with the\n * original value, then normalizes it to this lossy representation only for the\n * hydration payload. Normalization also owns disclosure: `stack` is optional\n * and must be omitted or redacted when server internals are not safe to expose\n * to the browser.\n */\nexport type SerializedPageError = {\n readonly name: string;\n readonly message: string;\n readonly stack?: string;\n};\n\n/**\n * Props received by the application-owned `error.page.tsx` during SSR.\n *\n * Deliberately preserve the thrown value here. An application can use its own\n * error classes, symbols, or structured values while rendering on the server;\n * this public component contract is not a JSON boundary.\n */\nexport type ErrorPageProps = {\n readonly error: unknown;\n readonly status: number;\n};\n\n/**\n * The JSON-safe counterpart of {@link ErrorPageProps}, used only after the\n * document crosses from SSR into browser hydration. Keeping this distinct\n * prevents a serialized approximation from being mistaken for the original\n * thrown value available to the server render.\n */\nexport type SerializedErrorPageProps = {\n readonly error: SerializedPageError;\n readonly status: number;\n};\n\nexport type HydrationDocumentPayloadSource = {\n readonly appData: unknown;\n readonly layoutData: unknown;\n readonly pageData: unknown;\n readonly shared: unknown;\n /**\n * The matched page manifest entry's stable `name` — the same field the\n * manifest entry contract `{ type, name, path, load }` declares. It is on\n * the wire so the browser can look up WHICH page the server rendered\n * instead of re-matching `location.pathname` itself: re-matching is a\n * second implementation of route semantics, and it can disagree with the\n * server on the very request it is hydrating.\n */\n readonly name: string;\n /**\n * The params the SERVER matched for this request — `bundle.route.params`\n * (`server/execute-page-request.ts:288`), carried untransformed. Same reason\n * `name` is here: the browser must not re-derive them from\n * `location.pathname`, because deriving them IS a second matcher.\n *\n * OPTIONAL, and ungated on purpose — see {@link metadata} below for the rule\n * both new keys share. The server always emits it (`{}` for a route with no\n * dynamic segments), so absence means the payload came from a producer that\n * predates this key; `currentRoute()` then reports `{}` rather than failing a\n * page over an accessor.\n */\n readonly params?: Readonly<Record<string, string>>;\n /**\n * The page metadata the server resolved at stage 8, carried WHOLE — the same\n * `MetadataOutput` `<Head/>` rendered into the document on the first request.\n *\n * Why it has to be on the wire at all: `<Head/>` renders inside the App\n * level, and the App level is not part of the hydrated tree (the client\n * mounts at `#root`, which App contains). So on a client navigation there is\n * no React render that can reach `<head>` — without this key the browser\n * never learns the new page's title and the tab keeps the old one.\n *\n * OPTIONAL, deliberately: `bundle.metadata` is itself optional\n * (`server/execute-page-request.ts:296`) — a page that exports no `metadata`\n * produces none, and a loader short-circuit skips stage 8 entirely. Gating a\n * key the server is right not to produce would make `readHydrationPayload`\n * throw on a valid page. Present-but-not-an-object is still MALFORMED and\n * still throws; only ABSENT is accepted.\n */\n readonly metadata?: MetadataOutput;\n /**\n * Present only when the server selected the application-owned error page for\n * this response. Atomic rather than two independently optional top-level\n * fields: a status without an error (or the reverse) cannot describe a tree\n * the browser can hydrate.\n *\n * `name` above intentionally remains the ORIGINAL matched route. This field\n * selects the `ErrorPage` module projected into that route's client\n * composition; it does not turn the error page into a second browsable route.\n */\n readonly errorPage?: SerializedErrorPageProps;\n};\n\nexport const PAYLOAD_SCRIPT_ID = \"__WARLOCK_DATA__\";\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028);\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);\n\n/** Escape JSON text for raw insertion into an application/json script. */\nexport function escapePayload(json: string): string {\n return json\n .split(\"<\")\n .join(\"\\\\u003c\")\n .split(\">\")\n .join(\"\\\\u003e\")\n .split(LINE_SEPARATOR)\n .join(\"\\\\u2028\")\n .split(PARAGRAPH_SEPARATOR)\n .join(\"\\\\u2029\");\n}\n\n/**\n * What `<Head/>`/`<Scripts/>` need to render real elements instead of the\n * framework injecting them by string surgery post-render (Suki, room seq\n * 1205): the resolved page metadata and the exact payload the hydration\n * script will read back. Provided once, around the root element, before\n * `renderToString` runs (`render-page.ts`'s stage 9 — the bundle is already\n * complete by then). Universal: no server-only imports, so the client's\n * hydration entry (a later slice) can provide the same shape from the parsed\n * payload script.\n */\nexport type DocumentContextValue = {\n metadata: MetadataOutput | undefined;\n payload: HydrationDocumentPayloadSource;\n /**\n * The nonce/lang/dir SLOTS: fed by the render provider from CORE request\n * fields — request nonce, request locale — never from app-owned `shared`\n * keys, which an app can overwrite. The provider-side\n * wiring is a separate slice, so these are absent at runtime until it\n * lands; every reader must treat them as optional.\n */\n nonce?: string;\n lang?: string;\n dir?: string;\n};\n\nexport const DocumentContext = createContext<DocumentContextValue | undefined>(undefined);\n\n/**\n * Require the page pipeline's universal document state. The payload id and\n * escaping helpers remain exported above for the existing server seam.\n */\nexport function useDocumentContext(componentName: string): DocumentContextValue {\n const value = useContext(DocumentContext);\n\n if (!value) {\n throw new Error(\n `<${componentName}/> was rendered outside the page pipeline's document context ` +\n \"(web/src/components/document-context.ts). Fix: only render it inside \" +\n \"an App/Layout/Page component tree the pipeline itself renders.\",\n );\n }\n\n return value;\n}\n"],"mappings":";;;AAsGA,MAAa,oBAAoB;AAEjC,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;AAGtD,SAAgB,cAAc,MAAsB;CAClD,OAAO,KACJ,MAAM,GAAG,EACT,KAAK,SAAS,EACd,MAAM,GAAG,EACT,KAAK,SAAS,EACd,MAAM,cAAc,EACpB,KAAK,SAAS,EACd,MAAM,mBAAmB,EACzB,KAAK,SAAS;AACnB;AA2BA,MAAa,kBAAkB,cAAgD,MAAS;;;;;AAMxF,SAAgB,mBAAmB,eAA6C;CAC9E,MAAM,QAAQ,WAAW,eAAe;CAExC,IAAI,CAAC,OACH,MAAM,IAAI,MACR,IAAI,cAAc,iMAGpB;CAGF,OAAO;AACT"}
1
+ {"version":3,"file":"document-context.mjs","names":[],"sources":["../../../../../../../web/src/components/document-context.ts"],"sourcesContent":["import { createContext, useContext } from \"react\";\nimport type { MetadataOutput } from \"../metadata\";\n\n/**\n * The JSON-safe error shape carried from the server document to browser\n * hydration.\n *\n * This is deliberately NOT the original thrown object. Error prototypes,\n * identity, non-enumerable fields and arbitrary custom values do not survive a\n * JSON boundary reliably. The server renders `ErrorPageProps` with the\n * original value, then normalizes it to this lossy representation only for the\n * hydration payload. Normalization also owns disclosure: `stack` is optional\n * and must be omitted or redacted when server internals are not safe to expose\n * to the browser.\n */\nexport type SerializedPageError = {\n readonly name: string;\n readonly message: string;\n readonly stack?: string;\n};\n\n/**\n * Props received by the application-owned `error.page.tsx` during SSR.\n *\n * Deliberately preserve the thrown value here. An application can use its own\n * error classes, symbols, or structured values while rendering on the server;\n * this public component contract is not a JSON boundary.\n */\nexport type ErrorPageProps = {\n readonly error: unknown;\n readonly status: number;\n};\n\n/**\n * The JSON-safe counterpart of {@link ErrorPageProps}, used only after the\n * document crosses from SSR into browser hydration. Keeping this distinct\n * prevents a serialized approximation from being mistaken for the original\n * thrown value available to the server render.\n */\nexport type SerializedErrorPageProps = {\n readonly error: SerializedPageError;\n readonly status: number;\n};\n\nexport type HydrationDocumentPayloadSource = {\n readonly appData: unknown;\n readonly layoutData: unknown;\n readonly pageData: unknown;\n readonly shared: unknown;\n /**\n * The matched page manifest entry's stable `name` — the same field the\n * manifest entry contract `{ type, name, path, load }` declares. It is on\n * the wire so the browser can look up WHICH page the server rendered\n * instead of re-matching `location.pathname` itself: re-matching is a\n * second implementation of route semantics, and it can disagree with the\n * server on the very request it is hydrating.\n */\n readonly name: string;\n /** The request locale selected by core for this exact render. */\n readonly locale: string;\n /**\n * The params the SERVER matched for this request — `bundle.route.params`\n * (`server/execute-page-request.ts:288`), carried untransformed. Same reason\n * `name` is here: the browser must not re-derive them from\n * `location.pathname`, because deriving them IS a second matcher.\n *\n * OPTIONAL, and ungated on purpose — see {@link metadata} below for the rule\n * both new keys share. The server always emits it (`{}` for a route with no\n * dynamic segments), so absence means the payload came from a producer that\n * predates this key; `currentRoute()` then reports `{}` rather than failing a\n * page over an accessor.\n */\n readonly params?: Readonly<Record<string, string>>;\n /**\n * The page metadata the server resolved at stage 8, carried WHOLE — the same\n * `MetadataOutput` `<Head/>` rendered into the document on the first request.\n *\n * Why it has to be on the wire at all: `<Head/>` renders inside the App\n * level, and the App level is not part of the hydrated tree (the client\n * mounts at `#root`, which App contains). So on a client navigation there is\n * no React render that can reach `<head>` — without this key the browser\n * never learns the new page's title and the tab keeps the old one.\n *\n * OPTIONAL, deliberately: `bundle.metadata` is itself optional\n * (`server/execute-page-request.ts:296`) — a page that exports no `metadata`\n * produces none, and a loader short-circuit skips stage 8 entirely. Gating a\n * key the server is right not to produce would make `readHydrationPayload`\n * throw on a valid page. Present-but-not-an-object is still MALFORMED and\n * still throws; only ABSENT is accepted.\n */\n readonly metadata?: MetadataOutput;\n /**\n * Present only when the server selected the application-owned error page for\n * this response. Atomic rather than two independently optional top-level\n * fields: a status without an error (or the reverse) cannot describe a tree\n * the browser can hydrate.\n *\n * `name` above intentionally remains the ORIGINAL matched route. This field\n * selects the `ErrorPage` module projected into that route's client\n * composition; it does not turn the error page into a second browsable route.\n */\n readonly errorPage?: SerializedErrorPageProps;\n};\n\nexport const PAYLOAD_SCRIPT_ID = \"__WARLOCK_DATA__\";\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028);\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029);\n\n/** Escape JSON text for raw insertion into an application/json script. */\nexport function escapePayload(json: string): string {\n return json\n .split(\"<\")\n .join(\"\\\\u003c\")\n .split(\">\")\n .join(\"\\\\u003e\")\n .split(LINE_SEPARATOR)\n .join(\"\\\\u2028\")\n .split(PARAGRAPH_SEPARATOR)\n .join(\"\\\\u2029\");\n}\n\n/**\n * What `<Head/>`/`<Scripts/>` need to render real elements instead of the\n * framework injecting them by string surgery post-render (Suki, room seq\n * 1205): the resolved page metadata and the exact payload the hydration\n * script will read back. Provided once, around the root element, before\n * `renderToString` runs (`render-page.ts`'s stage 9 — the bundle is already\n * complete by then). Universal: no server-only imports, so the client's\n * hydration entry (a later slice) can provide the same shape from the parsed\n * payload script.\n */\nexport type DocumentContextValue = {\n metadata: MetadataOutput | undefined;\n payload: HydrationDocumentPayloadSource;\n /**\n * The nonce/lang/dir SLOTS: fed by the render provider from CORE request\n * fields — request nonce, request locale — never from app-owned `shared`\n * keys, which an app can overwrite. The provider-side\n * wiring is a separate slice, so these are absent at runtime until it\n * lands; every reader must treat them as optional.\n */\n nonce?: string;\n lang?: string;\n dir?: string;\n};\n\nexport const DocumentContext = createContext<DocumentContextValue | undefined>(undefined);\n\n/**\n * Require the page pipeline's universal document state. The payload id and\n * escaping helpers remain exported above for the existing server seam.\n */\nexport function useDocumentContext(componentName: string): DocumentContextValue {\n const value = useContext(DocumentContext);\n\n if (!value) {\n throw new Error(\n `<${componentName}/> was rendered outside the page pipeline's document context ` +\n \"(web/src/components/document-context.ts). Fix: only render it inside \" +\n \"an App/Layout/Page component tree the pipeline itself renders.\",\n );\n }\n\n return value;\n}\n"],"mappings":";;;AAwGA,MAAa,oBAAoB;AAEjC,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;AAGtD,SAAgB,cAAc,MAAsB;CAClD,OAAO,KACJ,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,CAAC,CACf,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,CAAC,CACf,MAAM,cAAc,CAAC,CACrB,KAAK,SAAS,CAAC,CACf,MAAM,mBAAmB,CAAC,CAC1B,KAAK,SAAS;AACnB;AA2BA,MAAa,kBAAkB,cAAgD,MAAS;;;;;AAMxF,SAAgB,mBAAmB,eAA6C;CAC9E,MAAM,QAAQ,WAAW,eAAe;CAExC,IAAI,CAAC,OACH,MAAM,IAAI,MACR,IAAI,cAAc,iMAGpB;CAGF,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"link.mjs","names":[],"sources":["../../../../../../../web/src/components/link.ts"],"sourcesContent":["import { createElement } from \"react\";\nimport type {\n AnchorHTMLAttributes,\n ComponentType,\n FocusEvent,\n MouseEvent,\n ReactElement,\n} from \"react\";\nimport { prefetchPageData } from \"../client/navigation/prefetch\";\nimport { currentNavigator } from \"../routing/navigator\";\nimport { href, knownRouteNames } from \"../routing/route-table\";\n\n/**\n * `<Link>` is SUGAR over `href()`, and deliberately thin.\n *\n * `href(name, params, query)` is the durable primitive — it serves emails,\n * redirects, `Location` headers and every non-React caller, none of which can\n * render a component. This file adds one thing to it: an anchor element.\n *\n * It renders a real `<a href>`. Client-side interception is a later slice of\n * the navigation runtime and lands here without changing this API, which is the\n * point of routing everything through `href` first: navigation becomes a\n * BEHAVIOUR change, not an API change.\n *\n * ── Parity with `@mongez/react-router` ───────────────────────────────────────\n * `href`, `newTab`, `email`, `tel`, `component` and `prefetch` are spelled\n * exactly as MRR spells them, so a component moved across keeps compiling.\n * `params` and `query` are ours and have no MRR equivalent: they pair with the\n * typed `href()` helper, which is what makes a route NAME — rather than a URL —\n * the thing a call site names.\n *\n * ── The semantic divergence this file bridges ────────────────────────────────\n * MRR's `to` is a PATH. Ours was a route NAME, and only a name — which meant a\n * component moved across from MRR compiled and then threw at render, because\n * `\"/products\"` is not the name of anything. The two packages disagreed about\n * what the most-used prop in either of them MEANS.\n *\n * Since 2026-08-24 (owner ruling) `to`/`href` accept BOTH, discriminated by\n * SHAPE — see {@link isLiteralUrl}. That is what makes MRR code portable, and\n * it costs nothing at a Warlock call site, because the two grammars cannot\n * collide: a route name never begins with `/` and never carries a `scheme:`.\n * The ruling RESTS on that, so this file asserts it rather than trusting it\n * ({@link RouteNameShapeCollisionError}).\n */\n\ntype AnchorProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\">;\n\n/**\n * Where the link goes. Every field is documented here once; which COMBINATIONS\n * are legal is decided by {@link LinkDestination}.\n */\ntype LinkDestinationProps = {\n /**\n * A route NAME, or a literal URL — told apart by SHAPE.\n *\n * `\"products.details\"` is a NAME and is resolved through the route table. A\n * page that moves changes its URL and keeps its name, so every call site\n * survives the move; a dead name throws at render naming the routes that do\n * exist, rather than rendering an anchor that 404s. This is the form to\n * prefer, and the only one `params` and `query` apply to.\n *\n * `\"/pricing\"`, `\"https://stripe.com\"`, `\"mailto:sales@example.com\"` and any\n * other `scheme:` are LITERAL — passed through to the element untouched, with\n * no route lookup at all. An app links out, and a route name is not a thing\n * you can have for a page that is not yours.\n */\n to?: string;\n /**\n * An alias of {@link to}, for parity with `@mongez/react-router`. Identical\n * in every respect, including which shapes it accepts.\n */\n href?: string;\n /** Renders a `mailto:` link. Not an in-app navigation. */\n email?: string;\n /** Renders a `tel:` link. Not an in-app navigation. */\n tel?: string;\n /**\n * Values for the route's `:param` segments, e.g. `{ id }` for\n * `\"/products/:id\"`. Only meaningful with a route NAME.\n */\n params?: Record<string, unknown>;\n /**\n * Query string values; an `undefined` value is omitted. Only meaningful with\n * a route NAME.\n */\n query?: Record<string, unknown>;\n};\n\n/**\n * EXACTLY ONE destination, enforced by the type.\n *\n * The alternative — a documented precedence such as \"`to` wins over `href`\" —\n * is silent by construction: the losing prop goes on compiling and goes on\n * reading like it works at the call site, and the anchor points at the wrong\n * page. Refusing the pair costs a call site one edit and can never be\n * misread. The runtime refuses it as well, because a JavaScript caller and a\n * cast both get past this.\n */\ntype LinkDestination =\n | { to: string; href?: never; email?: never; tel?: never }\n | { href: string; to?: never; email?: never; tel?: never }\n | { email: string; to?: never; href?: never; tel?: never }\n | { tel: string; to?: never; href?: never; email?: never };\n\nexport type LinkProps = AnchorProps &\n LinkDestinationProps &\n LinkDestination & {\n /**\n * Open in a new browsing context: `target=\"_blank\"` plus the `rel` that\n * stops the opened page from reaching back through `window.opener`.\n *\n * A caller's own `target`/`rel` win — this only fills in what was not said.\n */\n newTab?: boolean;\n /**\n * Render as something other than `<a>` — a tag name or a component.\n *\n * It receives the resolved `href`, the click handler and every remaining\n * prop, so a design-system anchor keeps client-side navigation as long as\n * it spreads what it is given onto the element it renders.\n *\n * `ComponentType<any>` is MRR's signature, kept verbatim: the component is\n * the caller's and its props are unknowable from here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component?: ComponentType<any> | string;\n /**\n * Fetch this page's data when the pointer or the keyboard reaches the link,\n * so the click that follows swaps without a round trip.\n *\n * A GUESS, and treated as one everywhere: it is never awaited, a failure is\n * silent, and the click behaves exactly as it would without it. Opt-in per\n * link rather than on by default, because every prefetch is a request the\n * user did not ask for and someone pays for the bandwidth.\n *\n * IGNORED for anything that is not an in-app navigation — an external URL,\n * `mailto:`, `tel:`, `newTab`, any explicit `target`. Prefetching those\n * would mean issuing a cross-origin request to a third party on hover,\n * which is not a thing a link component may decide to do.\n */\n prefetch?: boolean;\n };\n\nconst DESTINATION_PROPS = [\"to\", \"href\", \"email\", \"tel\"] as const;\n\nexport class AmbiguousLinkDestinationError extends Error {\n public constructor(public readonly providedProps: readonly string[]) {\n super(\n `Warlock <Link> was given ${providedProps\n .map(name => JSON.stringify(name))\n .join(\" and \")}, but a link goes to exactly one place. There is no ` +\n \"precedence between them on purpose: one of the two would silently win, and the \" +\n \"call site would go on naming a destination that never renders. Delete the one \" +\n \"you did not mean.\",\n );\n this.name = \"AmbiguousLinkDestinationError\";\n }\n}\n\nexport class MissingLinkDestinationError extends Error {\n public constructor() {\n super(\n `Warlock <Link> was given no destination. Pass exactly one of ${DESTINATION_PROPS.map(\n name => JSON.stringify(name),\n ).join(\", \")}. It is not defaulted to the current page: an anchor with an empty ` +\n \"`href` renders as a working link and reloads the page when clicked, which is a \" +\n \"harder fault to see than this message.\",\n );\n this.name = \"MissingLinkDestinationError\";\n }\n}\n\nexport class RouteArgumentsOnLiteralUrlError extends Error {\n public constructor(\n public readonly url: string,\n public readonly providedProps: readonly string[],\n ) {\n super(\n `Warlock <Link> was given ${providedProps\n .map(name => JSON.stringify(name))\n .join(\" and \")} alongside the literal URL \"${url}\". Those apply to a route NAME, ` +\n \"which is resolved through the route table; a literal URL is passed through exactly \" +\n \"as written, so they would have been dropped and the link would have pointed at an \" +\n \"unfiltered page that still looked right at the call site. Put the values in the URL, \" +\n \"or name the route.\",\n );\n this.name = \"RouteArgumentsOnLiteralUrlError\";\n }\n}\n\n/**\n * The ruling's one assumption, broken. See the module doc comment: telling a\n * literal URL from a route NAME by shape is only safe while no route is NAMED\n * like a URL, and nothing in the route pipeline validates a hand-declared\n * `route.name`. So the collision is checked at the one place it could do harm,\n * where it is a loud refusal instead of an anchor that silently points\n * somewhere else.\n */\nexport class RouteNameShapeCollisionError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock route table: a route is NAMED ${JSON.stringify(routeName)}, which is shaped ` +\n \"like a URL. <Link> tells a literal URL from a route name by shape — a destination \" +\n \"starting with `/` or carrying a `scheme:` is passed through untouched — so this name \" +\n \"can never be resolved, and every link to it would silently point at that path \" +\n \"instead. Rename the route (`route = { path, name }`) to a dotted name such as \" +\n `${JSON.stringify(routeName.replace(/^\\/+/, \"\").replace(/\\//g, \".\") || \"index\")}.`,\n );\n this.name = \"RouteNameShapeCollisionError\";\n }\n}\n\ntype Destination = {\n /** What lands on the element's `href`. */\n url: string;\n /**\n * Whether this URL is a page in THIS app — the only kind the client\n * navigation runtime may be asked about, and the only kind that may be\n * prefetched. `mailto:`, `tel:` and an external URL hand off to another\n * application or another origin entirely, so intercepting any of them would\n * break it, and speculatively fetching one would be a cross-origin request\n * the developer never asked for.\n */\n isInApp: boolean;\n};\n\n/**\n * Any RFC 3986 scheme — `https:`, `mailto:`, `tel:`, `whatsapp:`, an app's own\n * custom one. Matched generically rather than as a list of known schemes: a\n * list would silently resolve `bitcoin:...` through the route table, which is\n * the exact failure this ruling exists to remove, and it would have to grow\n * forever.\n */\nconst SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/i;\n\n/**\n * Whether this destination is a URL to be used as written, rather than a route\n * name to resolve.\n *\n * The whole discriminator, and deliberately the whole of it: two cheap shape\n * tests, no parsing, no matching. Anything more would be a SECOND route matcher\n * living beside the server's, which this codebase refuses everywhere it comes\n * up — a matcher that disagreed with the real one would produce links to pages\n * that do not exist.\n */\nfunction isLiteralUrl(destination: string): boolean {\n return destination.startsWith(\"/\") || SCHEME_PATTERN.test(destination);\n}\n\n/**\n * Whether a literal URL addresses THIS app.\n *\n * A path is ours. A `scheme:` is not — including `https:` to our own origin,\n * which would need `window.location` to recognise and would make the answer\n * depend on where the code is running. And `//host/path` is PROTOCOL-RELATIVE:\n * it starts with a slash and is nonetheless another origin, which is precisely\n * the case a \"starts with `/`\" test alone would hand to the navigator, where it\n * becomes a `pushState` to a foreign origin — a SecurityError — or a\n * speculative fetch of a third-party host.\n */\nfunction addressesThisApp(url: string): boolean {\n return url.startsWith(\"/\") && !url.startsWith(\"//\");\n}\n\n/**\n * Refuses the one table that would make {@link isLiteralUrl} wrong.\n *\n * Reached only for a destination already judged literal, so the cost is a scan\n * of the published names for links that were never going to hit the table\n * anyway — and zero for the route-name form, which is the common one. The right\n * permanent home for this is `publishRouteTable`, at boot, once (see the report\n * on this card).\n */\nfunction assertNotARouteName(url: string): void {\n if (knownRouteNames().includes(url)) throw new RouteNameShapeCollisionError(url);\n}\n\nconst ROUTE_ARGUMENT_PROPS = [\"params\", \"query\"] as const;\n\nfunction resolveDestination(props: LinkDestinationProps): Destination {\n const provided = DESTINATION_PROPS.filter(name => props[name] !== undefined);\n\n if (provided.length > 1) throw new AmbiguousLinkDestinationError(provided);\n\n if (provided.length === 0) throw new MissingLinkDestinationError();\n\n if (props.email !== undefined) return { url: `mailto:${props.email}`, isInApp: false };\n\n if (props.tel !== undefined) return { url: `tel:${props.tel}`, isInApp: false };\n\n const destination = (props.to ?? props.href) as string;\n\n /*\n LITERAL: `/pricing`, `https://stripe.com`, `mailto:…`, `whatsapp://…`. It\n goes to the element exactly as written and the route table is never\n consulted — there is nothing to look up, and looking anyway is what used to\n throw `UnknownRouteNameError` on every link out of the application.\n */\n if (isLiteralUrl(destination)) {\n const routeArguments = ROUTE_ARGUMENT_PROPS.filter(name => props[name] !== undefined);\n\n if (routeArguments.length > 0) {\n throw new RouteArgumentsOnLiteralUrlError(destination, routeArguments);\n }\n\n assertNotARouteName(destination);\n\n return { url: destination, isInApp: addressesThisApp(destination) };\n }\n\n /*\n A NAME, resolved against the route table published at boot from the SAME\n discovery result the server registered its routes from. The previous version\n of this file restated six URLs in a literal map, so linking to any seventh\n page in the application threw — the map was the limit on what could be\n linked, and nothing said so at the call site.\n */\n return { url: href(destination, props.params, props.query), isInApp: true };\n}\n\n/**\n * Whether this click should be left entirely to the browser.\n *\n * Every case here is a click that MEANS something other than \"go there in this\n * tab\", and intercepting any of them would take away behaviour the user\n * explicitly asked for:\n *\n * - a modifier or middle button: open in a new tab/window, or download\n * - `download`: save the resource, do not render it\n * - already prevented: something upstream in the tree handled this click\n *\n * Left button with no modifiers is the only click that means plain navigation.\n * The `target` case is decided before this, from the RESOLVED target, because\n * `newTab` sets it after the caller's props are read.\n */\nfunction isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>): boolean {\n return (\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.defaultPrevented\n );\n}\n\n/**\n * A target other than `_self` names ANOTHER browsing context — `_blank`, but\n * also `_parent`, `_top` and any named frame. Client navigation rewrites the\n * history of THIS one, so none of them are ours to intercept.\n */\nfunction opensAnotherContext(target: string | undefined): boolean {\n return target !== undefined && target !== \"_self\";\n}\n\nexport function Link({\n to,\n href: hrefAlias,\n email,\n tel,\n params,\n query,\n newTab,\n prefetch,\n component: Component = \"a\",\n children,\n onClick,\n ...elementProps\n}: LinkProps): ReactElement {\n const { url, isInApp } = resolveDestination({\n to,\n href: hrefAlias,\n email,\n tel,\n params,\n query,\n });\n\n const target = elementProps.target ?? (newTab === true ? \"_blank\" : undefined);\n\n // Only a DEFAULT: a caller that wrote its own `rel` (`\"me noopener\"`,\n // `\"external\"`) meant it, and overwriting it would delete a value the page\n // depends on to say something this component knows nothing about.\n const rel =\n elementProps.rel ?? (target === \"_blank\" ? \"noopener noreferrer\" : undefined);\n\n const handleClick = (event: MouseEvent<HTMLAnchorElement>): void => {\n // The caller's handler runs FIRST and unconditionally — it may be doing\n // analytics, closing a menu, or calling `preventDefault()` to veto the\n // navigation outright. Deciding before it ran would let this component\n // navigate away from a click the application had already cancelled.\n onClick?.(event);\n\n // `mailto:`, `tel:` and anything aimed at another browsing context leave\n // this page standing. The runtime is not consulted at all — asking it would\n // spend a page-data fetch on a click that was never going to navigate here.\n if (!isInApp || opensAnotherContext(target)) return;\n\n if (!isPlainLeftClick(event)) return;\n\n /*\n Asked for per click, never captured at render: the runtime registers\n itself when the hydration bundle mounts, which is AFTER the first render\n of every anchor on the page. A value read at render time would be\n `undefined` forever for exactly the links present at hydration — that is,\n all of them.\n\n Absent (server render, or before hydration) the anchor is left alone and\n does what an anchor does. That is the whole progressive-enhancement story:\n links work before this code runs, and work better after.\n */\n if (currentNavigator()?.(url) !== true) return;\n\n event.preventDefault();\n };\n\n /*\n The SAME gate the click uses, asked before any speculative request exists:\n only a destination this app would have navigated to itself may be fetched\n ahead of time. `mailto:`, `tel:`, an external URL and anything aimed at\n another browsing context are all clicks that leave this page, and none of\n them has page data to fetch.\n */\n const prefetchesOnInteraction =\n prefetch === true && isInApp && !opensAnotherContext(target);\n\n /*\n Attached ONLY when prefetching — a link without the prop keeps whatever\n handlers the caller passed, on the element, unwrapped.\n\n Hover AND focus, because a keyboard user never generates the first one and\n would otherwise be the only visitor who never gets the optimisation.\n\n Fire-and-forget by construction: `prefetchPageData` never rejects and is\n never awaited, so nothing here can delay the event or surface a failure. It\n is also safe to reach on the server — it no-ops without a browser — which is\n why this file can import it directly rather than through a `connect*` seam\n like the navigator's. The navigator needs a seam because the runtime behind\n it drags React state and the page registry into the server bundle; the\n prefetch cache is a `Map` and a `fetch` call, inert until an event fires.\n */\n const prefetchHandlers = prefetchesOnInteraction\n ? {\n onMouseEnter: (event: MouseEvent<HTMLAnchorElement>): void => {\n elementProps.onMouseEnter?.(event);\n void prefetchPageData(url);\n },\n onFocus: (event: FocusEvent<HTMLAnchorElement>): void => {\n elementProps.onFocus?.(event);\n void prefetchPageData(url);\n },\n }\n : undefined;\n\n return createElement(\n Component,\n { ...elementProps, ...prefetchHandlers, target, rel, href: url, onClick: handleClick },\n children,\n );\n}\n"],"mappings":";;;;;;AA+IA,MAAM,oBAAoB;CAAC;CAAM;CAAQ;CAAS;AAAK;AAEvD,IAAa,gCAAb,cAAmD,MAAM;CACpB;CAAnC,AAAO,YAAY,AAAgB,eAAkC;EACnE,MACE,4BAA4B,cACzB,KAAI,SAAQ,KAAK,UAAU,IAAI,CAAC,EAChC,KAAK,OAAO,EAAE,mOAInB;EARiC;EASjC,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,cAAc;EACnB,MACE,gEAAgE,kBAAkB,KAChF,SAAQ,KAAK,UAAU,IAAI,CAC7B,EAAE,KAAK,IAAI,EAAE,2LAGf;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kCAAb,cAAqD,MAAM;CAEvC;CACA;CAFlB,AAAO,YACL,AAAgB,KAChB,AAAgB,eAChB;EACA,MACE,4BAA4B,cACzB,KAAI,SAAQ,KAAK,UAAU,IAAI,CAAC,EAChC,KAAK,OAAO,EAAE,8BAA8B,IAAI,6SAKrD;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,IAAa,+BAAb,cAAkD,MAAM;CACnB;CAAnC,AAAO,YAAY,AAAgB,WAAmB;EACpD,MACE,yCAAyC,KAAK,UAAU,SAAS,EAAE,6VAK9D,KAAK,UAAU,UAAU,QAAQ,QAAQ,EAAE,EAAE,QAAQ,OAAO,GAAG,KAAK,OAAO,EAAE,EACpF;EARiC;EASjC,KAAK,OAAO;CACd;AACF;;;;;;;;AAuBA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,aAAa,aAA8B;CAClD,OAAO,YAAY,WAAW,GAAG,KAAK,eAAe,KAAK,WAAW;AACvE;;;;;;;;;;;;AAaA,SAAS,iBAAiB,KAAsB;CAC9C,OAAO,IAAI,WAAW,GAAG,KAAK,CAAC,IAAI,WAAW,IAAI;AACpD;;;;;;;;;;AAWA,SAAS,oBAAoB,KAAmB;CAC9C,IAAI,gBAAgB,EAAE,SAAS,GAAG,GAAG,MAAM,IAAI,6BAA6B,GAAG;AACjF;AAEA,MAAM,uBAAuB,CAAC,UAAU,OAAO;AAE/C,SAAS,mBAAmB,OAA0C;CACpE,MAAM,WAAW,kBAAkB,QAAO,SAAQ,MAAM,UAAU,MAAS;CAE3E,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,8BAA8B,QAAQ;CAEzE,IAAI,SAAS,WAAW,GAAG,MAAM,IAAI,4BAA4B;CAEjE,IAAI,MAAM,UAAU,QAAW,OAAO;EAAE,KAAK,UAAU,MAAM;EAAS,SAAS;CAAM;CAErF,IAAI,MAAM,QAAQ,QAAW,OAAO;EAAE,KAAK,OAAO,MAAM;EAAO,SAAS;CAAM;CAE9E,MAAM,cAAe,MAAM,MAAM,MAAM;CAQvC,IAAI,aAAa,WAAW,GAAG;EAC7B,MAAM,iBAAiB,qBAAqB,QAAO,SAAQ,MAAM,UAAU,MAAS;EAEpF,IAAI,eAAe,SAAS,GAC1B,MAAM,IAAI,gCAAgC,aAAa,cAAc;EAGvE,oBAAoB,WAAW;EAE/B,OAAO;GAAE,KAAK;GAAa,SAAS,iBAAiB,WAAW;EAAE;CACpE;CASA,OAAO;EAAE,KAAK,KAAK,aAAa,MAAM,QAAQ,MAAM,KAAK;EAAG,SAAS;CAAK;AAC5E;;;;;;;;;;;;;;;;AAiBA,SAAS,iBAAiB,OAA+C;CACvE,OACE,MAAM,WAAW,KACjB,CAAC,MAAM,WACP,CAAC,MAAM,WACP,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM;AAEX;;;;;;AAOA,SAAS,oBAAoB,QAAqC;CAChE,OAAO,WAAW,UAAa,WAAW;AAC5C;AAEA,SAAgB,KAAK,EACnB,IACA,MAAM,WACN,OACA,KACA,QACA,OACA,QACA,UACA,WAAW,YAAY,KACvB,UACA,SACA,GAAG,gBACuB;CAC1B,MAAM,EAAE,KAAK,YAAY,mBAAmB;EAC1C;EACA,MAAM;EACN;EACA;EACA;EACA;CACF,CAAC;CAED,MAAM,SAAS,aAAa,WAAW,WAAW,OAAO,WAAW;CAKpE,MAAM,MACJ,aAAa,QAAQ,WAAW,WAAW,wBAAwB;CAErE,MAAM,eAAe,UAA+C;EAKlE,UAAU,KAAK;EAKf,IAAI,CAAC,WAAW,oBAAoB,MAAM,GAAG;EAE7C,IAAI,CAAC,iBAAiB,KAAK,GAAG;EAa9B,IAAI,iBAAiB,IAAI,GAAG,MAAM,MAAM;EAExC,MAAM,eAAe;CACvB;CA2BA,MAAM,mBAjBJ,aAAa,QAAQ,WAAW,CAAC,oBAAoB,MAAM,IAkBzD;EACE,eAAe,UAA+C;GAC5D,aAAa,eAAe,KAAK;GACjC,AAAK,iBAAiB,GAAG;EAC3B;EACA,UAAU,UAA+C;GACvD,aAAa,UAAU,KAAK;GAC5B,AAAK,iBAAiB,GAAG;EAC3B;CACF,IACA;CAEJ,OAAO,cACL,WACA;EAAE,GAAG;EAAc,GAAG;EAAkB;EAAQ;EAAK,MAAM;EAAK,SAAS;CAAY,GACrF,QACF;AACF"}
1
+ {"version":3,"file":"link.mjs","names":[],"sources":["../../../../../../../web/src/components/link.ts"],"sourcesContent":["import { createElement } from \"react\";\nimport type {\n AnchorHTMLAttributes,\n ComponentType,\n FocusEvent,\n MouseEvent,\n ReactElement,\n} from \"react\";\nimport { prefetchPageData } from \"../client/navigation/prefetch\";\nimport { currentNavigator } from \"../routing/navigator\";\nimport { href, knownRouteNames } from \"../routing/route-table\";\n\n/**\n * `<Link>` is SUGAR over `href()`, and deliberately thin.\n *\n * `href(name, params, query)` is the durable primitive — it serves emails,\n * redirects, `Location` headers and every non-React caller, none of which can\n * render a component. This file adds one thing to it: an anchor element.\n *\n * It renders a real `<a href>`. Client-side interception is a later slice of\n * the navigation runtime and lands here without changing this API, which is the\n * point of routing everything through `href` first: navigation becomes a\n * BEHAVIOUR change, not an API change.\n *\n * ── Parity with `@mongez/react-router` ───────────────────────────────────────\n * `href`, `newTab`, `email`, `tel`, `component` and `prefetch` are spelled\n * exactly as MRR spells them, so a component moved across keeps compiling.\n * `params` and `query` are ours and have no MRR equivalent: they pair with the\n * typed `href()` helper, which is what makes a route NAME — rather than a URL —\n * the thing a call site names.\n *\n * ── The semantic divergence this file bridges ────────────────────────────────\n * MRR's `to` is a PATH. Ours was a route NAME, and only a name — which meant a\n * component moved across from MRR compiled and then threw at render, because\n * `\"/products\"` is not the name of anything. The two packages disagreed about\n * what the most-used prop in either of them MEANS.\n *\n * Since 2026-08-24 (owner ruling) `to`/`href` accept BOTH, discriminated by\n * SHAPE — see {@link isLiteralUrl}. That is what makes MRR code portable, and\n * it costs nothing at a Warlock call site, because the two grammars cannot\n * collide: a route name never begins with `/` and never carries a `scheme:`.\n * The ruling RESTS on that, so this file asserts it rather than trusting it\n * ({@link RouteNameShapeCollisionError}).\n */\n\ntype AnchorProps = Omit<AnchorHTMLAttributes<HTMLAnchorElement>, \"href\">;\n\n/**\n * Where the link goes. Every field is documented here once; which COMBINATIONS\n * are legal is decided by {@link LinkDestination}.\n */\ntype LinkDestinationProps = {\n /**\n * A route NAME, or a literal URL — told apart by SHAPE.\n *\n * `\"products.details\"` is a NAME and is resolved through the route table. A\n * page that moves changes its URL and keeps its name, so every call site\n * survives the move; a dead name throws at render naming the routes that do\n * exist, rather than rendering an anchor that 404s. This is the form to\n * prefer, and the only one `params` and `query` apply to.\n *\n * `\"/pricing\"`, `\"https://stripe.com\"`, `\"mailto:sales@example.com\"` and any\n * other `scheme:` are LITERAL — passed through to the element untouched, with\n * no route lookup at all. An app links out, and a route name is not a thing\n * you can have for a page that is not yours.\n */\n to?: string;\n /**\n * An alias of {@link to}, for parity with `@mongez/react-router`. Identical\n * in every respect, including which shapes it accepts.\n */\n href?: string;\n /** Renders a `mailto:` link. Not an in-app navigation. */\n email?: string;\n /** Renders a `tel:` link. Not an in-app navigation. */\n tel?: string;\n /**\n * Values for the route's `:param` segments, e.g. `{ id }` for\n * `\"/products/:id\"`. Only meaningful with a route NAME.\n */\n params?: Record<string, unknown>;\n /**\n * Query string values; an `undefined` value is omitted. Only meaningful with\n * a route NAME.\n */\n query?: Record<string, unknown>;\n};\n\n/**\n * EXACTLY ONE destination, enforced by the type.\n *\n * The alternative — a documented precedence such as \"`to` wins over `href`\" —\n * is silent by construction: the losing prop goes on compiling and goes on\n * reading like it works at the call site, and the anchor points at the wrong\n * page. Refusing the pair costs a call site one edit and can never be\n * misread. The runtime refuses it as well, because a JavaScript caller and a\n * cast both get past this.\n */\ntype LinkDestination =\n | { to: string; href?: never; email?: never; tel?: never }\n | { href: string; to?: never; email?: never; tel?: never }\n | { email: string; to?: never; href?: never; tel?: never }\n | { tel: string; to?: never; href?: never; email?: never };\n\nexport type LinkProps = AnchorProps &\n LinkDestinationProps &\n LinkDestination & {\n /**\n * Open in a new browsing context: `target=\"_blank\"` plus the `rel` that\n * stops the opened page from reaching back through `window.opener`.\n *\n * A caller's own `target`/`rel` win — this only fills in what was not said.\n */\n newTab?: boolean;\n /**\n * Render as something other than `<a>` — a tag name or a component.\n *\n * It receives the resolved `href`, the click handler and every remaining\n * prop, so a design-system anchor keeps client-side navigation as long as\n * it spreads what it is given onto the element it renders.\n *\n * `ComponentType<any>` is MRR's signature, kept verbatim: the component is\n * the caller's and its props are unknowable from here.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component?: ComponentType<any> | string;\n /**\n * Fetch this page's data when the pointer or the keyboard reaches the link,\n * so the click that follows swaps without a round trip.\n *\n * A GUESS, and treated as one everywhere: it is never awaited, a failure is\n * silent, and the click behaves exactly as it would without it. Opt-in per\n * link rather than on by default, because every prefetch is a request the\n * user did not ask for and someone pays for the bandwidth.\n *\n * IGNORED for anything that is not an in-app navigation — an external URL,\n * `mailto:`, `tel:`, `newTab`, any explicit `target`. Prefetching those\n * would mean issuing a cross-origin request to a third party on hover,\n * which is not a thing a link component may decide to do.\n */\n prefetch?: boolean;\n };\n\nconst DESTINATION_PROPS = [\"to\", \"href\", \"email\", \"tel\"] as const;\n\nexport class AmbiguousLinkDestinationError extends Error {\n public constructor(public readonly providedProps: readonly string[]) {\n super(\n `Warlock <Link> was given ${providedProps\n .map(name => JSON.stringify(name))\n .join(\" and \")}, but a link goes to exactly one place. There is no ` +\n \"precedence between them on purpose: one of the two would silently win, and the \" +\n \"call site would go on naming a destination that never renders. Delete the one \" +\n \"you did not mean.\",\n );\n this.name = \"AmbiguousLinkDestinationError\";\n }\n}\n\nexport class MissingLinkDestinationError extends Error {\n public constructor() {\n super(\n `Warlock <Link> was given no destination. Pass exactly one of ${DESTINATION_PROPS.map(\n name => JSON.stringify(name),\n ).join(\", \")}. It is not defaulted to the current page: an anchor with an empty ` +\n \"`href` renders as a working link and reloads the page when clicked, which is a \" +\n \"harder fault to see than this message.\",\n );\n this.name = \"MissingLinkDestinationError\";\n }\n}\n\nexport class RouteArgumentsOnLiteralUrlError extends Error {\n public constructor(\n public readonly url: string,\n public readonly providedProps: readonly string[],\n ) {\n super(\n `Warlock <Link> was given ${providedProps\n .map(name => JSON.stringify(name))\n .join(\" and \")} alongside the literal URL \"${url}\". Those apply to a route NAME, ` +\n \"which is resolved through the route table; a literal URL is passed through exactly \" +\n \"as written, so they would have been dropped and the link would have pointed at an \" +\n \"unfiltered page that still looked right at the call site. Put the values in the URL, \" +\n \"or name the route.\",\n );\n this.name = \"RouteArgumentsOnLiteralUrlError\";\n }\n}\n\n/**\n * The ruling's one assumption, broken. See the module doc comment: telling a\n * literal URL from a route NAME by shape is only safe while no route is NAMED\n * like a URL, and nothing in the route pipeline validates a hand-declared\n * `route.name`. So the collision is checked at the one place it could do harm,\n * where it is a loud refusal instead of an anchor that silently points\n * somewhere else.\n */\nexport class RouteNameShapeCollisionError extends Error {\n public constructor(public readonly routeName: string) {\n super(\n `Warlock route table: a route is NAMED ${JSON.stringify(routeName)}, which is shaped ` +\n \"like a URL. <Link> tells a literal URL from a route name by shape — a destination \" +\n \"starting with `/` or carrying a `scheme:` is passed through untouched — so this name \" +\n \"can never be resolved, and every link to it would silently point at that path \" +\n \"instead. Rename the route (`route = { path, name }`) to a dotted name such as \" +\n `${JSON.stringify(routeName.replace(/^\\/+/, \"\").replace(/\\//g, \".\") || \"index\")}.`,\n );\n this.name = \"RouteNameShapeCollisionError\";\n }\n}\n\ntype Destination = {\n /** What lands on the element's `href`. */\n url: string;\n /**\n * Whether this URL is a page in THIS app — the only kind the client\n * navigation runtime may be asked about, and the only kind that may be\n * prefetched. `mailto:`, `tel:` and an external URL hand off to another\n * application or another origin entirely, so intercepting any of them would\n * break it, and speculatively fetching one would be a cross-origin request\n * the developer never asked for.\n */\n isInApp: boolean;\n};\n\n/**\n * Any RFC 3986 scheme — `https:`, `mailto:`, `tel:`, `whatsapp:`, an app's own\n * custom one. Matched generically rather than as a list of known schemes: a\n * list would silently resolve `bitcoin:...` through the route table, which is\n * the exact failure this ruling exists to remove, and it would have to grow\n * forever.\n */\nconst SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/i;\n\n/**\n * Whether this destination is a URL to be used as written, rather than a route\n * name to resolve.\n *\n * The whole discriminator, and deliberately the whole of it: two cheap shape\n * tests, no parsing, no matching. Anything more would be a SECOND route matcher\n * living beside the server's, which this codebase refuses everywhere it comes\n * up — a matcher that disagreed with the real one would produce links to pages\n * that do not exist.\n */\nfunction isLiteralUrl(destination: string): boolean {\n return destination.startsWith(\"/\") || SCHEME_PATTERN.test(destination);\n}\n\n/**\n * Whether a literal URL addresses THIS app.\n *\n * A path is ours. A `scheme:` is not — including `https:` to our own origin,\n * which would need `window.location` to recognise and would make the answer\n * depend on where the code is running. And `//host/path` is PROTOCOL-RELATIVE:\n * it starts with a slash and is nonetheless another origin, which is precisely\n * the case a \"starts with `/`\" test alone would hand to the navigator, where it\n * becomes a `pushState` to a foreign origin — a SecurityError — or a\n * speculative fetch of a third-party host.\n */\nfunction addressesThisApp(url: string): boolean {\n return url.startsWith(\"/\") && !url.startsWith(\"//\");\n}\n\n/**\n * Refuses the one table that would make {@link isLiteralUrl} wrong.\n *\n * Reached only for a destination already judged literal, so the cost is a scan\n * of the published names for links that were never going to hit the table\n * anyway — and zero for the route-name form, which is the common one. The right\n * permanent home for this is `publishRouteTable`, at boot, once (see the report\n * on this card).\n */\nfunction assertNotARouteName(url: string): void {\n if (knownRouteNames().includes(url)) throw new RouteNameShapeCollisionError(url);\n}\n\nconst ROUTE_ARGUMENT_PROPS = [\"params\", \"query\"] as const;\n\nfunction resolveDestination(props: LinkDestinationProps): Destination {\n const provided = DESTINATION_PROPS.filter(name => props[name] !== undefined);\n\n if (provided.length > 1) throw new AmbiguousLinkDestinationError(provided);\n\n if (provided.length === 0) throw new MissingLinkDestinationError();\n\n if (props.email !== undefined) return { url: `mailto:${props.email}`, isInApp: false };\n\n if (props.tel !== undefined) return { url: `tel:${props.tel}`, isInApp: false };\n\n const destination = (props.to ?? props.href) as string;\n\n /*\n LITERAL: `/pricing`, `https://stripe.com`, `mailto:…`, `whatsapp://…`. It\n goes to the element exactly as written and the route table is never\n consulted — there is nothing to look up, and looking anyway is what used to\n throw `UnknownRouteNameError` on every link out of the application.\n */\n if (isLiteralUrl(destination)) {\n const routeArguments = ROUTE_ARGUMENT_PROPS.filter(name => props[name] !== undefined);\n\n if (routeArguments.length > 0) {\n throw new RouteArgumentsOnLiteralUrlError(destination, routeArguments);\n }\n\n assertNotARouteName(destination);\n\n return { url: destination, isInApp: addressesThisApp(destination) };\n }\n\n /*\n A NAME, resolved against the route table published at boot from the SAME\n discovery result the server registered its routes from. The previous version\n of this file restated six URLs in a literal map, so linking to any seventh\n page in the application threw — the map was the limit on what could be\n linked, and nothing said so at the call site.\n */\n return { url: href(destination, props.params, props.query), isInApp: true };\n}\n\n/**\n * Whether this click should be left entirely to the browser.\n *\n * Every case here is a click that MEANS something other than \"go there in this\n * tab\", and intercepting any of them would take away behaviour the user\n * explicitly asked for:\n *\n * - a modifier or middle button: open in a new tab/window, or download\n * - `download`: save the resource, do not render it\n * - already prevented: something upstream in the tree handled this click\n *\n * Left button with no modifiers is the only click that means plain navigation.\n * The `target` case is decided before this, from the RESOLVED target, because\n * `newTab` sets it after the caller's props are read.\n */\nfunction isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>): boolean {\n return (\n event.button === 0 &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey &&\n !event.altKey &&\n !event.defaultPrevented\n );\n}\n\n/**\n * A target other than `_self` names ANOTHER browsing context — `_blank`, but\n * also `_parent`, `_top` and any named frame. Client navigation rewrites the\n * history of THIS one, so none of them are ours to intercept.\n */\nfunction opensAnotherContext(target: string | undefined): boolean {\n return target !== undefined && target !== \"_self\";\n}\n\nexport function Link({\n to,\n href: hrefAlias,\n email,\n tel,\n params,\n query,\n newTab,\n prefetch,\n component: Component = \"a\",\n children,\n onClick,\n ...elementProps\n}: LinkProps): ReactElement {\n const { url, isInApp } = resolveDestination({\n to,\n href: hrefAlias,\n email,\n tel,\n params,\n query,\n });\n\n const target = elementProps.target ?? (newTab === true ? \"_blank\" : undefined);\n\n // Only a DEFAULT: a caller that wrote its own `rel` (`\"me noopener\"`,\n // `\"external\"`) meant it, and overwriting it would delete a value the page\n // depends on to say something this component knows nothing about.\n const rel =\n elementProps.rel ?? (target === \"_blank\" ? \"noopener noreferrer\" : undefined);\n\n const handleClick = (event: MouseEvent<HTMLAnchorElement>): void => {\n // The caller's handler runs FIRST and unconditionally — it may be doing\n // analytics, closing a menu, or calling `preventDefault()` to veto the\n // navigation outright. Deciding before it ran would let this component\n // navigate away from a click the application had already cancelled.\n onClick?.(event);\n\n // `mailto:`, `tel:` and anything aimed at another browsing context leave\n // this page standing. The runtime is not consulted at all — asking it would\n // spend a page-data fetch on a click that was never going to navigate here.\n if (!isInApp || opensAnotherContext(target)) return;\n\n if (!isPlainLeftClick(event)) return;\n\n /*\n Asked for per click, never captured at render: the runtime registers\n itself when the hydration bundle mounts, which is AFTER the first render\n of every anchor on the page. A value read at render time would be\n `undefined` forever for exactly the links present at hydration — that is,\n all of them.\n\n Absent (server render, or before hydration) the anchor is left alone and\n does what an anchor does. That is the whole progressive-enhancement story:\n links work before this code runs, and work better after.\n */\n if (currentNavigator()?.(url) !== true) return;\n\n event.preventDefault();\n };\n\n /*\n The SAME gate the click uses, asked before any speculative request exists:\n only a destination this app would have navigated to itself may be fetched\n ahead of time. `mailto:`, `tel:`, an external URL and anything aimed at\n another browsing context are all clicks that leave this page, and none of\n them has page data to fetch.\n */\n const prefetchesOnInteraction =\n prefetch === true && isInApp && !opensAnotherContext(target);\n\n /*\n Attached ONLY when prefetching — a link without the prop keeps whatever\n handlers the caller passed, on the element, unwrapped.\n\n Hover AND focus, because a keyboard user never generates the first one and\n would otherwise be the only visitor who never gets the optimisation.\n\n Fire-and-forget by construction: `prefetchPageData` never rejects and is\n never awaited, so nothing here can delay the event or surface a failure. It\n is also safe to reach on the server — it no-ops without a browser — which is\n why this file can import it directly rather than through a `connect*` seam\n like the navigator's. The navigator needs a seam because the runtime behind\n it drags React state and the page registry into the server bundle; the\n prefetch cache is a `Map` and a `fetch` call, inert until an event fires.\n */\n const prefetchHandlers = prefetchesOnInteraction\n ? {\n onMouseEnter: (event: MouseEvent<HTMLAnchorElement>): void => {\n elementProps.onMouseEnter?.(event);\n void prefetchPageData(url);\n },\n onFocus: (event: FocusEvent<HTMLAnchorElement>): void => {\n elementProps.onFocus?.(event);\n void prefetchPageData(url);\n },\n }\n : undefined;\n\n return createElement(\n Component,\n { ...elementProps, ...prefetchHandlers, target, rel, href: url, onClick: handleClick },\n children,\n );\n}\n"],"mappings":";;;;;;AA+IA,MAAM,oBAAoB;CAAC;CAAM;CAAQ;CAAS;AAAK;AAEvD,IAAa,gCAAb,cAAmD,MAAM;CACpB;CAAnC,AAAO,YAAY,AAAgB,eAAkC;EACnE,MACE,4BAA4B,cACzB,KAAI,SAAQ,KAAK,UAAU,IAAI,CAAC,CAAC,CACjC,KAAK,OAAO,EAAE,mOAInB;EARiC;EASjC,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD,AAAO,cAAc;EACnB,MACE,gEAAgE,kBAAkB,KAChF,SAAQ,KAAK,UAAU,IAAI,CAC7B,CAAC,CAAC,KAAK,IAAI,EAAE,2LAGf;EACA,KAAK,OAAO;CACd;AACF;AAEA,IAAa,kCAAb,cAAqD,MAAM;CAEvC;CACA;CAFlB,AAAO,YACL,AAAgB,KAChB,AAAgB,eAChB;EACA,MACE,4BAA4B,cACzB,KAAI,SAAQ,KAAK,UAAU,IAAI,CAAC,CAAC,CACjC,KAAK,OAAO,EAAE,8BAA8B,IAAI,6SAKrD;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,IAAa,+BAAb,cAAkD,MAAM;CACnB;CAAnC,AAAO,YAAY,AAAgB,WAAmB;EACpD,MACE,yCAAyC,KAAK,UAAU,SAAS,EAAE,6VAK9D,KAAK,UAAU,UAAU,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,OAAO,GAAG,KAAK,OAAO,EAAE,EACpF;EARiC;EASjC,KAAK,OAAO;CACd;AACF;;;;;;;;AAuBA,MAAM,iBAAiB;;;;;;;;;;;AAYvB,SAAS,aAAa,aAA8B;CAClD,OAAO,YAAY,WAAW,GAAG,KAAK,eAAe,KAAK,WAAW;AACvE;;;;;;;;;;;;AAaA,SAAS,iBAAiB,KAAsB;CAC9C,OAAO,IAAI,WAAW,GAAG,KAAK,CAAC,IAAI,WAAW,IAAI;AACpD;;;;;;;;;;AAWA,SAAS,oBAAoB,KAAmB;CAC9C,IAAI,gBAAgB,CAAC,CAAC,SAAS,GAAG,GAAG,MAAM,IAAI,6BAA6B,GAAG;AACjF;AAEA,MAAM,uBAAuB,CAAC,UAAU,OAAO;AAE/C,SAAS,mBAAmB,OAA0C;CACpE,MAAM,WAAW,kBAAkB,QAAO,SAAQ,MAAM,UAAU,MAAS;CAE3E,IAAI,SAAS,SAAS,GAAG,MAAM,IAAI,8BAA8B,QAAQ;CAEzE,IAAI,SAAS,WAAW,GAAG,MAAM,IAAI,4BAA4B;CAEjE,IAAI,MAAM,UAAU,QAAW,OAAO;EAAE,KAAK,UAAU,MAAM;EAAS,SAAS;CAAM;CAErF,IAAI,MAAM,QAAQ,QAAW,OAAO;EAAE,KAAK,OAAO,MAAM;EAAO,SAAS;CAAM;CAE9E,MAAM,cAAe,MAAM,MAAM,MAAM;CAQvC,IAAI,aAAa,WAAW,GAAG;EAC7B,MAAM,iBAAiB,qBAAqB,QAAO,SAAQ,MAAM,UAAU,MAAS;EAEpF,IAAI,eAAe,SAAS,GAC1B,MAAM,IAAI,gCAAgC,aAAa,cAAc;EAGvE,oBAAoB,WAAW;EAE/B,OAAO;GAAE,KAAK;GAAa,SAAS,iBAAiB,WAAW;EAAE;CACpE;CASA,OAAO;EAAE,KAAK,KAAK,aAAa,MAAM,QAAQ,MAAM,KAAK;EAAG,SAAS;CAAK;AAC5E;;;;;;;;;;;;;;;;AAiBA,SAAS,iBAAiB,OAA+C;CACvE,OACE,MAAM,WAAW,KACjB,CAAC,MAAM,WACP,CAAC,MAAM,WACP,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM;AAEX;;;;;;AAOA,SAAS,oBAAoB,QAAqC;CAChE,OAAO,WAAW,UAAa,WAAW;AAC5C;AAEA,SAAgB,KAAK,EACnB,IACA,MAAM,WACN,OACA,KACA,QACA,OACA,QACA,UACA,WAAW,YAAY,KACvB,UACA,SACA,GAAG,gBACuB;CAC1B,MAAM,EAAE,KAAK,YAAY,mBAAmB;EAC1C;EACA,MAAM;EACN;EACA;EACA;EACA;CACF,CAAC;CAED,MAAM,SAAS,aAAa,WAAW,WAAW,OAAO,WAAW;CAKpE,MAAM,MACJ,aAAa,QAAQ,WAAW,WAAW,wBAAwB;CAErE,MAAM,eAAe,UAA+C;EAKlE,UAAU,KAAK;EAKf,IAAI,CAAC,WAAW,oBAAoB,MAAM,GAAG;EAE7C,IAAI,CAAC,iBAAiB,KAAK,GAAG;EAa9B,IAAI,iBAAiB,CAAC,GAAG,GAAG,MAAM,MAAM;EAExC,MAAM,eAAe;CACvB;CA2BA,MAAM,mBAjBJ,aAAa,QAAQ,WAAW,CAAC,oBAAoB,MAAM,IAkBzD;EACE,eAAe,UAA+C;GAC5D,aAAa,eAAe,KAAK;GACjC,AAAK,iBAAiB,GAAG;EAC3B;EACA,UAAU,UAA+C;GACvD,aAAa,UAAU,KAAK;GAC5B,AAAK,iBAAiB,GAAG;EAC3B;CACF,IACA;CAEJ,OAAO,cACL,WACA;EAAE,GAAG;EAAc,GAAG;EAAkB;EAAQ;EAAK,MAAM;EAAK,SAAS;CAAY,GACrF,QACF;AACF"}
@@ -12,7 +12,8 @@ const REQUIRED_PAYLOAD_KEYS = [
12
12
  "layoutData",
13
13
  "pageData",
14
14
  "shared",
15
- "name"
15
+ "name",
16
+ "locale"
16
17
  ];
17
18
  const ABSENT_PAYLOAD_MESSAGE = `Warlock hydration payload is absent: #${PAYLOAD_SCRIPT_ID}, owned by web/src/components/document-context.ts, was not found.`;
18
19
  const MALFORMED_PAYLOAD_MESSAGE = `Warlock hydration payload was found at #${PAYLOAD_SCRIPT_ID} but could not be read.`;
@@ -67,6 +68,9 @@ function requireErrorPagePayload(value) {
67
68
  function requireHydrationPayload(value) {
68
69
  if (!isPlainObject(value)) malformedPayload();
69
70
  for (const key of REQUIRED_PAYLOAD_KEYS) if (!Object.prototype.hasOwnProperty.call(value, key)) malformedPayload();
71
+ if (typeof value.name !== "string") malformedPayload();
72
+ const locale = value.locale;
73
+ if (typeof locale !== "string" || locale.length === 0) malformedPayload();
70
74
  for (const key of OPTIONAL_OBJECT_PAYLOAD_KEYS) {
71
75
  const optional = value[key];
72
76
  if (optional !== void 0 && !isPlainObject(optional)) malformedPayload();
@@ -78,7 +82,7 @@ function requireHydrationPayload(value) {
78
82
  /**
79
83
  * Read the fixed payload script without changing the server-rendered root.
80
84
  *
81
- * Extra fields are ignored. The gate owns the FIVE required keys — absent or
85
+ * Extra fields are ignored. The gate owns the SIX required keys — absent or
82
86
  * malformed, both throw — plus a shape check on the three optional ones
83
87
  * ({@link OPTIONAL_OBJECT_PAYLOAD_KEYS}); it deliberately does not require
84
88
  * those to be present. `errorPage`, when present, is additionally validated as
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-payload.mjs","names":[],"sources":["../../../../../../web/src/hydration-payload.ts"],"sourcesContent":["import {\n PAYLOAD_SCRIPT_ID,\n type HydrationDocumentPayloadSource,\n} from \"./components/document-context\";\n\nexport type { HydrationDocumentPayloadSource } from \"./components/document-context\";\nexport type {\n ErrorPageProps,\n SerializedErrorPageProps,\n SerializedPageError,\n} from \"./components/document-context\";\n\n/**\n * Exported so a payload-shape assertion can be written against the contract\n * itself. A spec that hardcodes its own copy of this list silently becomes a\n * claim about a PAST revision — that is exactly how the rev. 3 keys landed with\n * two specs still asserting the rev. 2 shape.\n */\nexport const REQUIRED_PAYLOAD_KEYS = [\n \"appData\",\n \"layoutData\",\n \"pageData\",\n \"shared\",\n \"name\",\n] as const;\n\nconst ABSENT_PAYLOAD_MESSAGE =\n `Warlock hydration payload is absent: #${PAYLOAD_SCRIPT_ID}, owned by ` +\n \"web/src/components/document-context.ts, was not found.\";\nconst MALFORMED_PAYLOAD_MESSAGE =\n `Warlock hydration payload was found at #${PAYLOAD_SCRIPT_ID} but could not be read.`;\n\nfunction malformedPayload(): never {\n throw new Error(MALFORMED_PAYLOAD_MESSAGE);\n}\n\n/**\n * The keys that are allowed to be ABSENT but not allowed to be wrong.\n *\n * `metadata`, `params` and `errorPage` are optional because the server is right\n * always produce them — a page with no `metadata` export resolves none, and a\n * older payload carries none of these additions. Failing a whole page over an\n * absent accessor would turn a compatible payload into a blank screen, so\n * absence is accepted.\n *\n * Present-but-not-an-object is a different claim entirely: it means something\n * produced a payload with these names meaning something else, and every reader\n * downstream would then be indexing a string. That is MALFORMED under the same\n * rule the required keys live by, so it throws. Arrays included — `typeof []`\n * is `\"object\"`, and an array of params is not params.\n */\nexport const OPTIONAL_OBJECT_PAYLOAD_KEYS = [\"metadata\", \"params\", \"errorPage\"] as const;\n\nfunction isPlainObject(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactStringKeys(\n value: Record<PropertyKey, unknown>,\n required: readonly string[],\n optional: readonly string[] = [],\n): boolean {\n const allowed = new Set([...required, ...optional]);\n const keys = Reflect.ownKeys(value);\n\n return (\n required.every((key) => Object.prototype.hasOwnProperty.call(value, key)) &&\n keys.every((key) => typeof key === \"string\" && allowed.has(key))\n );\n}\n\n/**\n * Validate the explicit serialization boundary, not an `Error` instance.\n * `JSON.stringify(new Error(\"boom\"))` is normally `{}` because its useful\n * fields are non-enumerable; accepting that would hydrate an error page with a\n * different contract from the one the server rendered.\n */\nfunction requireErrorPagePayload(value: unknown): void {\n if (!isPlainObject(value)) malformedPayload();\n\n const errorPage = value as Record<PropertyKey, unknown>;\n\n if (!hasExactStringKeys(errorPage, [\"error\", \"status\"])) malformedPayload();\n if (!isPlainObject(errorPage.error)) malformedPayload();\n\n const error = errorPage.error as Record<PropertyKey, unknown>;\n\n if (!hasExactStringKeys(error, [\"name\", \"message\"], [\"stack\"])) malformedPayload();\n if (typeof error.name !== \"string\" || typeof error.message !== \"string\") {\n malformedPayload();\n }\n if (error.stack !== undefined && typeof error.stack !== \"string\") malformedPayload();\n\n if (\n typeof errorPage.status !== \"number\" ||\n !Number.isInteger(errorPage.status) ||\n errorPage.status < 500 ||\n errorPage.status > 599\n ) {\n malformedPayload();\n }\n}\n\nfunction requireHydrationPayload(value: unknown): HydrationDocumentPayloadSource {\n if (!isPlainObject(value)) malformedPayload();\n\n for (const key of REQUIRED_PAYLOAD_KEYS) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) malformedPayload();\n }\n\n for (const key of OPTIONAL_OBJECT_PAYLOAD_KEYS) {\n const optional = (value as Record<string, unknown>)[key];\n\n if (optional !== undefined && !isPlainObject(optional)) malformedPayload();\n }\n\n const errorPage = (value as Record<string, unknown>).errorPage;\n if (errorPage !== undefined) requireErrorPagePayload(errorPage);\n\n return value as HydrationDocumentPayloadSource;\n}\n\n/**\n * Read the fixed payload script without changing the server-rendered root.\n *\n * Extra fields are ignored. The gate owns the FIVE required keys — absent or\n * malformed, both throw — plus a shape check on the three optional ones\n * ({@link OPTIONAL_OBJECT_PAYLOAD_KEYS}); it deliberately does not require\n * those to be present. `errorPage`, when present, is additionally validated as\n * one atomic `{ error, status }` selection with a serialized error and a 5xx.\n */\nexport function readHydrationPayload(documentNode: Document): HydrationDocumentPayloadSource {\n const element = documentNode.getElementById(PAYLOAD_SCRIPT_ID);\n\n if (element === null) throw new Error(ABSENT_PAYLOAD_MESSAGE);\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(element.textContent ?? \"\");\n } catch {\n malformedPayload();\n }\n\n return requireHydrationPayload(parsed);\n}\n"],"mappings":";;;;;;;;;AAkBA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,yBACJ,yCAAyC,kBAAkB;AAE7D,MAAM,4BACJ,2CAA2C,kBAAkB;AAE/D,SAAS,mBAA0B;CACjC,MAAM,IAAI,MAAM,yBAAyB;AAC3C;;;;;;;;;;;;;;;;AAiBA,MAAa,+BAA+B;CAAC;CAAY;CAAU;AAAW;AAE9E,SAAS,cAAc,OAAyB;CAC9C,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,mBACP,OACA,UACA,WAA8B,CAAC,GACtB;CACT,MAAM,UAAU,IAAI,IAAI,CAAC,GAAG,UAAU,GAAG,QAAQ,CAAC;CAClD,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAElC,OACE,SAAS,OAAO,QAAQ,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,CAAC,KACxE,KAAK,OAAO,QAAQ,OAAO,QAAQ,YAAY,QAAQ,IAAI,GAAG,CAAC;AAEnE;;;;;;;AAQA,SAAS,wBAAwB,OAAsB;CACrD,IAAI,CAAC,cAAc,KAAK,GAAG,iBAAiB;CAE5C,MAAM,YAAY;CAElB,IAAI,CAAC,mBAAmB,WAAW,CAAC,SAAS,QAAQ,CAAC,GAAG,iBAAiB;CAC1E,IAAI,CAAC,cAAc,UAAU,KAAK,GAAG,iBAAiB;CAEtD,MAAM,QAAQ,UAAU;CAExB,IAAI,CAAC,mBAAmB,OAAO,CAAC,QAAQ,SAAS,GAAG,CAAC,OAAO,CAAC,GAAG,iBAAiB;CACjF,IAAI,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,YAAY,UAC7D,iBAAiB;CAEnB,IAAI,MAAM,UAAU,UAAa,OAAO,MAAM,UAAU,UAAU,iBAAiB;CAEnF,IACE,OAAO,UAAU,WAAW,YAC5B,CAAC,OAAO,UAAU,UAAU,MAAM,KAClC,UAAU,SAAS,OACnB,UAAU,SAAS,KAEnB,iBAAiB;AAErB;AAEA,SAAS,wBAAwB,OAAgD;CAC/E,IAAI,CAAC,cAAc,KAAK,GAAG,iBAAiB;CAE5C,KAAK,MAAM,OAAO,uBAChB,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,GAAG,iBAAiB;CAG1E,KAAK,MAAM,OAAO,8BAA8B;EAC9C,MAAM,WAAY,MAAkC;EAEpD,IAAI,aAAa,UAAa,CAAC,cAAc,QAAQ,GAAG,iBAAiB;CAC3E;CAEA,MAAM,YAAa,MAAkC;CACrD,IAAI,cAAc,QAAW,wBAAwB,SAAS;CAE9D,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,qBAAqB,cAAwD;CAC3F,MAAM,UAAU,aAAa,eAAe,iBAAiB;CAE7D,IAAI,YAAY,MAAM,MAAM,IAAI,MAAM,sBAAsB;CAE5D,IAAI;CAEJ,IAAI;EACF,SAAS,KAAK,MAAM,QAAQ,eAAe,EAAE;CAC/C,QAAQ;EACN,iBAAiB;CACnB;CAEA,OAAO,wBAAwB,MAAM;AACvC"}
1
+ {"version":3,"file":"hydration-payload.mjs","names":[],"sources":["../../../../../../web/src/hydration-payload.ts"],"sourcesContent":["import {\n PAYLOAD_SCRIPT_ID,\n type HydrationDocumentPayloadSource,\n} from \"./components/document-context\";\n\nexport type { HydrationDocumentPayloadSource } from \"./components/document-context\";\nexport type {\n ErrorPageProps,\n SerializedErrorPageProps,\n SerializedPageError,\n} from \"./components/document-context\";\n\n/**\n * Exported so a payload-shape assertion can be written against the contract\n * itself. A spec that hardcodes its own copy of this list silently becomes a\n * claim about a PAST revision — that is exactly how the rev. 3 keys landed with\n * two specs still asserting the rev. 2 shape.\n */\nexport const REQUIRED_PAYLOAD_KEYS = [\n \"appData\",\n \"layoutData\",\n \"pageData\",\n \"shared\",\n \"name\",\n \"locale\",\n] as const;\n\nconst ABSENT_PAYLOAD_MESSAGE =\n `Warlock hydration payload is absent: #${PAYLOAD_SCRIPT_ID}, owned by ` +\n \"web/src/components/document-context.ts, was not found.\";\nconst MALFORMED_PAYLOAD_MESSAGE =\n `Warlock hydration payload was found at #${PAYLOAD_SCRIPT_ID} but could not be read.`;\n\nfunction malformedPayload(): never {\n throw new Error(MALFORMED_PAYLOAD_MESSAGE);\n}\n\n/**\n * The keys that are allowed to be ABSENT but not allowed to be wrong.\n *\n * `metadata`, `params` and `errorPage` are optional because the server is right\n * always produce them — a page with no `metadata` export resolves none, and a\n * older payload carries none of these additions. Failing a whole page over an\n * absent accessor would turn a compatible payload into a blank screen, so\n * absence is accepted.\n *\n * Present-but-not-an-object is a different claim entirely: it means something\n * produced a payload with these names meaning something else, and every reader\n * downstream would then be indexing a string. That is MALFORMED under the same\n * rule the required keys live by, so it throws. Arrays included — `typeof []`\n * is `\"object\"`, and an array of params is not params.\n */\nexport const OPTIONAL_OBJECT_PAYLOAD_KEYS = [\"metadata\", \"params\", \"errorPage\"] as const;\n\nfunction isPlainObject(value: unknown): boolean {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction hasExactStringKeys(\n value: Record<PropertyKey, unknown>,\n required: readonly string[],\n optional: readonly string[] = [],\n): boolean {\n const allowed = new Set([...required, ...optional]);\n const keys = Reflect.ownKeys(value);\n\n return (\n required.every((key) => Object.prototype.hasOwnProperty.call(value, key)) &&\n keys.every((key) => typeof key === \"string\" && allowed.has(key))\n );\n}\n\n/**\n * Validate the explicit serialization boundary, not an `Error` instance.\n * `JSON.stringify(new Error(\"boom\"))` is normally `{}` because its useful\n * fields are non-enumerable; accepting that would hydrate an error page with a\n * different contract from the one the server rendered.\n */\nfunction requireErrorPagePayload(value: unknown): void {\n if (!isPlainObject(value)) malformedPayload();\n\n const errorPage = value as Record<PropertyKey, unknown>;\n\n if (!hasExactStringKeys(errorPage, [\"error\", \"status\"])) malformedPayload();\n if (!isPlainObject(errorPage.error)) malformedPayload();\n\n const error = errorPage.error as Record<PropertyKey, unknown>;\n\n if (!hasExactStringKeys(error, [\"name\", \"message\"], [\"stack\"])) malformedPayload();\n if (typeof error.name !== \"string\" || typeof error.message !== \"string\") {\n malformedPayload();\n }\n if (error.stack !== undefined && typeof error.stack !== \"string\") malformedPayload();\n\n if (\n typeof errorPage.status !== \"number\" ||\n !Number.isInteger(errorPage.status) ||\n errorPage.status < 500 ||\n errorPage.status > 599\n ) {\n malformedPayload();\n }\n}\n\nfunction requireHydrationPayload(value: unknown): HydrationDocumentPayloadSource {\n if (!isPlainObject(value)) malformedPayload();\n\n for (const key of REQUIRED_PAYLOAD_KEYS) {\n if (!Object.prototype.hasOwnProperty.call(value, key)) malformedPayload();\n }\n\n if (typeof (value as Record<string, unknown>).name !== \"string\") malformedPayload();\n const locale = (value as Record<string, unknown>).locale;\n if (typeof locale !== \"string\" || locale.length === 0) malformedPayload();\n\n for (const key of OPTIONAL_OBJECT_PAYLOAD_KEYS) {\n const optional = (value as Record<string, unknown>)[key];\n\n if (optional !== undefined && !isPlainObject(optional)) malformedPayload();\n }\n\n const errorPage = (value as Record<string, unknown>).errorPage;\n if (errorPage !== undefined) requireErrorPagePayload(errorPage);\n\n return value as HydrationDocumentPayloadSource;\n}\n\n/**\n * Read the fixed payload script without changing the server-rendered root.\n *\n * Extra fields are ignored. The gate owns the SIX required keys — absent or\n * malformed, both throw — plus a shape check on the three optional ones\n * ({@link OPTIONAL_OBJECT_PAYLOAD_KEYS}); it deliberately does not require\n * those to be present. `errorPage`, when present, is additionally validated as\n * one atomic `{ error, status }` selection with a serialized error and a 5xx.\n */\nexport function readHydrationPayload(documentNode: Document): HydrationDocumentPayloadSource {\n const element = documentNode.getElementById(PAYLOAD_SCRIPT_ID);\n\n if (element === null) throw new Error(ABSENT_PAYLOAD_MESSAGE);\n\n let parsed: unknown;\n\n try {\n parsed = JSON.parse(element.textContent ?? \"\");\n } catch {\n malformedPayload();\n }\n\n return requireHydrationPayload(parsed);\n}\n"],"mappings":";;;;;;;;;AAkBA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,yBACJ,yCAAyC,kBAAkB;AAE7D,MAAM,4BACJ,2CAA2C,kBAAkB;AAE/D,SAAS,mBAA0B;CACjC,MAAM,IAAI,MAAM,yBAAyB;AAC3C;;;;;;;;;;;;;;;;AAiBA,MAAa,+BAA+B;CAAC;CAAY;CAAU;AAAW;AAE9E,SAAS,cAAc,OAAyB;CAC9C,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,mBACP,OACA,UACA,WAA8B,CAAC,GACtB;CACT,MAAM,UAAU,IAAI,IAAI,CAAC,GAAG,UAAU,GAAG,QAAQ,CAAC;CAClD,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAElC,OACE,SAAS,OAAO,QAAQ,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,CAAC,KACxE,KAAK,OAAO,QAAQ,OAAO,QAAQ,YAAY,QAAQ,IAAI,GAAG,CAAC;AAEnE;;;;;;;AAQA,SAAS,wBAAwB,OAAsB;CACrD,IAAI,CAAC,cAAc,KAAK,GAAG,iBAAiB;CAE5C,MAAM,YAAY;CAElB,IAAI,CAAC,mBAAmB,WAAW,CAAC,SAAS,QAAQ,CAAC,GAAG,iBAAiB;CAC1E,IAAI,CAAC,cAAc,UAAU,KAAK,GAAG,iBAAiB;CAEtD,MAAM,QAAQ,UAAU;CAExB,IAAI,CAAC,mBAAmB,OAAO,CAAC,QAAQ,SAAS,GAAG,CAAC,OAAO,CAAC,GAAG,iBAAiB;CACjF,IAAI,OAAO,MAAM,SAAS,YAAY,OAAO,MAAM,YAAY,UAC7D,iBAAiB;CAEnB,IAAI,MAAM,UAAU,UAAa,OAAO,MAAM,UAAU,UAAU,iBAAiB;CAEnF,IACE,OAAO,UAAU,WAAW,YAC5B,CAAC,OAAO,UAAU,UAAU,MAAM,KAClC,UAAU,SAAS,OACnB,UAAU,SAAS,KAEnB,iBAAiB;AAErB;AAEA,SAAS,wBAAwB,OAAgD;CAC/E,IAAI,CAAC,cAAc,KAAK,GAAG,iBAAiB;CAE5C,KAAK,MAAM,OAAO,uBAChB,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,GAAG,GAAG,iBAAiB;CAG1E,IAAI,OAAQ,MAAkC,SAAS,UAAU,iBAAiB;CAClF,MAAM,SAAU,MAAkC;CAClD,IAAI,OAAO,WAAW,YAAY,OAAO,WAAW,GAAG,iBAAiB;CAExE,KAAK,MAAM,OAAO,8BAA8B;EAC9C,MAAM,WAAY,MAAkC;EAEpD,IAAI,aAAa,UAAa,CAAC,cAAc,QAAQ,GAAG,iBAAiB;CAC3E;CAEA,MAAM,YAAa,MAAkC;CACrD,IAAI,cAAc,QAAW,wBAAwB,SAAS;CAE9D,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,qBAAqB,cAAwD;CAC3F,MAAM,UAAU,aAAa,eAAe,iBAAiB;CAE7D,IAAI,YAAY,MAAM,MAAM,IAAI,MAAM,sBAAsB;CAE5D,IAAI;CAEJ,IAAI;EACF,SAAS,KAAK,MAAM,QAAQ,eAAe,EAAE;CAC/C,QAAQ;EACN,iBAAiB;CACnB;CAEA,OAAO,wBAAwB,MAAM;AACvC"}
package/esm/index.d.mts CHANGED
@@ -4,6 +4,7 @@ import { AppProps, LayoutProps, PageProps } from "./props.mjs";
4
4
  import { PageMetadata } from "./metadata.mjs";
5
5
  import { ErrorPageProps, SerializedErrorPageProps, SerializedPageError } from "./components/document-context.mjs";
6
6
  import { shared, useShared } from "./shared.mjs";
7
+ import { LocaleProvider, LocaleProviderProps, Translate, useLocale, useTrans } from "./localization.mjs";
7
8
  import { QueryStringInput, QueryStringLeaf, QueryStringNested, QueryStringObject, QueryStringOptions, QueryStringValue, RepeatedKeyStrategy, UnserializableQueryValueError, queryString, queryStringOf, resetQueryStringOptions, setQueryStringOptions } from "./routing/query-string.mjs";
8
9
  import { RouteParameters, RouteQuery, href } from "./routing/route-table.mjs";
9
10
  import { Link } from "./components/link.mjs";
@@ -32,5 +33,6 @@ import { Scripts } from "./components/scripts.mjs";
32
33
  */
33
34
  interface SharedContext {}
34
35
  //#endregion
35
- export { type AppLoader, type AppProps, type ErrorPageProps, Head, type HttpContext, type LayoutLoader, type LayoutProps, Link, type MatchedRoute, type NavigationEndPayload, type NavigationErrorPayload, type NavigationStartPayload, type PageContext, type PageLoader, type PageMetadata, type PageProps, type QueryStringInput, type QueryStringLeaf, type QueryStringNested, type QueryStringObject, type QueryStringOptions, type QueryStringValue, type RepeatedKeyStrategy, type RouteParameters, type RouteQuery, Scripts, type SerializedErrorPageProps, type SerializedPageError, SharedContext, UnserializableQueryValueError, createRouterEvents, currentRoute, getHash, href, navigateBack, navigateTo, previousRoute, queryString, queryStringOf, refresh, resetQueryStringOptions, routerEvents, setQueryStringOptions, shared, useShared };
36
- //# sourceMappingURL=index.d.mts.map
36
+ export { type AppLoader, type AppProps, type ErrorPageProps, Head, type HttpContext, type LayoutLoader, type LayoutProps, Link, LocaleProvider, type LocaleProviderProps, type MatchedRoute, type NavigationEndPayload, type NavigationErrorPayload, type NavigationStartPayload, type PageContext, type PageLoader, type PageMetadata, type PageProps, type QueryStringInput, type QueryStringLeaf, type QueryStringNested, type QueryStringObject, type QueryStringOptions, type QueryStringValue, type RepeatedKeyStrategy, type RouteParameters, type RouteQuery, Scripts, type SerializedErrorPageProps, type SerializedPageError, SharedContext, type Translate, UnserializableQueryValueError, createRouterEvents, currentRoute, getHash, href, navigateBack, navigateTo, previousRoute, queryString, queryStringOf, refresh, resetQueryStringOptions, routerEvents, setQueryStringOptions, shared, useLocale, useShared, useTrans };
37
+ //# sourceMappingURL=index.d.mts.map
38
+ import "./server/create-page-route-handler.mjs";
package/esm/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { shared, useShared } from "./shared.mjs";
2
+ import { LocaleProvider, useLocale, useTrans } from "./localization.mjs";
2
3
  import { UnserializableQueryValueError, queryString, queryStringOf, resetQueryStringOptions, setQueryStringOptions } from "./routing/query-string.mjs";
3
4
  import { href } from "./routing/route-table.mjs";
4
5
  import { Link } from "./components/link.mjs";
@@ -9,4 +10,4 @@ import { refresh } from "./client/navigation/refresh.mjs";
9
10
  import { Head } from "./components/head.mjs";
10
11
  import { Scripts } from "./components/scripts.mjs";
11
12
 
12
- export { Head, Link, Scripts, UnserializableQueryValueError, createRouterEvents, currentRoute, getHash, href, navigateBack, navigateTo, previousRoute, queryString, queryStringOf, refresh, resetQueryStringOptions, routerEvents, setQueryStringOptions, shared, useShared };
13
+ export { Head, Link, LocaleProvider, Scripts, UnserializableQueryValueError, createRouterEvents, currentRoute, getHash, href, navigateBack, navigateTo, previousRoute, queryString, queryStringOf, refresh, resetQueryStringOptions, routerEvents, setQueryStringOptions, shared, useLocale, useShared, useTrans };
@@ -0,0 +1,21 @@
1
+ import { Converter, Translatable, transFrom } from "@mongez/localization";
2
+ import { ReactNode } from "react";
3
+
4
+ //#region ../web/src/localization.d.ts
5
+ type LocaleProviderProps = {
6
+ readonly locale: string;
7
+ readonly children: ReactNode;
8
+ };
9
+ type Translate = (keyword: Translatable, placeholders?: unknown, converter?: Converter) => ReturnType<typeof transFrom>;
10
+ /** Bind translations to the request locale carried by the hydration payload. */
11
+ declare function LocaleProvider({
12
+ locale,
13
+ children
14
+ }: LocaleProviderProps): import("react").JSX.Element;
15
+ /** Read the locale selected for the current server render or client page. */
16
+ declare function useLocale(): string;
17
+ /** Translate without consulting @mongez/localization's process-global locale. */
18
+ declare function useTrans(): Translate;
19
+ //#endregion
20
+ export { LocaleProvider, LocaleProviderProps, Translate, useLocale, useTrans };
21
+ //# sourceMappingURL=localization.d.mts.map
@@ -0,0 +1,28 @@
1
+ import { transFrom } from "@mongez/localization";
2
+ import { createContext, useCallback, useContext } from "react";
3
+ import { jsx } from "react/jsx-runtime";
4
+
5
+ //#region ../web/src/localization.tsx
6
+ const LocaleContext = createContext(void 0);
7
+ /** Bind translations to the request locale carried by the hydration payload. */
8
+ function LocaleProvider({ locale, children }) {
9
+ return /* @__PURE__ */ jsx(LocaleContext.Provider, {
10
+ value: locale,
11
+ children
12
+ });
13
+ }
14
+ /** Read the locale selected for the current server render or client page. */
15
+ function useLocale() {
16
+ const locale = useContext(LocaleContext);
17
+ if (locale === void 0) throw new Error("useLocale() was called outside Warlock's LocaleProvider. Render the component through the @warlock.js/web page pipeline.");
18
+ return locale;
19
+ }
20
+ /** Translate without consulting @mongez/localization's process-global locale. */
21
+ function useTrans() {
22
+ const locale = useLocale();
23
+ return useCallback((keyword, placeholders, converter) => transFrom(locale, keyword, placeholders, converter), [locale]);
24
+ }
25
+
26
+ //#endregion
27
+ export { LocaleProvider, useLocale, useTrans };
28
+ //# sourceMappingURL=localization.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"localization.mjs","names":[],"sources":["../../../../../../web/src/localization.tsx"],"sourcesContent":["import {\n transFrom,\n type Converter,\n type Translatable,\n} from \"@mongez/localization\";\nimport { createContext, useCallback, useContext, type ReactNode } from \"react\";\n\nexport type LocaleProviderProps = {\n readonly locale: string;\n readonly children: ReactNode;\n};\n\nexport type Translate = (\n keyword: Translatable,\n placeholders?: unknown,\n converter?: Converter,\n) => ReturnType<typeof transFrom>;\n\nconst LocaleContext = createContext<string | undefined>(undefined);\n\n/** Bind translations to the request locale carried by the hydration payload. */\nexport function LocaleProvider({ locale, children }: LocaleProviderProps) {\n return <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>;\n}\n\n/** Read the locale selected for the current server render or client page. */\nexport function useLocale(): string {\n const locale = useContext(LocaleContext);\n\n if (locale === undefined) {\n throw new Error(\n \"useLocale() was called outside Warlock's LocaleProvider. Render the component \" +\n \"through the @warlock.js/web page pipeline.\",\n );\n }\n\n return locale;\n}\n\n/** Translate without consulting @mongez/localization's process-global locale. */\nexport function useTrans(): Translate {\n const locale = useLocale();\n\n return useCallback(\n (keyword, placeholders, converter) =>\n transFrom(locale, keyword, placeholders, converter),\n [locale],\n );\n}\n"],"mappings":";;;;;AAkBA,MAAM,gBAAgB,cAAkC,MAAS;;AAGjE,SAAgB,eAAe,EAAE,QAAQ,YAAiC;CACxE,OAAO,oBAAC,cAAc,UAAf;EAAwB,OAAO;EAAS;CAAiC;AAClF;;AAGA,SAAgB,YAAoB;CAClC,MAAM,SAAS,WAAW,aAAa;CAEvC,IAAI,WAAW,QACb,MAAM,IAAI,MACR,0HAEF;CAGF,OAAO;AACT;;AAGA,SAAgB,WAAsB;CACpC,MAAM,SAAS,UAAU;CAEzB,OAAO,aACJ,SAAS,cAAc,cACtB,UAAU,QAAQ,SAAS,cAAc,SAAS,GACpD,CAAC,MAAM,CACT;AACF"}
@@ -24,9 +24,11 @@
24
24
  *
25
25
  * Responses to a data request must carry `Vary: <this header>` so a shared
26
26
  * cache can never hand a document to a client that asked for JSON, or the
27
- * reverse. Page responses are `private, no-store` today, which makes that
28
- * theoretical `Vary` is what keeps it theoretical if the caching policy
29
- * changes.
27
+ * reverse. Most page responses are `no-store` which makes that theoretical
28
+ * — but an opted-in route (`route.cache`, `../routing/route-identity.ts`) is
29
+ * genuinely `public, max-age=<n>` on BOTH representations
30
+ * (`response-cache-floor.ts`), so `Vary` is what keeps a shared cache from
31
+ * ever conflating them.
30
32
  */
31
33
  const WARLOCK_DATA_REQUEST_HEADER = "x-warlock-data";
32
34
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"data-request.mjs","names":[],"sources":["../../../../../../../web/src/routing/data-request.ts"],"sourcesContent":["/**\n * The marker that turns a page request into a DATA request.\n *\n * A client navigation needs exactly what a full page load needs — middleware,\n * validation, loaders, redirects, cookies, the settled status — and differs in\n * one respect only: it wants the hydration payload as JSON instead of a\n * rendered document. So it is deliberately NOT a separate `/_loader` route.\n *\n * WHY NOT A SEPARATE ROUTE. A `/_loader?path=/products/42` endpoint has to\n * resolve that path to a page itself, which is a SECOND implementation of route\n * semantics living beside the server's. This codebase already refuses that\n * bargain for the browser — the hydration payload carries the route `name` so\n * the client never re-matches — and the same reasoning applies here with more\n * force: a loader endpoint that disagreed with the real route about params,\n * prefixes or which page owns a path would answer a different request than the\n * one the user navigated to. Same URL, same route, same matcher, same pipeline;\n * only the final representation differs.\n *\n * WHY A HEADER AND NOT `?_data=1`. The query string belongs to the page — it is\n * what `validation` and loaders read. Injecting a framework key into it means a\n * page with strict query validation rejects its own client navigations, and\n * every loader that echoes its query starts leaking a private flag.\n *\n * Responses to a data request must carry `Vary: <this header>` so a shared\n * cache can never hand a document to a client that asked for JSON, or the\n * reverse. Page responses are `private, no-store` today, which makes that\n * theoretical — `Vary` is what keeps it theoretical if the caching policy\n * changes.\n */\nexport const WARLOCK_DATA_REQUEST_HEADER = \"x-warlock-data\";\n\n/**\n * The value the client sends. Any non-empty value is honoured on the way in —\n * the header's PRESENCE is the signal — but the client sends this one so the\n * traffic is self-describing in a log or a network panel.\n */\nexport const WARLOCK_DATA_REQUEST_VALUE = \"1\";\n\n/**\n * Declared explicitly because the payload goes on the wire ALREADY SERIALIZED,\n * as a string, and core only auto-picks `application/json` for object bodies.\n * See the send site for why it must be a string.\n */\nexport const DATA_RESPONSE_CONTENT_TYPE = \"application/json\";\n\n/**\n * Whether a request asked for the payload rather than the document.\n *\n * Presence-based on purpose: a proxy that rewrites the value, or a client on a\n * newer version that sends something more specific, still means \"data\". Only an\n * absent or empty header means \"render the document\".\n */\nexport function isDataRequest(headerValue: string | string[] | undefined): boolean {\n const value = Array.isArray(headerValue) ? headerValue[0] : headerValue;\n\n return typeof value === \"string\" && value.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,8BAA8B;;;;;;AAc3C,MAAa,6BAA6B;;;;;;;;AAS1C,SAAgB,cAAc,aAAqD;CACjF,MAAM,QAAQ,MAAM,QAAQ,WAAW,IAAI,YAAY,KAAK;CAE5D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS;AACrD"}
1
+ {"version":3,"file":"data-request.mjs","names":[],"sources":["../../../../../../../web/src/routing/data-request.ts"],"sourcesContent":["/**\n * The marker that turns a page request into a DATA request.\n *\n * A client navigation needs exactly what a full page load needs — middleware,\n * validation, loaders, redirects, cookies, the settled status — and differs in\n * one respect only: it wants the hydration payload as JSON instead of a\n * rendered document. So it is deliberately NOT a separate `/_loader` route.\n *\n * WHY NOT A SEPARATE ROUTE. A `/_loader?path=/products/42` endpoint has to\n * resolve that path to a page itself, which is a SECOND implementation of route\n * semantics living beside the server's. This codebase already refuses that\n * bargain for the browser — the hydration payload carries the route `name` so\n * the client never re-matches — and the same reasoning applies here with more\n * force: a loader endpoint that disagreed with the real route about params,\n * prefixes or which page owns a path would answer a different request than the\n * one the user navigated to. Same URL, same route, same matcher, same pipeline;\n * only the final representation differs.\n *\n * WHY A HEADER AND NOT `?_data=1`. The query string belongs to the page — it is\n * what `validation` and loaders read. Injecting a framework key into it means a\n * page with strict query validation rejects its own client navigations, and\n * every loader that echoes its query starts leaking a private flag.\n *\n * Responses to a data request must carry `Vary: <this header>` so a shared\n * cache can never hand a document to a client that asked for JSON, or the\n * reverse. Most page responses are `no-store` which makes that theoretical\n * — but an opted-in route (`route.cache`, `../routing/route-identity.ts`) is\n * genuinely `public, max-age=<n>` on BOTH representations\n * (`response-cache-floor.ts`), so `Vary` is what keeps a shared cache from\n * ever conflating them.\n */\nexport const WARLOCK_DATA_REQUEST_HEADER = \"x-warlock-data\";\n\n/**\n * The value the client sends. Any non-empty value is honoured on the way in —\n * the header's PRESENCE is the signal — but the client sends this one so the\n * traffic is self-describing in a log or a network panel.\n */\nexport const WARLOCK_DATA_REQUEST_VALUE = \"1\";\n\n/**\n * Declared explicitly because the payload goes on the wire ALREADY SERIALIZED,\n * as a string, and core only auto-picks `application/json` for object bodies.\n * See the send site for why it must be a string.\n */\nexport const DATA_RESPONSE_CONTENT_TYPE = \"application/json\";\n\n/**\n * Whether a request asked for the payload rather than the document.\n *\n * Presence-based on purpose: a proxy that rewrites the value, or a client on a\n * newer version that sends something more specific, still means \"data\". Only an\n * absent or empty header means \"render the document\".\n */\nexport function isDataRequest(headerValue: string | string[] | undefined): boolean {\n const value = Array.isArray(headerValue) ? headerValue[0] : headerValue;\n\n return typeof value === \"string\" && value.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,8BAA8B;;;;;;AAc3C,MAAa,6BAA6B;;;;;;;;AAS1C,SAAgB,cAAc,aAAqD;CACjF,MAAM,QAAQ,MAAM,QAAQ,WAAW,IAAI,YAAY,KAAK;CAE5D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS;AACrD"}
@@ -1,14 +1,38 @@
1
+ import { PageFileSegmentNotSupportedError, classifyPageFileSegment } from "./page-file-segment.mjs";
2
+
1
3
  //#region ../web/src/routing/filesystem-route.ts
2
4
  function isGroup(segment) {
3
5
  return /^\([^/]+\)$/.test(segment);
4
6
  }
5
- function routeSegment(segment) {
7
+ /**
8
+ * Translate one filesystem segment (a directory name or the page basename)
9
+ * into its route form. Consults {@link classifyPageFileSegment} first and
10
+ * throws {@link PageFileSegmentNotSupportedError} for any segment outside
11
+ * the supported grammar, naming `pageFile` for context, instead of silently
12
+ * passing the segment through as a literal URL segment.
13
+ */
14
+ function routeSegment(segment, pageFile) {
15
+ const verdict = classifyPageFileSegment(segment);
16
+ if (verdict.type === "rejected") throw new PageFileSegmentNotSupportedError(pageFile, segment, verdict.reason);
6
17
  const dynamic = /^\[([A-Za-z_][A-Za-z0-9_]*)\]$/.exec(segment);
7
18
  return dynamic ? `:${dynamic[1]}` : segment;
8
19
  }
9
20
  function prefixSegments(prefix) {
10
21
  return prefix.split("/").filter(Boolean);
11
22
  }
23
+ /**
24
+ * Split a layout `prefix` into route segments AND validate each one through
25
+ * {@link routeSegment}, exactly like a directory segment. A `prefix` is
26
+ * author-controlled text, not derived from the filesystem, so nothing about
27
+ * it is exempt from the grammar `page-file-segment.ts` defines — without
28
+ * this, a `prefix` such as `"/docs/[...slug]"` would smuggle a rejected
29
+ * shape straight into the URL. `pageFile` identifies the page whose layout
30
+ * contributed `prefix`, so a rejection points at the layout, not the page.
31
+ */
32
+ function validatedPrefixSegments(prefix, pageFile) {
33
+ const source = `${pageFile} (via layout prefix '${prefix}')`;
34
+ return prefixSegments(prefix).map((segment) => routeSegment(segment, source));
35
+ }
12
36
  function pageParts(pageFile) {
13
37
  if (pageFile.includes("\\")) throw new Error(`filesystem-route: pageFile must use POSIX separators: "${pageFile}"`);
14
38
  if (!pageFile.endsWith(".page.tsx")) throw new Error(`filesystem-route: pageFile must end in .page.tsx: "${pageFile}"`);
@@ -22,21 +46,26 @@ function pageParts(pageFile) {
22
46
  function deriveFilesystemRoutePath(input) {
23
47
  const { directories, basename } = pageParts(input.pageFile);
24
48
  const prefixes = input.layoutPrefixes ?? {};
25
- const segments = [...prefixSegments(prefixes[""] ?? "")];
49
+ const segments = [...validatedPrefixSegments(prefixes[""] ?? "", input.pageFile)];
26
50
  for (let index = 0; index < directories.length; index++) {
27
51
  const directory = directories[index];
28
52
  const prefix = prefixes[directories.slice(0, index + 1).join("/")];
29
- if (prefix !== void 0) segments.push(...prefixSegments(prefix));
30
- else if (!isGroup(directory)) segments.push(routeSegment(directory));
53
+ const routed = routeSegment(directory, input.pageFile);
54
+ if (prefix !== void 0) segments.push(...validatedPrefixSegments(prefix, input.pageFile));
55
+ else if (!isGroup(directory)) segments.push(routed);
31
56
  }
32
- if (basename !== "index") segments.push(routeSegment(basename));
57
+ if (basename !== "index") segments.push(routeSegment(basename, input.pageFile));
33
58
  return segments.length === 0 ? "/" : `/${segments.join("/")}`;
34
59
  }
35
60
  /** Derive the stable dotted route name from a page's filesystem identity. */
36
61
  function deriveFilesystemRouteName(pageFile) {
37
62
  const { directories, basename } = pageParts(pageFile);
38
- const segments = directories.filter((segment) => !isGroup(segment)).map(routeSegment);
39
- if (basename !== "index") segments.push(routeSegment(basename));
63
+ const segments = [];
64
+ for (const directory of directories) {
65
+ const routed = routeSegment(directory, pageFile);
66
+ if (!isGroup(directory)) segments.push(routed);
67
+ }
68
+ if (basename !== "index") segments.push(routeSegment(basename, pageFile));
40
69
  return segments.map((segment) => segment.replace(/^:/, "")).join(".") || "index";
41
70
  }
42
71
 
@@ -1 +1 @@
1
- {"version":3,"file":"filesystem-route.mjs","names":[],"sources":["../../../../../../../web/src/routing/filesystem-route.ts"],"sourcesContent":["export type FilesystemRouteInput = {\n /** POSIX path relative to `src/web`, ending in `.page.tsx`. */\n pageFile: string;\n /** Layout prefixes keyed by their POSIX directory relative to `src/web`; root uses `\"\"`. */\n layoutPrefixes?: Readonly<Record<string, string>>;\n};\n\nfunction isGroup(segment: string): boolean {\n return /^\\([^/]+\\)$/.test(segment);\n}\n\nfunction routeSegment(segment: string): string {\n const dynamic = /^\\[([A-Za-z_][A-Za-z0-9_]*)\\]$/.exec(segment);\n\n return dynamic ? `:${dynamic[1]}` : segment;\n}\n\nfunction prefixSegments(prefix: string): string[] {\n return prefix.split(\"/\").filter(Boolean);\n}\n\nfunction pageParts(pageFile: string): { directories: string[]; basename: string } {\n if (pageFile.includes(\"\\\\\")) {\n throw new Error(`filesystem-route: pageFile must use POSIX separators: \"${pageFile}\"`);\n }\n\n if (!pageFile.endsWith(\".page.tsx\")) {\n throw new Error(`filesystem-route: pageFile must end in .page.tsx: \"${pageFile}\"`);\n }\n\n const parts = pageFile.split(\"/\");\n const filename = parts.pop() as string;\n\n return {\n directories: parts,\n basename: filename.slice(0, -\".page.tsx\".length),\n };\n}\n\n/** Derive the effective URL for a page with no explicit `route` export. */\nexport function deriveFilesystemRoutePath(input: FilesystemRouteInput): string {\n const { directories, basename } = pageParts(input.pageFile);\n const prefixes = input.layoutPrefixes ?? {};\n const segments = [...prefixSegments(prefixes[\"\"] ?? \"\")];\n\n for (let index = 0; index < directories.length; index++) {\n const directory = directories[index];\n const directoryPath = directories.slice(0, index + 1).join(\"/\");\n const prefix = prefixes[directoryPath];\n\n if (prefix !== undefined) {\n segments.push(...prefixSegments(prefix));\n } else if (!isGroup(directory)) {\n segments.push(routeSegment(directory));\n }\n }\n\n if (basename !== \"index\") {\n segments.push(routeSegment(basename));\n }\n\n return segments.length === 0 ? \"/\" : `/${segments.join(\"/\")}`;\n}\n\n/** Derive the stable dotted route name from a page's filesystem identity. */\nexport function deriveFilesystemRouteName(pageFile: string): string {\n const { directories, basename } = pageParts(pageFile);\n const segments = directories.filter((segment) => !isGroup(segment)).map(routeSegment);\n\n if (basename !== \"index\") {\n segments.push(routeSegment(basename));\n }\n\n return segments.map((segment) => segment.replace(/^:/, \"\")).join(\".\") || \"index\";\n}\n"],"mappings":";AAOA,SAAS,QAAQ,SAA0B;CACzC,OAAO,cAAc,KAAK,OAAO;AACnC;AAEA,SAAS,aAAa,SAAyB;CAC7C,MAAM,UAAU,iCAAiC,KAAK,OAAO;CAE7D,OAAO,UAAU,IAAI,QAAQ,OAAO;AACtC;AAEA,SAAS,eAAe,QAA0B;CAChD,OAAO,OAAO,MAAM,GAAG,EAAE,OAAO,OAAO;AACzC;AAEA,SAAS,UAAU,UAA+D;CAChF,IAAI,SAAS,SAAS,IAAI,GACxB,MAAM,IAAI,MAAM,0DAA0D,SAAS,EAAE;CAGvF,IAAI,CAAC,SAAS,SAAS,WAAW,GAChC,MAAM,IAAI,MAAM,sDAAsD,SAAS,EAAE;CAGnF,MAAM,QAAQ,SAAS,MAAM,GAAG;CAGhC,OAAO;EACL,aAAa;EACb,UAJe,MAAM,IAIJ,EAAE,MAAM,GAAG,EAAmB;CACjD;AACF;;AAGA,SAAgB,0BAA0B,OAAqC;CAC7E,MAAM,EAAE,aAAa,aAAa,UAAU,MAAM,QAAQ;CAC1D,MAAM,WAAW,MAAM,kBAAkB,CAAC;CAC1C,MAAM,WAAW,CAAC,GAAG,eAAe,SAAS,OAAO,EAAE,CAAC;CAEvD,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,QAAQ,SAAS;EACvD,MAAM,YAAY,YAAY;EAE9B,MAAM,SAAS,SADO,YAAY,MAAM,GAAG,QAAQ,CAAC,EAAE,KAAK,GACvB;EAEpC,IAAI,WAAW,QACb,SAAS,KAAK,GAAG,eAAe,MAAM,CAAC;OAClC,IAAI,CAAC,QAAQ,SAAS,GAC3B,SAAS,KAAK,aAAa,SAAS,CAAC;CAEzC;CAEA,IAAI,aAAa,SACf,SAAS,KAAK,aAAa,QAAQ,CAAC;CAGtC,OAAO,SAAS,WAAW,IAAI,MAAM,IAAI,SAAS,KAAK,GAAG;AAC5D;;AAGA,SAAgB,0BAA0B,UAA0B;CAClE,MAAM,EAAE,aAAa,aAAa,UAAU,QAAQ;CACpD,MAAM,WAAW,YAAY,QAAQ,YAAY,CAAC,QAAQ,OAAO,CAAC,EAAE,IAAI,YAAY;CAEpF,IAAI,aAAa,SACf,SAAS,KAAK,aAAa,QAAQ,CAAC;CAGtC,OAAO,SAAS,KAAK,YAAY,QAAQ,QAAQ,MAAM,EAAE,CAAC,EAAE,KAAK,GAAG,KAAK;AAC3E"}
1
+ {"version":3,"file":"filesystem-route.mjs","names":[],"sources":["../../../../../../../web/src/routing/filesystem-route.ts"],"sourcesContent":["import { PageFileSegmentNotSupportedError, classifyPageFileSegment } from \"./page-file-segment\";\r\n\r\nexport type FilesystemRouteInput = {\r\n /** POSIX path relative to `src/web`, ending in `.page.tsx`. */\r\n pageFile: string;\r\n /** Layout prefixes keyed by their POSIX directory relative to `src/web`; root uses `\"\"`. */\r\n layoutPrefixes?: Readonly<Record<string, string>>;\r\n};\r\n\r\nfunction isGroup(segment: string): boolean {\r\n return /^\\([^/]+\\)$/.test(segment);\r\n}\r\n\r\n/**\r\n * Translate one filesystem segment (a directory name or the page basename)\r\n * into its route form. Consults {@link classifyPageFileSegment} first and\r\n * throws {@link PageFileSegmentNotSupportedError} for any segment outside\r\n * the supported grammar, naming `pageFile` for context, instead of silently\r\n * passing the segment through as a literal URL segment.\r\n */\r\nfunction routeSegment(segment: string, pageFile: string): string {\r\n const verdict = classifyPageFileSegment(segment);\r\n\r\n if (verdict.type === \"rejected\") {\r\n throw new PageFileSegmentNotSupportedError(pageFile, segment, verdict.reason);\r\n }\r\n\r\n const dynamic = /^\\[([A-Za-z_][A-Za-z0-9_]*)\\]$/.exec(segment);\r\n\r\n return dynamic ? `:${dynamic[1]}` : segment;\r\n}\r\n\r\nfunction prefixSegments(prefix: string): string[] {\r\n return prefix.split(\"/\").filter(Boolean);\r\n}\r\n\r\n/**\r\n * Split a layout `prefix` into route segments AND validate each one through\r\n * {@link routeSegment}, exactly like a directory segment. A `prefix` is\r\n * author-controlled text, not derived from the filesystem, so nothing about\r\n * it is exempt from the grammar `page-file-segment.ts` defines — without\r\n * this, a `prefix` such as `\"/docs/[...slug]\"` would smuggle a rejected\r\n * shape straight into the URL. `pageFile` identifies the page whose layout\r\n * contributed `prefix`, so a rejection points at the layout, not the page.\r\n */\r\nfunction validatedPrefixSegments(prefix: string, pageFile: string): string[] {\r\n const source = `${pageFile} (via layout prefix '${prefix}')`;\r\n\r\n return prefixSegments(prefix).map((segment) => routeSegment(segment, source));\r\n}\r\n\r\nfunction pageParts(pageFile: string): { directories: string[]; basename: string } {\r\n if (pageFile.includes(\"\\\\\")) {\r\n throw new Error(`filesystem-route: pageFile must use POSIX separators: \"${pageFile}\"`);\r\n }\r\n\r\n if (!pageFile.endsWith(\".page.tsx\")) {\r\n throw new Error(`filesystem-route: pageFile must end in .page.tsx: \"${pageFile}\"`);\r\n }\r\n\r\n const parts = pageFile.split(\"/\");\r\n const filename = parts.pop() as string;\r\n\r\n return {\r\n directories: parts,\r\n basename: filename.slice(0, -\".page.tsx\".length),\r\n };\r\n}\r\n\r\n/** Derive the effective URL for a page with no explicit `route` export. */\r\nexport function deriveFilesystemRoutePath(input: FilesystemRouteInput): string {\r\n const { directories, basename } = pageParts(input.pageFile);\r\n const prefixes = input.layoutPrefixes ?? {};\r\n const segments = [...validatedPrefixSegments(prefixes[\"\"] ?? \"\", input.pageFile)];\r\n\r\n for (let index = 0; index < directories.length; index++) {\r\n const directory = directories[index];\r\n const directoryPath = directories.slice(0, index + 1).join(\"/\");\r\n const prefix = prefixes[directoryPath];\r\n\r\n // Validate EVERY directory name before deciding whether it contributes.\r\n // Contribution and legality are separate questions, and answering them in\r\n // one branch is what let a malformed name through: a directory that owns a\r\n // layout `prefix` took the prefix branch and was never classified, so\r\n // bracket syntax inside a group name went unexamined whenever that group\r\n // also carried a prefix. The name derivation always classified every\r\n // directory; this path did not, and the two disagreed.\r\n const routed = routeSegment(directory, input.pageFile);\r\n\r\n if (prefix !== undefined) {\r\n segments.push(...validatedPrefixSegments(prefix, input.pageFile));\r\n } else if (!isGroup(directory)) {\r\n segments.push(routed);\r\n }\r\n }\r\n\r\n if (basename !== \"index\") {\r\n segments.push(routeSegment(basename, input.pageFile));\r\n }\r\n\r\n return segments.length === 0 ? \"/\" : `/${segments.join(\"/\")}`;\r\n}\r\n\r\n/** Derive the stable dotted route name from a page's filesystem identity. */\r\nexport function deriveFilesystemRouteName(pageFile: string): string {\r\n const { directories, basename } = pageParts(pageFile);\r\n const segments: string[] = [];\r\n\r\n for (const directory of directories) {\r\n const routed = routeSegment(directory, pageFile);\r\n\r\n if (!isGroup(directory)) {\r\n segments.push(routed);\r\n }\r\n }\r\n\r\n if (basename !== \"index\") {\r\n segments.push(routeSegment(basename, pageFile));\r\n }\r\n\r\n return segments.map((segment) => segment.replace(/^:/, \"\")).join(\".\") || \"index\";\r\n}\r\n"],"mappings":";;;AASA,SAAS,QAAQ,SAA0B;CACzC,OAAO,cAAc,KAAK,OAAO;AACnC;;;;;;;;AASA,SAAS,aAAa,SAAiB,UAA0B;CAC/D,MAAM,UAAU,wBAAwB,OAAO;CAE/C,IAAI,QAAQ,SAAS,YACnB,MAAM,IAAI,iCAAiC,UAAU,SAAS,QAAQ,MAAM;CAG9E,MAAM,UAAU,iCAAiC,KAAK,OAAO;CAE7D,OAAO,UAAU,IAAI,QAAQ,OAAO;AACtC;AAEA,SAAS,eAAe,QAA0B;CAChD,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO;AACzC;;;;;;;;;;AAWA,SAAS,wBAAwB,QAAgB,UAA4B;CAC3E,MAAM,SAAS,GAAG,SAAS,uBAAuB,OAAO;CAEzD,OAAO,eAAe,MAAM,CAAC,CAAC,KAAK,YAAY,aAAa,SAAS,MAAM,CAAC;AAC9E;AAEA,SAAS,UAAU,UAA+D;CAChF,IAAI,SAAS,SAAS,IAAI,GACxB,MAAM,IAAI,MAAM,0DAA0D,SAAS,EAAE;CAGvF,IAAI,CAAC,SAAS,SAAS,WAAW,GAChC,MAAM,IAAI,MAAM,sDAAsD,SAAS,EAAE;CAGnF,MAAM,QAAQ,SAAS,MAAM,GAAG;CAGhC,OAAO;EACL,aAAa;EACb,UAJe,MAAM,IAIJ,CAAC,CAAC,MAAM,GAAG,EAAmB;CACjD;AACF;;AAGA,SAAgB,0BAA0B,OAAqC;CAC7E,MAAM,EAAE,aAAa,aAAa,UAAU,MAAM,QAAQ;CAC1D,MAAM,WAAW,MAAM,kBAAkB,CAAC;CAC1C,MAAM,WAAW,CAAC,GAAG,wBAAwB,SAAS,OAAO,IAAI,MAAM,QAAQ,CAAC;CAEhF,KAAK,IAAI,QAAQ,GAAG,QAAQ,YAAY,QAAQ,SAAS;EACvD,MAAM,YAAY,YAAY;EAE9B,MAAM,SAAS,SADO,YAAY,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAK,GACvB;EASpC,MAAM,SAAS,aAAa,WAAW,MAAM,QAAQ;EAErD,IAAI,WAAW,QACb,SAAS,KAAK,GAAG,wBAAwB,QAAQ,MAAM,QAAQ,CAAC;OAC3D,IAAI,CAAC,QAAQ,SAAS,GAC3B,SAAS,KAAK,MAAM;CAExB;CAEA,IAAI,aAAa,SACf,SAAS,KAAK,aAAa,UAAU,MAAM,QAAQ,CAAC;CAGtD,OAAO,SAAS,WAAW,IAAI,MAAM,IAAI,SAAS,KAAK,GAAG;AAC5D;;AAGA,SAAgB,0BAA0B,UAA0B;CAClE,MAAM,EAAE,aAAa,aAAa,UAAU,QAAQ;CACpD,MAAM,WAAqB,CAAC;CAE5B,KAAK,MAAM,aAAa,aAAa;EACnC,MAAM,SAAS,aAAa,WAAW,QAAQ;EAE/C,IAAI,CAAC,QAAQ,SAAS,GACpB,SAAS,KAAK,MAAM;CAExB;CAEA,IAAI,aAAa,SACf,SAAS,KAAK,aAAa,UAAU,QAAQ,CAAC;CAGhD,OAAO,SAAS,KAAK,YAAY,QAAQ,QAAQ,MAAM,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,KAAK;AAC3E"}
@@ -1 +1 @@
1
- {"version":3,"file":"layout-policy.mjs","names":[],"sources":["../../../../../../../web/src/routing/layout-policy.ts"],"sourcesContent":["/**\n * Layout policy — the single, pure rule for turning a page's ENUMERATED\n * layout chain into a selection decision.\n *\n * Enumeration and selection are deliberately separate concerns. Discovery\n * ({@link \"../build/discover-pages.ts\"}'s `layoutChainFor`) walks a page's\n * directory ancestry and reports every `layout.tsx` it finds, outermost\n * first, honestly and unfiltered — it does not decide whether that chain is\n * usable. This module is the one place that decision is made: given a chain,\n * how many layouts does composition get to use, and which one(s)?\n *\n * THE RULE COUNTS RENDERING LAYOUTS, NOT FILES. A layout that contributes no\n * element to the document — one with no default export, carrying only\n * `prefix`, `middleware` or other named exports — is not a second wrapper and\n * never was. Counting files instead of wrappers made an authorization boundary\n * indistinguishable from a nested layout, and the resulting refusal told app\n * authors to delete the boundary to make the build pass. Nested RENDERING\n * layouts remain unsupported; everything else composes freely.\n *\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. This module\n * receives a canonical chain and trusts nothing about it beyond the input\n * contract asserted below — it asserts rather than trusts, but it never\n * repairs. It therefore never DECIDES what renders either: that answer needs\n * the filesystem, so the caller — which has it — classifies each entry and\n * passes the classification in. Discovery owns the fact; this module owns the\n * rule. The `layout` identifiers are opaque (paths, in practice) and this\n * module never inspects their shape; it only counts and selects.\n *\n * REJECTION IS DATA, NOT A THROW: a chain with two or more rendering layouts\n * does not make {@link selectPageLayout} raise — it returns the rejected\n * rendering layouts, in order. What a rejection MEANS to the user is\n * nonetheless fixed here: {@link NestedLayoutsNotSupportedError} is the single\n * error contract for it — one class, one message shape, built from the\n * rejection data plus caller-supplied page identity. Callers decide only WHEN\n * to raise it and supply that context; none of them wraps the rejection in a\n * category or wording of its own. A shared policy whose failure semantics fork\n * per caller is shared in the happy path and forked in the sad one — and the\n * sad path is the one users meet.\n */\n\n/**\n * One layout in a chain, with the caller's answer to the only question this\n * module needs about it: does it render?\n *\n * `renders` is true when the layout's module has a default export — the thing\n * that puts an element in the document. Everything else it exports (`prefix`,\n * `middleware`, helpers) is invisible to this rule.\n */\nexport type LayoutChainEntry = {\n /** Opaque identifier for the layout — an app-root-relative POSIX path, in practice. */\n layout: string;\n /** Whether this layout contributes an element to the document. */\n renders: boolean;\n};\n\n/**\n * A chain as {@link selectPageLayout} accepts it: classified entries, or bare\n * identifiers for a caller that has not classified its chain yet.\n *\n * TRANSITIONAL: a bare string is read as a RENDERING layout, which is the\n * conservative reading (it can only make the rule stricter, never looser) and\n * reproduces this module's pre-classification behaviour exactly. It exists so\n * the boot-time manifest installer — which holds loaded modules rather than\n * source files — keeps working unchanged until it classifies too; remove the\n * string arm once every caller passes {@link LayoutChainEntry}s.\n */\nexport type LayoutChainInput = readonly (string | LayoutChainEntry)[];\n\n/**\n * The policy's decision for one page's layout chain:\n *\n * - `\"none\"` — no layout on the chain renders; the page composes against no\n * layout. A chain of three middleware-only layouts lands here exactly as an\n * empty chain does, because neither has a wrapper in it.\n * - `\"selected\"` — exactly one layout renders; `layout` is that element, which,\n * being the only rendering one, is simultaneously the outermost and the\n * nearest rendering layout — there is no distinction to draw between the two\n * when there is only one.\n * - `\"rejected\"` — more than one layout renders; `layouts` carries the\n * RENDERING layouts only, outermost-first, in chain order, so a consumer can\n * name every layout actually at fault without naming the guards between them.\n */\nexport type LayoutPolicyResult =\n | { type: \"none\" }\n | { type: \"selected\"; layout: string }\n | { type: \"rejected\"; layouts: readonly string[] };\n\n/**\n * Raised when a `chain` passed to {@link selectPageLayout} contains an empty\n * layout identifier. An empty string is not a layout identifier a caller could\n * have meant; this module refuses it rather than silently treating it as\n * absent or as a real selection.\n */\nexport class EmptyLayoutChainEntryError extends Error {\n public constructor(public readonly chain: readonly string[]) {\n super(\n `layout-policy: chain [${chain.map((entry) => `\"${entry}\"`).join(\", \")}] contains an empty ` +\n \"string. Every element of a layout chain passed to selectPageLayout must be a non-empty \" +\n \"layout identifier — omit the entry entirely rather than passing an empty string for it.\",\n );\n this.name = \"EmptyLayoutChainEntryError\";\n }\n}\n\n/**\n * The single error contract for a `rejected` selection — the one class and\n * one message every caller of {@link selectPageLayout} raises when it refuses\n * a page whose path holds more than one RENDERING layout. `pageFile` and\n * `layoutFiles` are the caller's context (its audience-appropriate identifiers\n * for the page and the rejected rendering layouts — app-root-relative POSIX\n * paths, in practice); the category and wording are this module's.\n *\n * The wording names the rendering layouts and ONLY the rendering layouts, and\n * it does not offer removal as a remedy. Its predecessor said \"remove or\n * consolidate the extra layout\", which, on a chain whose second element was a\n * `middleware`-only authorization boundary, instructed the reader to delete\n * their security guard to make the build pass.\n */\nexport class NestedLayoutsNotSupportedError extends Error {\n public constructor(\n public readonly pageFile: string,\n public readonly layoutFiles: readonly string[],\n ) {\n super(\n `\"${pageFile}\" has more than one layout on its path that renders: ` +\n `${layoutFiles.map((file) => `\"${file}\"`).join(\", \")}. Pages currently support at most one ` +\n \"RENDERING layout — a layout with a default export — and nesting more than one is not yet \" +\n \"supported. Layouts that render nothing, such as a `prefix`- or `middleware`-only layout, \" +\n \"do not count against this and may nest freely. To fix: consolidate the rendering layouts \" +\n \"named above into one — and do not remove a middleware-only layout to satisfy this, since \" +\n \"none of them is what this refuses.\",\n );\n this.name = \"NestedLayoutsNotSupportedError\";\n }\n}\n\n/** The classified form of an entry, whichever way the caller spelled it. */\nfunction toEntry(entry: string | LayoutChainEntry): LayoutChainEntry {\n return typeof entry === \"string\" ? { layout: entry, renders: true } : entry;\n}\n\n/**\n * Selects which layout, if any, a page RENDERS inside, given its layout chain\n * as enumerated outermost-first.\n *\n * Only entries with `renders: true` are counted: no rendering layout yields\n * `{ type: \"none\" }`; exactly one yields `{ type: \"selected\"; layout }`; more\n * than one yields `{ type: \"rejected\"; layouts }` carrying just those rendering\n * layouts — this function throws nothing for that case; see the module doc for\n * why rejection is data, not a throw.\n *\n * Throws {@link EmptyLayoutChainEntryError} when any entry's identifier is an\n * empty string — the one input-contract violation this module refuses rather\n * than passes through as a selection.\n */\nexport function selectPageLayout(chain: LayoutChainInput): LayoutPolicyResult {\n const entries = chain.map(toEntry);\n\n if (entries.some((entry) => entry.layout === \"\")) {\n throw new EmptyLayoutChainEntryError(entries.map((entry) => entry.layout));\n }\n\n const rendering = entries.filter((entry) => entry.renders).map((entry) => entry.layout);\n\n if (rendering.length === 0) {\n return { type: \"none\" };\n }\n\n if (rendering.length === 1) {\n return { type: \"selected\", layout: rendering[0] };\n }\n\n return { type: \"rejected\", layouts: rendering };\n}\n"],"mappings":";;;;;;;AA8FA,IAAa,6BAAb,cAAgD,MAAM;CACjB;CAAnC,AAAO,YAAY,AAAgB,OAA0B;EAC3D,MACE,yBAAyB,MAAM,KAAK,UAAU,IAAI,MAAM,EAAE,EAAE,KAAK,IAAI,EAAE,mMAGzE;EALiC;EAMjC,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,IAAa,iCAAb,cAAoD,MAAM;CAEtC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,aAChB;EACA,MACE,IAAI,SAAS,uDACR,YAAY,KAAK,SAAS,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI,EAAE,ibAMzD;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;AAGA,SAAS,QAAQ,OAAoD;CACnE,OAAO,OAAO,UAAU,WAAW;EAAE,QAAQ;EAAO,SAAS;CAAK,IAAI;AACxE;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,OAA6C;CAC5E,MAAM,UAAU,MAAM,IAAI,OAAO;CAEjC,IAAI,QAAQ,MAAM,UAAU,MAAM,WAAW,EAAE,GAC7C,MAAM,IAAI,2BAA2B,QAAQ,KAAK,UAAU,MAAM,MAAM,CAAC;CAG3E,MAAM,YAAY,QAAQ,QAAQ,UAAU,MAAM,OAAO,EAAE,KAAK,UAAU,MAAM,MAAM;CAEtF,IAAI,UAAU,WAAW,GACvB,OAAO,EAAE,MAAM,OAAO;CAGxB,IAAI,UAAU,WAAW,GACvB,OAAO;EAAE,MAAM;EAAY,QAAQ,UAAU;CAAG;CAGlD,OAAO;EAAE,MAAM;EAAY,SAAS;CAAU;AAChD"}
1
+ {"version":3,"file":"layout-policy.mjs","names":[],"sources":["../../../../../../../web/src/routing/layout-policy.ts"],"sourcesContent":["/**\n * Layout policy — the single, pure rule for turning a page's ENUMERATED\n * layout chain into a selection decision.\n *\n * Enumeration and selection are deliberately separate concerns. Discovery\n * ({@link \"../build/discover-pages.ts\"}'s `layoutChainFor`) walks a page's\n * directory ancestry and reports every `layout.tsx` it finds, outermost\n * first, honestly and unfiltered — it does not decide whether that chain is\n * usable. This module is the one place that decision is made: given a chain,\n * how many layouts does composition get to use, and which one(s)?\n *\n * THE RULE COUNTS RENDERING LAYOUTS, NOT FILES. A layout that contributes no\n * element to the document — one with no default export, carrying only\n * `prefix`, `middleware` or other named exports — is not a second wrapper and\n * never was. Counting files instead of wrappers made an authorization boundary\n * indistinguishable from a nested layout, and the resulting refusal told app\n * authors to delete the boundary to make the build pass. Nested RENDERING\n * layouts remain unsupported; everything else composes freely.\n *\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. This module\n * receives a canonical chain and trusts nothing about it beyond the input\n * contract asserted below — it asserts rather than trusts, but it never\n * repairs. It therefore never DECIDES what renders either: that answer needs\n * the filesystem, so the caller — which has it — classifies each entry and\n * passes the classification in. Discovery owns the fact; this module owns the\n * rule. The `layout` identifiers are opaque (paths, in practice) and this\n * module never inspects their shape; it only counts and selects.\n *\n * REJECTION IS DATA, NOT A THROW: a chain with two or more rendering layouts\n * does not make {@link selectPageLayout} raise — it returns the rejected\n * rendering layouts, in order. What a rejection MEANS to the user is\n * nonetheless fixed here: {@link NestedLayoutsNotSupportedError} is the single\n * error contract for it — one class, one message shape, built from the\n * rejection data plus caller-supplied page identity. Callers decide only WHEN\n * to raise it and supply that context; none of them wraps the rejection in a\n * category or wording of its own. A shared policy whose failure semantics fork\n * per caller is shared in the happy path and forked in the sad one — and the\n * sad path is the one users meet.\n */\n\n/**\n * One layout in a chain, with the caller's answer to the only question this\n * module needs about it: does it render?\n *\n * `renders` is true when the layout's module has a default export — the thing\n * that puts an element in the document. Everything else it exports (`prefix`,\n * `middleware`, helpers) is invisible to this rule.\n */\nexport type LayoutChainEntry = {\n /** Opaque identifier for the layout — an app-root-relative POSIX path, in practice. */\n layout: string;\n /** Whether this layout contributes an element to the document. */\n renders: boolean;\n};\n\n/**\n * A chain as {@link selectPageLayout} accepts it: classified entries, or bare\n * identifiers for a caller that has not classified its chain yet.\n *\n * TRANSITIONAL: a bare string is read as a RENDERING layout, which is the\n * conservative reading (it can only make the rule stricter, never looser) and\n * reproduces this module's pre-classification behaviour exactly. It exists so\n * the boot-time manifest installer — which holds loaded modules rather than\n * source files — keeps working unchanged until it classifies too; remove the\n * string arm once every caller passes {@link LayoutChainEntry}s.\n */\nexport type LayoutChainInput = readonly (string | LayoutChainEntry)[];\n\n/**\n * The policy's decision for one page's layout chain:\n *\n * - `\"none\"` — no layout on the chain renders; the page composes against no\n * layout. A chain of three middleware-only layouts lands here exactly as an\n * empty chain does, because neither has a wrapper in it.\n * - `\"selected\"` — exactly one layout renders; `layout` is that element, which,\n * being the only rendering one, is simultaneously the outermost and the\n * nearest rendering layout — there is no distinction to draw between the two\n * when there is only one.\n * - `\"rejected\"` — more than one layout renders; `layouts` carries the\n * RENDERING layouts only, outermost-first, in chain order, so a consumer can\n * name every layout actually at fault without naming the guards between them.\n */\nexport type LayoutPolicyResult =\n | { type: \"none\" }\n | { type: \"selected\"; layout: string }\n | { type: \"rejected\"; layouts: readonly string[] };\n\n/**\n * Raised when a `chain` passed to {@link selectPageLayout} contains an empty\n * layout identifier. An empty string is not a layout identifier a caller could\n * have meant; this module refuses it rather than silently treating it as\n * absent or as a real selection.\n */\nexport class EmptyLayoutChainEntryError extends Error {\n public constructor(public readonly chain: readonly string[]) {\n super(\n `layout-policy: chain [${chain.map((entry) => `\"${entry}\"`).join(\", \")}] contains an empty ` +\n \"string. Every element of a layout chain passed to selectPageLayout must be a non-empty \" +\n \"layout identifier — omit the entry entirely rather than passing an empty string for it.\",\n );\n this.name = \"EmptyLayoutChainEntryError\";\n }\n}\n\n/**\n * The single error contract for a `rejected` selection — the one class and\n * one message every caller of {@link selectPageLayout} raises when it refuses\n * a page whose path holds more than one RENDERING layout. `pageFile` and\n * `layoutFiles` are the caller's context (its audience-appropriate identifiers\n * for the page and the rejected rendering layouts — app-root-relative POSIX\n * paths, in practice); the category and wording are this module's.\n *\n * The wording names the rendering layouts and ONLY the rendering layouts, and\n * it does not offer removal as a remedy. Its predecessor said \"remove or\n * consolidate the extra layout\", which, on a chain whose second element was a\n * `middleware`-only authorization boundary, instructed the reader to delete\n * their security guard to make the build pass.\n */\nexport class NestedLayoutsNotSupportedError extends Error {\n public constructor(\n public readonly pageFile: string,\n public readonly layoutFiles: readonly string[],\n ) {\n super(\n `\"${pageFile}\" has more than one layout on its path that renders: ` +\n `${layoutFiles.map((file) => `\"${file}\"`).join(\", \")}. Pages currently support at most one ` +\n \"RENDERING layout — a layout with a default export — and nesting more than one is not yet \" +\n \"supported. Layouts that render nothing, such as a `prefix`- or `middleware`-only layout, \" +\n \"do not count against this and may nest freely. To fix: consolidate the rendering layouts \" +\n \"named above into one — and do not remove a middleware-only layout to satisfy this, since \" +\n \"none of them is what this refuses.\",\n );\n this.name = \"NestedLayoutsNotSupportedError\";\n }\n}\n\n/** The classified form of an entry, whichever way the caller spelled it. */\nfunction toEntry(entry: string | LayoutChainEntry): LayoutChainEntry {\n return typeof entry === \"string\" ? { layout: entry, renders: true } : entry;\n}\n\n/**\n * Selects which layout, if any, a page RENDERS inside, given its layout chain\n * as enumerated outermost-first.\n *\n * Only entries with `renders: true` are counted: no rendering layout yields\n * `{ type: \"none\" }`; exactly one yields `{ type: \"selected\"; layout }`; more\n * than one yields `{ type: \"rejected\"; layouts }` carrying just those rendering\n * layouts — this function throws nothing for that case; see the module doc for\n * why rejection is data, not a throw.\n *\n * Throws {@link EmptyLayoutChainEntryError} when any entry's identifier is an\n * empty string — the one input-contract violation this module refuses rather\n * than passes through as a selection.\n */\nexport function selectPageLayout(chain: LayoutChainInput): LayoutPolicyResult {\n const entries = chain.map(toEntry);\n\n if (entries.some((entry) => entry.layout === \"\")) {\n throw new EmptyLayoutChainEntryError(entries.map((entry) => entry.layout));\n }\n\n const rendering = entries.filter((entry) => entry.renders).map((entry) => entry.layout);\n\n if (rendering.length === 0) {\n return { type: \"none\" };\n }\n\n if (rendering.length === 1) {\n return { type: \"selected\", layout: rendering[0] };\n }\n\n return { type: \"rejected\", layouts: rendering };\n}\n"],"mappings":";;;;;;;AA8FA,IAAa,6BAAb,cAAgD,MAAM;CACjB;CAAnC,AAAO,YAAY,AAAgB,OAA0B;EAC3D,MACE,yBAAyB,MAAM,KAAK,UAAU,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,mMAGzE;EALiC;EAMjC,KAAK,OAAO;CACd;AACF;;;;;;;;;;;;;;;AAgBA,IAAa,iCAAb,cAAoD,MAAM;CAEtC;CACA;CAFlB,AAAO,YACL,AAAgB,UAChB,AAAgB,aAChB;EACA,MACE,IAAI,SAAS,uDACR,YAAY,KAAK,SAAS,IAAI,KAAK,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,ibAMzD;EAXgB;EACA;EAWhB,KAAK,OAAO;CACd;AACF;;AAGA,SAAS,QAAQ,OAAoD;CACnE,OAAO,OAAO,UAAU,WAAW;EAAE,QAAQ;EAAO,SAAS;CAAK,IAAI;AACxE;;;;;;;;;;;;;;;AAgBA,SAAgB,iBAAiB,OAA6C;CAC5E,MAAM,UAAU,MAAM,IAAI,OAAO;CAEjC,IAAI,QAAQ,MAAM,UAAU,MAAM,WAAW,EAAE,GAC7C,MAAM,IAAI,2BAA2B,QAAQ,KAAK,UAAU,MAAM,MAAM,CAAC;CAG3E,MAAM,YAAY,QAAQ,QAAQ,UAAU,MAAM,OAAO,CAAC,CAAC,KAAK,UAAU,MAAM,MAAM;CAEtF,IAAI,UAAU,WAAW,GACvB,OAAO,EAAE,MAAM,OAAO;CAGxB,IAAI,UAAU,WAAW,GACvB,OAAO;EAAE,MAAM;EAAY,QAAQ,UAAU;CAAG;CAGlD,OAAO;EAAE,MAAM;EAAY,SAAS;CAAU;AAChD"}
@@ -0,0 +1,66 @@
1
+ //#region ../web/src/routing/page-file-segment.ts
2
+ const allowed = { type: "allowed" };
3
+ function rejected(reason) {
4
+ return {
5
+ type: "rejected",
6
+ reason
7
+ };
8
+ }
9
+ /** A whole, unqualified parameter name — no leading digit, no punctuation. */
10
+ const parameterNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
11
+ /** A single balanced, non-nested bracket group such as `[id]` or `[...slug]`. */
12
+ const bracketGroupPattern = /\[[^[\]]*]/g;
13
+ /** A `(group)` directory — the whole segment wrapped in one pair of parens. */
14
+ const groupSegmentPattern = /^\(([^/]+)\)$/;
15
+ /**
16
+ * Decides whether one filesystem segment is inside the grammar
17
+ * `filesystem-route.ts` can translate. Pure and total: every input yields a
18
+ * verdict and nothing throws. `segment` must already be the isolated
19
+ * segment (a single directory name, or the page basename with `.page.tsx`
20
+ * already stripped) — no normalization is performed here.
21
+ */
22
+ function classifyPageFileSegment(segment) {
23
+ const groupMatch = groupSegmentPattern.exec(segment);
24
+ if (groupMatch) {
25
+ const groupName = groupMatch[1];
26
+ if (groupName.includes("[") || groupName.includes("]")) return rejected(`Segment "${segment}" is a group, and a group contributes nothing to the URL path, so bracket syntax inside it can never produce a dynamic segment — move the dynamic segment out of the group, as in "(marketing)/[id]/page.page.tsx" rather than "(marketing[id])/page.page.tsx".`);
27
+ return allowed;
28
+ }
29
+ if (!segment.includes("[") && !segment.includes("]")) return allowed;
30
+ const groups = segment.match(bracketGroupPattern) ?? [];
31
+ const remaining = groups.reduce((text, group) => text.replace(group, ""), segment);
32
+ if (remaining.includes("[") || remaining.includes("]")) return rejected(`Segment "${segment}" has unbalanced "[" or "]" brackets, which page routes do not support — balance the brackets, as in a whole-segment param like "[id]".`);
33
+ if (groups.length > 1) return rejected(`Segment "${segment}" contains more than one bracket group, and page routes require a dynamic segment to occupy its whole filesystem segment — split them into separate directory segments, as in "[id]/[slug]".`);
34
+ const [group] = groups;
35
+ if (remaining !== "") return rejected(`Segment "${segment}" mixes a bracket group with other text, and page routes require a dynamic segment to occupy its whole filesystem segment — declare it as its own segment, as in "[id]".`);
36
+ const name = group.slice(1, -1);
37
+ if (name === "") return rejected(`Segment "${segment}" has an empty parameter name — declare a name inside the brackets, as in "[id]".`);
38
+ if (name.startsWith("...")) return rejected(`Segment "${segment}" is a catch-all pattern, which page routes do not support — page routes support only a whole-segment param such as "[id]", not a catch-all.`);
39
+ if (parameterNamePattern.test(name)) return allowed;
40
+ return rejected(`Segment "${segment}" declares a parameter name page routes do not support — a parameter name must start with a letter or "_" and contain only letters, digits and "_", as in "[id]" or "[user_id]".`);
41
+ }
42
+ /**
43
+ * The single error contract for a rejected page-file segment — the one
44
+ * class and one message every caller of {@link classifyPageFileSegment}
45
+ * raises when it refuses a page whose filesystem segment was rejected.
46
+ * `pageFile` is the caller's context (its audience-appropriate identifier
47
+ * for the page — an app-root-relative POSIX path, in practice); `segment`
48
+ * and `reason` come from the verdict; the category and wording are this
49
+ * module's.
50
+ */
51
+ var PageFileSegmentNotSupportedError = class extends Error {
52
+ pageFile;
53
+ segment;
54
+ reason;
55
+ constructor(pageFile, segment, reason) {
56
+ super(`"${pageFile}" contains the filesystem segment "${segment}", which is not supported: ${reason} Page routes support a plain static segment or a whole-segment dynamic param such as "[id]".`);
57
+ this.pageFile = pageFile;
58
+ this.segment = segment;
59
+ this.reason = reason;
60
+ this.name = "PageFileSegmentNotSupportedError";
61
+ }
62
+ };
63
+
64
+ //#endregion
65
+ export { PageFileSegmentNotSupportedError, classifyPageFileSegment };
66
+ //# sourceMappingURL=page-file-segment.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-file-segment.mjs","names":[],"sources":["../../../../../../../web/src/routing/page-file-segment.ts"],"sourcesContent":["/**\n * Page-file segment grammar — the single, pure predicate that decides\n * whether one filesystem segment of a page file (a directory name or the\n * `.page.tsx` basename) is inside the grammar `filesystem-route.ts` can\n * actually translate into a route. This is a SIBLING of\n * `page-route-grammar.ts`, not an extension of it: that module validates a\n * page's DECLARED colon-form `route.path` (`/users/:id`); this one validates\n * a FILESYSTEM segment as it appears on disk (`[id]`) before it is turned\n * into one.\n *\n * DIRECTORY CONTRACT — applies to everything in `web/src/routing/`: nothing\n * here may import `node:fs`, `node:path`, `vite`, or `fastify`. This module\n * receives a single path segment string and trusts nothing about it beyond\n * what it checks — it asserts rather than trusts, but it never repairs a\n * malformed segment into a valid one.\n *\n * ALLOWED — and ONLY these shapes; anything else is rejected by default:\n * a plain static segment containing no \"[\" and no \"]\" at all; a `(group)`\n * directory whose name contains no \"[\" and no \"]\"; and exactly `[name]`,\n * where the segment is nothing but a single bracket pair and `name` matches\n * `^[A-Za-z_][A-Za-z0-9_]*$` — i.e. precisely the shape `filesystem-route.ts`\n * can translate into a `:name` route param.\n *\n * REJECTED — each with a reason naming the offending segment and, where one\n * exists, the supported alternative: a `(group)` directory whose name\n * contains \"[\" or \"]\" anywhere (`(bad[id])`, `([x])`) — a group contributes\n * nothing to the URL path, so bracket syntax inside one can never produce a\n * dynamic segment, and the fix is to move the dynamic segment out of the\n * group; a catch-all group (`[...slug]`, `[...]`); two or more bracket\n * groups in one segment (`[id].[slug]`, `[a]-[b]`); a bracket group mixed\n * with other text (`pre[id]`); an empty parameter name (`[]`); a parameter\n * name that does not start with a letter or `_`, or contains a character\n * other than a letter, digit or `_` (`[1bad]`, `[a-b]`, `[a b]`); and\n * unbalanced or stray `[`/`]` characters.\n *\n * REJECTION IS DATA, NOT A THROW: {@link classifyPageFileSegment} is total\n * and never raises. What a rejection MEANS to the user is nonetheless fixed\n * here: {@link PageFileSegmentNotSupportedError} is the single error\n * contract every caller raises when it refuses a rejected segment — one\n * class, one message shape, built from the rejection reason plus\n * caller-supplied page identity. Callers decide only WHEN to raise it and\n * supply that context; none of them wraps the rejection in a category or\n * wording of its own.\n */\n\n/**\n * The predicate's verdict for one filesystem segment:\n *\n * - `\"allowed\"` — the segment is one of the grammar's allowed shapes.\n * - `\"rejected\"` — the segment is outside the grammar; `reason` is a\n * complete, user-readable sentence naming the offending segment and the\n * supported alternative if one exists.\n */\nexport type PageFileSegmentVerdict = { type: \"allowed\" } | { type: \"rejected\"; reason: string };\n\nconst allowed: PageFileSegmentVerdict = { type: \"allowed\" };\n\nfunction rejected(reason: string): PageFileSegmentVerdict {\n return { type: \"rejected\", reason };\n}\n\n/** A whole, unqualified parameter name — no leading digit, no punctuation. */\nconst parameterNamePattern = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** A single balanced, non-nested bracket group such as `[id]` or `[...slug]`. */\nconst bracketGroupPattern = /\\[[^[\\]]*]/g;\n\n/** A `(group)` directory — the whole segment wrapped in one pair of parens. */\nconst groupSegmentPattern = /^\\(([^/]+)\\)$/;\n\n/**\n * Decides whether one filesystem segment is inside the grammar\n * `filesystem-route.ts` can translate. Pure and total: every input yields a\n * verdict and nothing throws. `segment` must already be the isolated\n * segment (a single directory name, or the page basename with `.page.tsx`\n * already stripped) — no normalization is performed here.\n */\nexport function classifyPageFileSegment(segment: string): PageFileSegmentVerdict {\n const groupMatch = groupSegmentPattern.exec(segment);\n\n if (groupMatch) {\n const groupName = groupMatch[1];\n\n if (groupName.includes(\"[\") || groupName.includes(\"]\")) {\n return rejected(\n `Segment \"${segment}\" is a group, and a group contributes nothing to the URL path, so ` +\n `bracket syntax inside it can never produce a dynamic segment — move the dynamic ` +\n `segment out of the group, as in \"(marketing)/[id]/page.page.tsx\" rather than ` +\n `\"(marketing[id])/page.page.tsx\".`,\n );\n }\n\n return allowed;\n }\n\n if (!segment.includes(\"[\") && !segment.includes(\"]\")) {\n return allowed;\n }\n\n const groups = segment.match(bracketGroupPattern) ?? [];\n const remaining = groups.reduce((text, group) => text.replace(group, \"\"), segment);\n\n if (remaining.includes(\"[\") || remaining.includes(\"]\")) {\n return rejected(\n `Segment \"${segment}\" has unbalanced \"[\" or \"]\" brackets, which page routes do not ` +\n `support — balance the brackets, as in a whole-segment param like \"[id]\".`,\n );\n }\n\n if (groups.length > 1) {\n return rejected(\n `Segment \"${segment}\" contains more than one bracket group, and page routes require a ` +\n `dynamic segment to occupy its whole filesystem segment — split them into separate ` +\n `directory segments, as in \"[id]/[slug]\".`,\n );\n }\n\n const [group] = groups;\n\n if (remaining !== \"\") {\n return rejected(\n `Segment \"${segment}\" mixes a bracket group with other text, and page routes require a ` +\n `dynamic segment to occupy its whole filesystem segment — declare it as its own segment, ` +\n `as in \"[id]\".`,\n );\n }\n\n const name = group.slice(1, -1);\n\n if (name === \"\") {\n return rejected(\n `Segment \"${segment}\" has an empty parameter name — declare a name inside the brackets, ` +\n `as in \"[id]\".`,\n );\n }\n\n if (name.startsWith(\"...\")) {\n return rejected(\n `Segment \"${segment}\" is a catch-all pattern, which page routes do not support — page ` +\n `routes support only a whole-segment param such as \"[id]\", not a catch-all.`,\n );\n }\n\n if (parameterNamePattern.test(name)) {\n return allowed;\n }\n\n return rejected(\n `Segment \"${segment}\" declares a parameter name page routes do not support — a parameter ` +\n `name must start with a letter or \"_\" and contain only letters, digits and \"_\", as in ` +\n `\"[id]\" or \"[user_id]\".`,\n );\n}\n\n/**\n * The single error contract for a rejected page-file segment — the one\n * class and one message every caller of {@link classifyPageFileSegment}\n * raises when it refuses a page whose filesystem segment was rejected.\n * `pageFile` is the caller's context (its audience-appropriate identifier\n * for the page — an app-root-relative POSIX path, in practice); `segment`\n * and `reason` come from the verdict; the category and wording are this\n * module's.\n */\nexport class PageFileSegmentNotSupportedError extends Error {\n public constructor(\n public readonly pageFile: string,\n public readonly segment: string,\n public readonly reason: string,\n ) {\n super(\n `\"${pageFile}\" contains the filesystem segment \"${segment}\", which is not supported: ` +\n `${reason} Page routes support a plain static segment or a whole-segment dynamic param ` +\n `such as \"[id]\".`,\n );\n this.name = \"PageFileSegmentNotSupportedError\";\n }\n}\n"],"mappings":";AAuDA,MAAM,UAAkC,EAAE,MAAM,UAAU;AAE1D,SAAS,SAAS,QAAwC;CACxD,OAAO;EAAE,MAAM;EAAY;CAAO;AACpC;;AAGA,MAAM,uBAAuB;;AAG7B,MAAM,sBAAsB;;AAG5B,MAAM,sBAAsB;;;;;;;;AAS5B,SAAgB,wBAAwB,SAAyC;CAC/E,MAAM,aAAa,oBAAoB,KAAK,OAAO;CAEnD,IAAI,YAAY;EACd,MAAM,YAAY,WAAW;EAE7B,IAAI,UAAU,SAAS,GAAG,KAAK,UAAU,SAAS,GAAG,GACnD,OAAO,SACL,YAAY,QAAQ,gQAItB;EAGF,OAAO;CACT;CAEA,IAAI,CAAC,QAAQ,SAAS,GAAG,KAAK,CAAC,QAAQ,SAAS,GAAG,GACjD,OAAO;CAGT,MAAM,SAAS,QAAQ,MAAM,mBAAmB,KAAK,CAAC;CACtD,MAAM,YAAY,OAAO,QAAQ,MAAM,UAAU,KAAK,QAAQ,OAAO,EAAE,GAAG,OAAO;CAEjF,IAAI,UAAU,SAAS,GAAG,KAAK,UAAU,SAAS,GAAG,GACnD,OAAO,SACL,YAAY,QAAQ,wIAEtB;CAGF,IAAI,OAAO,SAAS,GAClB,OAAO,SACL,YAAY,QAAQ,6LAGtB;CAGF,MAAM,CAAC,SAAS;CAEhB,IAAI,cAAc,IAChB,OAAO,SACL,YAAY,QAAQ,yKAGtB;CAGF,MAAM,OAAO,MAAM,MAAM,GAAG,EAAE;CAE9B,IAAI,SAAS,IACX,OAAO,SACL,YAAY,QAAQ,kFAEtB;CAGF,IAAI,KAAK,WAAW,KAAK,GACvB,OAAO,SACL,YAAY,QAAQ,6IAEtB;CAGF,IAAI,qBAAqB,KAAK,IAAI,GAChC,OAAO;CAGT,OAAO,SACL,YAAY,QAAQ,iLAGtB;AACF;;;;;;;;;;AAWA,IAAa,mCAAb,cAAsD,MAAM;CAExC;CACA;CACA;CAHlB,AAAO,YACL,AAAgB,UAChB,AAAgB,SAChB,AAAgB,QAChB;EACA,MACE,IAAI,SAAS,qCAAqC,QAAQ,6BACrD,OAAO,6FAEd;EARgB;EACA;EACA;EAOhB,KAAK,OAAO;CACd;AACF"}