@timber-js/app 0.2.0-alpha.241 → 0.2.0-alpha.242
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/{actions-BCYVyoFl.js → actions-BkwgRwCl.js} +37 -9
- package/dist/_chunks/actions-BkwgRwCl.js.map +1 -0
- package/dist/_chunks/{als-registry-fabsRnPY.js → als-registry-C-iwbtvI.js} +1 -2
- package/dist/_chunks/{als-registry-fabsRnPY.js.map → als-registry-C-iwbtvI.js.map} +1 -1
- package/dist/_chunks/{cache-api-n5FL4wFs.js → cache-api-BGA7c5qJ.js} +5 -5
- package/dist/_chunks/{cache-api-n5FL4wFs.js.map → cache-api-BGA7c5qJ.js.map} +1 -1
- package/dist/_chunks/{chains-IswOWMnq.js → chains-Cuwwjv6T.js} +2 -2
- package/dist/_chunks/{chains-IswOWMnq.js.map → chains-Cuwwjv6T.js.map} +1 -1
- package/dist/_chunks/chains-LGjBHfSN.js +1 -0
- package/dist/_chunks/{classify-B08RCF6s.js → classify-Y8S9C0Na.js} +2 -2
- package/dist/_chunks/{classify-B08RCF6s.js.map → classify-Y8S9C0Na.js.map} +1 -1
- package/dist/_chunks/{cli-check-tpFb6pBU.js → cli-check-KeE1QaIx.js} +3 -3
- package/dist/_chunks/{cli-check-tpFb6pBU.js.map → cli-check-KeE1QaIx.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-DRNJutey.js → cli-schema-sync-DZEF31wd.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-DRNJutey.js.map → cli-schema-sync-DZEF31wd.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-C0pXBtzG.js → cli-schema-sync-_y5O6MIg.js} +1 -1
- package/dist/_chunks/{client-dep-entries-Dw5Dvatr.js → client-dep-entries-DpiwvoDi.js} +2 -2
- package/dist/_chunks/{client-dep-entries-Dw5Dvatr.js.map → client-dep-entries-DpiwvoDi.js.map} +1 -1
- package/dist/_chunks/{convention-lint-BfC_dAhZ.js → convention-lint-0AEsPK2T.js} +19 -5
- package/dist/_chunks/convention-lint-0AEsPK2T.js.map +1 -0
- package/dist/_chunks/dev-server-CboXr8zX.js +1 -0
- package/dist/_chunks/{dev-server-3R6Bl9_R.js → dev-server-DYDr8KIc.js} +2 -3
- package/dist/_chunks/dev-server-DYDr8KIc.js.map +1 -0
- package/dist/_chunks/{error-boundary-Dfhxigko.js → error-boundary-wuNvAJ4n.js} +8 -15
- package/dist/_chunks/error-boundary-wuNvAJ4n.js.map +1 -0
- package/dist/_chunks/{flight-source-node-QOpWZATb.js → flight-source-node-KQsX_OhS.js} +4 -7
- package/dist/_chunks/flight-source-node-KQsX_OhS.js.map +1 -0
- package/dist/_chunks/{json-lossy-check-5KFcC1yt.js → json-lossy-check-BVDALqMf.js} +2 -2
- package/dist/_chunks/{json-lossy-check-5KFcC1yt.js.map → json-lossy-check-BVDALqMf.js.map} +1 -1
- package/dist/_chunks/key-headers-uIig1_mU.js +40 -0
- package/dist/_chunks/key-headers-uIig1_mU.js.map +1 -0
- package/dist/_chunks/{live-graph-D1dfVqoT.js → live-graph-VhzO7Ol9.js} +4 -4
- package/dist/_chunks/{live-graph-D1dfVqoT.js.map → live-graph-VhzO7Ol9.js.map} +1 -1
- package/dist/_chunks/{logger-BvGxPd1e.js → logger-C4m8rfMy.js} +2 -2
- package/dist/_chunks/{logger-BvGxPd1e.js.map → logger-C4m8rfMy.js.map} +1 -1
- package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -1
- package/dist/_chunks/{node-response-D5cfiyWP.js → node-response-8Vz29cGS.js} +2 -2
- package/dist/_chunks/{node-response-D5cfiyWP.js.map → node-response-8Vz29cGS.js.map} +1 -1
- package/dist/_chunks/{poison-scan-CX02ilxN.js → poison-scan-Dpl3ibG-.js} +2 -2
- package/dist/_chunks/{poison-scan-CX02ilxN.js.map → poison-scan-Dpl3ibG-.js.map} +1 -1
- package/dist/_chunks/{scanner-DneYxQoY.js → scanner-CCEHN9Jg.js} +2 -2
- package/dist/_chunks/{scanner-DneYxQoY.js.map → scanner-CCEHN9Jg.js.map} +1 -1
- package/dist/_chunks/{sizeof-BtQ3ErLf.js → sizeof-CIF7fwSJ.js} +2 -2
- package/dist/_chunks/{sizeof-BtQ3ErLf.js.map → sizeof-CIF7fwSJ.js.map} +1 -1
- package/dist/_chunks/{walkers-C9R2A4jN.js → walkers-BbotBhNG.js} +3 -3
- package/dist/_chunks/{walkers-C9R2A4jN.js.map → walkers-BbotBhNG.js.map} +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/analyze/crawl-entry.js +3 -3
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/index.js +2 -2
- package/dist/cache/stores/memory.js +1 -1
- package/dist/cdn/workers-cache-purge.js +1 -1
- package/dist/cli.js +3 -3
- package/dist/client/browser-entry/router-init.d.ts +0 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.js +3 -5
- package/dist/client/internal.js.map +1 -1
- package/dist/client/navigation-commit.d.ts +0 -7
- package/dist/client/navigation-commit.d.ts.map +1 -1
- package/dist/client/outlet-content-cache.d.ts +16 -42
- package/dist/client/outlet-content-cache.d.ts.map +1 -1
- package/dist/client/outlet-scope-context.d.ts +4 -4
- package/dist/client/outlet-scope-context.d.ts.map +1 -1
- package/dist/client/params-context.d.ts +1 -1
- package/dist/client/router-types.d.ts +3 -13
- package/dist/client/router-types.d.ts.map +1 -1
- package/dist/client/router.d.ts.map +1 -1
- package/dist/client/segment-cache.d.ts +2 -2
- package/dist/client/segment-outlet.d.ts +12 -15
- package/dist/client/segment-outlet.d.ts.map +1 -1
- package/dist/client/stale-segment.d.ts +2 -2
- package/dist/config-types.d.ts +0 -17
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/index.js +7 -8
- package/dist/index.js.map +1 -1
- package/dist/native/rsc/manifest.json +2 -4
- package/dist/native/rsc/routing/segment-keys.js.map +1 -1
- package/dist/native/rsc/server/als-registry.js +1 -2
- package/dist/native/rsc/server/als-registry.js.map +1 -1
- package/dist/native/rsc/server/client-state-tree.js +1 -5
- package/dist/native/rsc/server/client-state-tree.js.map +1 -1
- package/dist/native/rsc/server/flight-source-node.js +2 -5
- package/dist/native/rsc/server/flight-source-node.js.map +1 -1
- package/dist/native/rsc/server/flight-source.js +6 -41
- package/dist/native/rsc/server/flight-source.js.map +1 -1
- package/dist/native/rsc/server/framework-stack-frames.js.map +1 -1
- package/dist/native/rsc/server/request-context.js +3 -3
- package/dist/native/rsc/server/request-context.js.map +1 -1
- package/dist/native/rsc/server/route-element-builder.js +5 -5
- package/dist/native/rsc/server/route-element-builder.js.map +1 -1
- package/dist/native/rsc/server/rsc-entry/render-route.js +4 -30
- package/dist/native/rsc/server/rsc-entry/render-route.js.map +1 -1
- package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js +0 -2
- package/dist/native/rsc/server/rsc-entry/revalidate-renderer.js.map +1 -1
- package/dist/native/rsc/server/rsc-entry/rsc-stream.js +2 -5
- package/dist/native/rsc/server/rsc-entry/rsc-stream.js.map +1 -1
- package/dist/native/rsc/server/segment-lifetime/outlet-gate.js +44 -0
- package/dist/native/rsc/server/segment-lifetime/outlet-gate.js.map +1 -0
- package/dist/native/rsc/server/segment-lifetime/read-rule.js +25 -3
- package/dist/native/rsc/server/segment-lifetime/read-rule.js.map +1 -1
- package/dist/native/rsc/server/segment-lifetime/read-scope.js +3 -2
- package/dist/native/rsc/server/segment-lifetime/read-scope.js.map +1 -1
- package/dist/native/rsc/server/segment-lifetime/segment-key.js +17 -3
- package/dist/native/rsc/server/segment-lifetime/segment-key.js.map +1 -1
- package/dist/native/rsc/server/segment-lifetime/slot-outlets.js +4 -4
- package/dist/native/rsc/server/segment-lifetime/slot-outlets.js.map +1 -1
- package/dist/native/rsc/server/slot-resolver.js +3 -3
- package/dist/native/rsc/server/slot-resolver.js.map +1 -1
- package/dist/native/rsc/server/vite-handoff-rsc.js.map +1 -1
- package/dist/native/rsc/shared/key-headers.js +20 -0
- package/dist/native/rsc/shared/key-headers.js.map +1 -0
- package/dist/native/rsc/shared/outlet-decision.js.map +1 -1
- package/dist/native/ssr/client/outlet-content-cache.js +6 -26
- package/dist/native/ssr/client/outlet-content-cache.js.map +1 -1
- package/dist/native/ssr/client/outlet-scope-context.js.map +1 -1
- package/dist/native/ssr/client/segment-outlet.js +6 -19
- package/dist/native/ssr/client/segment-outlet.js.map +1 -1
- package/dist/native/ssr/manifest.json +1 -1
- package/dist/native/ssr/server/als-registry.js +0 -1
- package/dist/native/ssr/server/als-registry.js.map +1 -1
- package/dist/native/ssr/server/client-state-tree.js +1 -5
- package/dist/native/ssr/server/client-state-tree.js.map +1 -1
- package/dist/native/ssr/server/flight-source-node.js +2 -5
- package/dist/native/ssr/server/flight-source-node.js.map +1 -1
- package/dist/native/ssr/server/flight-source.js +0 -1
- package/dist/native/ssr/server/flight-source.js.map +1 -1
- package/dist/native/ssr/server/framework-stack-frames.js.map +1 -1
- package/dist/native/ssr/server/request-context.js +3 -3
- package/dist/native/ssr/server/request-context.js.map +1 -1
- package/dist/native/ssr/server/segment-lifetime/read-rule.js +25 -3
- package/dist/native/ssr/server/segment-lifetime/read-rule.js.map +1 -1
- package/dist/native/ssr/server/vite-handoff-rsc.js.map +1 -1
- package/dist/native/ssr/shared/key-headers.js +13 -0
- package/dist/native/ssr/shared/key-headers.js.map +1 -0
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/routing/route-options.d.ts.map +1 -1
- package/dist/routing/segment-keys.d.ts +3 -4
- package/dist/routing/segment-keys.d.ts.map +1 -1
- package/dist/server/als-registry.d.ts +2 -16
- package/dist/server/als-registry.d.ts.map +1 -1
- package/dist/server/client-state-tree.d.ts +5 -11
- package/dist/server/client-state-tree.d.ts.map +1 -1
- package/dist/server/flight-source-node.d.ts +1 -6
- package/dist/server/flight-source-node.d.ts.map +1 -1
- package/dist/server/flight-source.d.ts +0 -27
- package/dist/server/flight-source.d.ts.map +1 -1
- package/dist/server/framework-stack-frames.d.ts +1 -4
- package/dist/server/framework-stack-frames.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +13 -23
- package/dist/server/internal.js.map +1 -1
- package/dist/server/request-context.d.ts.map +1 -1
- package/dist/server/route-element-builder.d.ts +2 -2
- package/dist/server/route-element-builder.d.ts.map +1 -1
- package/dist/server/rsc-entry/helpers.d.ts +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/render-route.d.ts +0 -1
- package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
- package/dist/server/rsc-entry/revalidate-renderer.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-stream.d.ts +2 -11
- package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
- package/dist/server/segment-lifetime/outlet-gate.d.ts +58 -0
- package/dist/server/segment-lifetime/outlet-gate.d.ts.map +1 -0
- package/dist/server/segment-lifetime/read-rule.d.ts +13 -3
- package/dist/server/segment-lifetime/read-rule.d.ts.map +1 -1
- package/dist/server/segment-lifetime/read-scope.d.ts +2 -1
- package/dist/server/segment-lifetime/read-scope.d.ts.map +1 -1
- package/dist/server/segment-lifetime/segment-key.d.ts +3 -0
- package/dist/server/segment-lifetime/segment-key.d.ts.map +1 -1
- package/dist/server/segment-lifetime/slot-outlets.d.ts +2 -2
- package/dist/server/segment-lifetime/slot-outlets.d.ts.map +1 -1
- package/dist/server/slot-resolver.d.ts +5 -5
- package/dist/server/slot-resolver.d.ts.map +1 -1
- package/dist/server/types.d.ts +8 -2
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/vite-handoff-rsc.d.ts +1 -10
- package/dist/server/vite-handoff-rsc.d.ts.map +1 -1
- package/dist/shared/key-headers.d.ts +13 -0
- package/dist/shared/key-headers.d.ts.map +1 -0
- package/dist/shared/outlet-decision.d.ts +13 -44
- package/dist/shared/outlet-decision.d.ts.map +1 -1
- package/dist/shared/payload-root.d.ts +1 -1
- package/dist/shared/segment-info.d.ts +3 -7
- package/dist/shared/segment-info.d.ts.map +1 -1
- package/docs/api/30-api-server.mdx +1 -1
- package/package.json +1 -1
- package/src/client/browser-entry/index.ts +0 -2
- package/src/client/browser-entry/router-init.ts +2 -4
- package/src/client/error-boundary.tsx +1 -1
- package/src/client/navigation-commit.ts +4 -18
- package/src/client/outlet-content-cache.ts +24 -62
- package/src/client/outlet-scope-context.ts +5 -5
- package/src/client/params-context.ts +1 -1
- package/src/client/router-types.ts +3 -14
- package/src/client/router.ts +0 -2
- package/src/client/rsc-fetch.ts +1 -1
- package/src/client/segment-cache.ts +2 -2
- package/src/client/segment-outlet.tsx +19 -51
- package/src/client/stale-segment.ts +2 -2
- package/src/config-types.ts +0 -17
- package/src/config-validation.ts +0 -1
- package/src/plugins/entries.ts +0 -1
- package/src/routing/route-options.ts +20 -4
- package/src/routing/scanner.ts +1 -1
- package/src/routing/segment-keys.ts +3 -4
- package/src/rsc-runtime/vendor-types.d.ts +1 -1
- package/src/server/als-registry.ts +2 -23
- package/src/server/client-state-tree.ts +7 -18
- package/src/server/flight-source-node.ts +1 -5
- package/src/server/flight-source.ts +1 -81
- package/src/server/framework-stack-frames.ts +1 -4
- package/src/server/request-context.ts +6 -5
- package/src/server/route-element-builder.ts +13 -14
- package/src/server/rsc-entry/helpers.ts +1 -1
- package/src/server/rsc-entry/index.ts +0 -3
- package/src/server/rsc-entry/render-route.ts +7 -54
- package/src/server/rsc-entry/revalidate-renderer.ts +0 -2
- package/src/server/rsc-entry/rsc-stream.ts +3 -23
- package/src/server/segment-lifetime/outlet-gate.ts +102 -0
- package/src/server/segment-lifetime/read-rule.ts +63 -6
- package/src/server/segment-lifetime/read-scope.ts +4 -2
- package/src/server/segment-lifetime/segment-key.ts +31 -3
- package/src/server/segment-lifetime/slot-outlets.ts +5 -5
- package/src/server/slot-resolver.ts +8 -8
- package/src/server/types.ts +8 -2
- package/src/server/vite-handoff-rsc.ts +1 -12
- package/src/shared/key-headers.ts +42 -0
- package/src/shared/outlet-decision.ts +13 -48
- package/src/shared/payload-root.ts +1 -1
- package/src/shared/segment-info.ts +3 -7
- package/dist/_chunks/actions-BCYVyoFl.js.map +0 -1
- package/dist/_chunks/chains-DPZAMMav.js +0 -1
- package/dist/_chunks/convention-lint-BfC_dAhZ.js.map +0 -1
- package/dist/_chunks/dev-server-3DNTXQV-.js +0 -1
- package/dist/_chunks/dev-server-3R6Bl9_R.js.map +0 -1
- package/dist/_chunks/error-boundary-Dfhxigko.js.map +0 -1
- package/dist/_chunks/flight-source-node-QOpWZATb.js.map +0 -1
- package/dist/native/rsc/server/segment-hash/capture.js +0 -107
- package/dist/native/rsc/server/segment-hash/capture.js.map +0 -1
- package/dist/native/rsc/server/segment-hash/outlet.js +0 -101
- package/dist/native/rsc/server/segment-hash/outlet.js.map +0 -1
- package/dist/native/rsc/server/segment-hash/stream-tap.js +0 -139
- package/dist/native/rsc/server/segment-hash/stream-tap.js.map +0 -1
- package/dist/native/rsc/server/segment-hash/value-hash.js +0 -171
- package/dist/native/rsc/server/segment-hash/value-hash.js.map +0 -1
- package/dist/native/ssr/server/segment-hash/value-hash.js +0 -162
- package/dist/native/ssr/server/segment-hash/value-hash.js.map +0 -1
- package/dist/server/segment-hash/capture.d.ts +0 -77
- package/dist/server/segment-hash/capture.d.ts.map +0 -1
- package/dist/server/segment-hash/outlet.d.ts +0 -93
- package/dist/server/segment-hash/outlet.d.ts.map +0 -1
- package/dist/server/segment-hash/stream-tap.d.ts +0 -49
- package/dist/server/segment-hash/stream-tap.d.ts.map +0 -1
- package/dist/server/segment-hash/value-hash.d.ts +0 -70
- package/dist/server/segment-hash/value-hash.d.ts.map +0 -1
- package/src/server/segment-hash/capture.ts +0 -232
- package/src/server/segment-hash/outlet.ts +0 -229
- package/src/server/segment-hash/stream-tap.ts +0 -244
- package/src/server/segment-hash/value-hash.ts +0 -338
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-response-D5cfiyWP.js","names":[],"sources":["../../src/server/abort-scope.ts","../../src/server/render-utils.ts","../../src/server/stream-utils.ts","../../src/server/node-response.ts"],"sourcesContent":["/**\n * Abort listeners scoped to the work they guard.\n *\n * A request's signal outlives the render, stream, or timer that listens to\n * it, and a listener left on it keeps everything its closure holds reachable\n * from the request. In production that only delays collection until the\n * request is garbage. In dev it pins the request forever: React's dev Flight\n * server tracks every live promise in an async-hook Map whose debug chains\n * reach the request, so any promise reachable from the request is never\n * collected and never leaves that Map (TIM-1589).\n *\n * So server code never calls `signal.addEventListener('abort', …)` itself\n * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}\n * takes the end of the listener's scope as a required argument, which makes\n * a listener without a removal unwritable.\n */\n\n/**\n * Call `onAbort` if `signal` aborts before the scope `until` ends. If\n * `signal` has already aborted, `onAbort` runs now.\n *\n * `until` is the scope: a promise (the listener is removed when it fulfills\n * or rejects, a microtask later) or an `AbortSignal` (removed synchronously\n * when it aborts; use one when an abort later in the same tick must not\n * fire, as after a timeout's `cancel()`).\n */\nexport function onAbortUntil(\n signal: AbortSignal | undefined,\n onAbort: () => void,\n until: PromiseLike<unknown> | AbortSignal\n): void {\n if (!signal) return;\n if (signal.aborted) {\n onAbort();\n return;\n }\n let scope: AbortSignal;\n if (until instanceof AbortSignal) {\n scope = until;\n } else {\n const ended = new AbortController();\n const end = (): void => endScope(ended);\n until.then(end, end);\n scope = ended.signal;\n }\n // addEventListener's own `signal` option removes the listener when the\n // scope aborts: the platform's one-step removal, no handle to keep.\n signal.addEventListener('abort', onAbort, { once: true, signal: scope });\n}\n\n/**\n * The reason every scope controller aborts with. Nothing reads a scope\n * signal's reason (it only removes listeners, through addEventListener's\n * `signal` option), and `abort()` with no reason builds a DOMException, stack\n * trace included, on every call: several per request, ~1.8% of an HTML\n * request's CPU (TIM-1626).\n */\nconst SCOPE_ENDED: unique symbol = Symbol('timber.scope-ended');\n\n/**\n * End a scope: abort a server-private controller whose signal only bounds\n * listeners (an `onAbortUntil` `until`). Never use it on a signal anything\n * reads a reason from — a render, fetch or stream would see this symbol\n * instead of an AbortError.\n */\nexport function endScope(scope: AbortController): void {\n scope.abort(SCOPE_ENDED);\n}\n","/**\n * Shared render-phase utilities — used by both the Node.js and Web\n * stream wrappers. Pure functions only; no stream-shape dependencies.\n *\n * Consolidated from duplicated copies in node-stream-transforms.ts,\n * ssr-render.ts, and rsc-entry/helpers.ts. See TIM-1071 item 1.\n */\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` in csp-nonce.ts and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n\n/**\n * The reason to abort a render with when its consumer releases it.\n *\n * The framework releases a Flight render it no longer needs — the renderer\n * once a deny or redirect is captured, a tee once either branch is done —\n * usually without a reason. React then reports the abort to the render's\n * `onError` as a plain `Error(\"The render was aborted by the server without a\n * reason.\")`, which reads as an application failure: a `metadata()` that\n * denies while the page is still fetching logged an unhandled render error\n * (TIM-1597). An `AbortError` is what {@link isAbortError} already treats as\n * not-an-error. A reason the caller did pass (a timeout, the tee's divergence\n * guard) is kept, so those still reach the log.\n */\nexport function releaseReason(reason: unknown): unknown {\n return reason ?? new DOMException('The render was released by its consumer.', 'AbortError');\n}\n\n/**\n * Check if an error is an abort error (connection closed by client).\n *\n * When the browser aborts a request (page refresh, navigation away),\n * the AbortSignal fires and React/streams throw an AbortError. This\n * is not an application error — suppress it from error boundaries and logs.\n *\n * A native `ReadableStream.tee()` cancels its source with an array of both\n * branches' reasons (Streams spec, ReadableStreamDefaultTee), so a Web\n * render released through a tee is aborted with `[reason1, reason2]`. That is\n * an abort when every entry is — a tee whose branches were both released\n * ({@link releaseReason}) — and an error when any entry is, such as the\n * divergence guard's.\n */\nexport function isAbortError(error: unknown): boolean {\n if (Array.isArray(error)) return error.length > 0 && error.every(isAbortError);\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n/**\n * Inline script that adds `<meta name=\"robots\" content=\"noindex\">` to the\n * document head. Injected when a render-phase error replaces the shell so\n * search engines don't index error pages.\n *\n * MUST be byte-identical across all stream wrappers (Node and Web) for a\n * given nonce to ensure consistent Content-Length headers — which is why\n * both wrappers call this one function rather than inlining the string.\n */\nexport function noindexScript(nonce?: string): string {\n return `<script${nonceAttr(nonce)}>document.head.appendChild(Object.assign(document.createElement(\"meta\"),{name:\"robots\",content:\"noindex\"}))</script>`;\n}\n","/**\n * Stream utilities for the RSC rendering pipeline.\n *\n * teeWithErrorPropagation — wraps native ReadableStream.tee() with:\n * 1. Cross-branch error propagation (error on one branch cancels the other)\n * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)\n *\n * This prevents two classes of bugs:\n * - Silent stalls when one tee branch errors and the other hangs indefinitely\n * - Unbounded memory growth when one consumer (SSR) is much slower than the other\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\"\n */\n\nimport { getLogger } from './logger.ts';\n\n/** Default maximum buffer divergence before cancellation (5MB). */\nexport const DEFAULT_MAX_BUFFER_BYTES = 5 * 1024 * 1024;\n\nexport interface TeeOptions {\n /**\n * Maximum byte divergence between the two branches before both are\n * cancelled. When one branch has consumed this many more bytes than\n * the other, the tee's internal buffer is at least this large.\n *\n * Default: 5MB.\n */\n maxBufferBytes?: number;\n}\n\n/**\n * Tee a ReadableStream with error propagation and buffer monitoring.\n *\n * Delegates to the native `stream.tee()` for the actual forking, then wraps\n * each branch in a ReadableStream that:\n * - Tracks bytes consumed per branch\n * - Cancels both branches if byte divergence exceeds `maxBufferBytes`\n * - Cancels the other branch if either branch is cancelled or errors\n *\n * The returned streams are drop-in replacements for the native tee branches.\n */\nexport function teeWithErrorPropagation(\n stream: ReadableStream<Uint8Array>,\n options?: TeeOptions\n): [ReadableStream<Uint8Array>, ReadableStream<Uint8Array>] {\n const maxBuffer = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n const [rawBranch1, rawBranch2] = stream.tee();\n\n // Shared state for cross-branch coordination\n let consumed1 = 0;\n let consumed2 = 0;\n let cancelled = false;\n\n // Readers and controllers are assigned when wrapBranch creates the wrapped\n // streams. We store them so cancelBoth can cancel raw tee branches AND\n // error the wrapped stream controllers for cross-branch propagation.\n let rawReader1: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rawReader2: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let controller1: ReadableStreamDefaultController<Uint8Array> | undefined;\n let controller2: ReadableStreamDefaultController<Uint8Array> | undefined;\n\n /**\n * Cancel both tee branches. `initiator` is the branch index (0 or 1)\n * that triggered the cancellation — its controller is already being\n * closed/errored by the pull/cancel that triggered this, so we skip it.\n * Pass -1 to cancel+error both (e.g., from the buffer divergence guard).\n *\n * Both raw readers are always canceled regardless of initiator, because\n * the tee source stream is only released when both branches are canceled.\n * ReadableStreamDefaultReader.cancel() is idempotent, so double-cancel\n * is safe.\n */\n function cancelBoth(reason: unknown, initiator: number = -1): void {\n if (cancelled) return;\n cancelled = true;\n // Cancel both raw readers — tee source requires both branches canceled.\n rawReader1?.cancel(reason).catch(() => {});\n rawReader2?.cancel(reason).catch(() => {});\n // Error wrapped controllers so consumers see the failure.\n // Skip the initiator's controller — it's already being closed/errored.\n if (initiator !== 0) {\n try {\n controller1?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n if (initiator !== 1) {\n try {\n controller2?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n }\n\n function wrapBranch(\n branchIndex: number,\n rawBranch: ReadableStream<Uint8Array>,\n assignReader: (r: ReadableStreamDefaultReader<Uint8Array>) => void,\n assignController: (c: ReadableStreamDefaultController<Uint8Array>) => void,\n addConsumed: (n: number) => void,\n getSelfConsumed: () => number,\n getOtherConsumed: () => number\n ): ReadableStream<Uint8Array> {\n const reader = rawBranch.getReader();\n assignReader(reader);\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n assignController(controller);\n },\n\n async pull(controller) {\n if (cancelled) {\n return;\n }\n\n try {\n const { done, value } = await reader.read();\n\n // Re-check after await — cancelBoth may have fired while we\n // were waiting on the raw reader.\n if (cancelled) return;\n\n if (done) {\n try {\n controller.close();\n } catch {\n /* controller already errored by cancelBoth */\n }\n return;\n }\n\n addConsumed(value.byteLength);\n\n // Check buffer divergence: the difference in consumed bytes\n // approximates the tee's internal buffer size.\n const divergence = getSelfConsumed() - getOtherConsumed();\n if (divergence > maxBuffer) {\n cancelBoth(teeBufferExceeded(maxBuffer, divergence));\n return;\n }\n\n controller.enqueue(value);\n } catch (err) {\n if (!cancelled) {\n // Source stream errored — propagate to both branches.\n // cancelBoth with initiator skips our own controller,\n // so we error it explicitly here.\n cancelBoth(err, branchIndex);\n try {\n controller.error(err);\n } catch {\n /* already closed/errored */\n }\n }\n }\n },\n\n cancel(reason) {\n // Consumer cancelled this branch — propagate to the other\n cancelBoth(reason, branchIndex);\n },\n });\n }\n\n const wrapped1 = wrapBranch(\n 0,\n rawBranch1,\n (r) => {\n rawReader1 = r;\n },\n (c) => {\n controller1 = c;\n },\n (n) => {\n consumed1 += n;\n },\n () => consumed1,\n () => consumed2\n );\n\n const wrapped2 = wrapBranch(\n 1,\n rawBranch2,\n (r) => {\n rawReader2 = r;\n },\n (c) => {\n controller2 = c;\n },\n (n) => {\n consumed2 += n;\n },\n () => consumed2,\n () => consumed1\n );\n\n return [wrapped1, wrapped2];\n}\n\n/**\n * Stream-lifecycle timing for one response body: firstChunk, lastChunk,\n * close, maxGap (largest inter-chunk gap), chunk count, and byte count,\n * logged once when the stream terminates (clean close OR\n * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`. The\n * Web body wrapper below and the Node body (`node-body-response.ts`) feed\n * the same recorder, so the two report identically.\n */\nexport interface StreamTimingRecorder {\n chunk(byteLength: number): void;\n end(cancelled: boolean): void;\n}\n\nexport function createStreamTimingRecorder(startTime: number): StreamTimingRecorder {\n let firstChunkMs = 0;\n let lastChunkMs = 0;\n let maxGapMs = 0;\n let prevChunkTime = 0;\n let chunks = 0;\n let bytes = 0;\n let ended = false;\n\n return {\n chunk(byteLength) {\n const now = performance.now();\n const relativeMs = Math.round(now - startTime);\n if (chunks === 0) {\n firstChunkMs = relativeMs;\n } else {\n const gap = Math.round(now - prevChunkTime);\n if (gap > maxGapMs) maxGapMs = gap;\n }\n prevChunkTime = now;\n lastChunkMs = relativeMs;\n chunks++;\n bytes += byteLength;\n },\n end(cancelled) {\n if (ended) return;\n ended = true;\n const closeMs = Math.round(performance.now() - startTime);\n getLogger().debug('stream-lifecycle', {\n firstChunkMs,\n lastChunkMs,\n closeMs,\n maxGapMs,\n chunks,\n bytes,\n ...(cancelled ? { cancelled: true } : {}),\n });\n },\n };\n}\n\n/**\n * Wrap a Web response body with stream-lifecycle timing instrumentation\n * ({@link createStreamTimingRecorder}).\n *\n * Uses a manual reader pump to guarantee logging on all termination\n * paths — TransformStream.flush() is not called on cancellation.\n */\nexport function wrapResponseWithStreamTiming(\n body: ReadableStream<Uint8Array>,\n startTime: number\n): ReadableStream<Uint8Array> {\n const timing = createStreamTimingRecorder(startTime);\n const reader = body.getReader();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n timing.end(false);\n controller.close();\n return;\n }\n timing.chunk(value.byteLength);\n controller.enqueue(value);\n } catch (err) {\n timing.end(false);\n controller.error(err);\n }\n },\n\n cancel(reason) {\n timing.end(true);\n reader.cancel(reason).catch(() => {});\n },\n });\n}\n\n/** Format bytes as human-readable string (e.g., \"5.00 MB\"). */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n}\n\n/**\n * The error both tee implementations (this Web one and the Node one in\n * `flight-source-node.ts`) cancel with when one branch lags the other by more\n * than `maxBuffer` bytes. Warns once, here, so the two cannot drift.\n */\nexport function teeBufferExceeded(maxBuffer: number, divergence: number): Error {\n const error = new Error(\n `RSC stream tee buffer exceeded ${formatBytes(maxBuffer)} ` +\n `(divergence: ${formatBytes(divergence)}). ` +\n `This usually means SSR is much slower than the inline stream consumer. ` +\n `Consider reducing RSC payload size or increasing the tee buffer limit.`\n );\n console.warn(`[timber] ${error.message}`);\n return error;\n}\n\n/**\n * A pull reader over any chunk stream: a Web reader, or the Flight reader in\n * `flight-source.ts`, which reads a Node or Web Flight source.\n */\nexport interface ChunkReader<T> {\n read(): Promise<ReadableStreamReadResult<T>>;\n cancel(reason?: unknown): void;\n}\n\n/**\n * Read a chunk stream to completion under one overall deadline. Every read\n * is raced against the time remaining, and the reader is cancelled on every\n * exit, so a stalled upstream never outlives the deadline. See\n * design/02-rendering-pipeline.md §\"Always Timeout-Guard Stream Reads\".\n *\n * @param label - Prefix for the timeout error message. Both ways the deadline\n * can pass (between reads, or while a read is pending) reject with the same\n * `${label} did not complete within ${timeoutMs}ms`.\n */\nexport async function drainWithDeadline<T>(\n reader: ChunkReader<T>,\n timeoutMs: number,\n label: string\n): Promise<T[]> {\n const chunks: T[] = [];\n const deadline = Date.now() + timeoutMs;\n const deadlineError = () => new Error(`${label} did not complete within ${timeoutMs}ms`);\n try {\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw deadlineError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(deadlineError()), remaining);\n });\n let result: Awaited<ReturnType<ChunkReader<T>['read']>>;\n try {\n result = await Promise.race([reader.read(), timeout]);\n } finally {\n clearTimeout(timer);\n }\n if (result.done) return chunks;\n chunks.push(result.value);\n }\n } finally {\n reader.cancel();\n }\n}\n\n/** Concatenate byte chunks into one array. */\nexport function concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Read a byte stream to completion under one overall deadline and return\n * the concatenated bytes ({@link drainWithDeadline}). The static generator's\n * body drain uses it; Flight renders use `collectFlightBytes`\n * (`flight-source.ts`), which reads either source kind the same way.\n */\nexport async function readAllBytesWithDeadline(\n stream: ReadableStream<Uint8Array>,\n timeoutMs: number,\n label: string\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks = await drainWithDeadline(\n { read: () => reader.read(), cancel: (reason) => void reader.cancel(reason).catch(() => {}) },\n timeoutMs,\n label\n );\n return concatBytes(chunks);\n}\n","/**\n * Responses with a Node body — the platform-neutral half.\n *\n * On Node, SSR's HTML and Flight payload bodies are Node `Readable`s. They\n * travel the pipeline as a `NodeBodyResponse` (`node-body-response.ts`, Node\n * only): a real `Response` whose body stays a Node stream until the adapter\n * pipes it to the socket, so a response is never converted Node → Web → Node\n * (LOCAL-1475). srvx (nitro, the dev server) and nitro-preview's sender take\n * the Node body through `_toNodeResponse()`. Any code that reads the body\n * through the Web API still works: the response then converts once.\n *\n * Pipeline code shared with Workers re-wraps, strips, or times a response\n * through the helpers here, which ask the response itself to do the Node\n * work, so this module never imports `node:stream`. A response is recognised\n * by a `Symbol.for` brand, not `instanceof`: the RSC and SSR environments\n * load separate copies of the class.\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport type { Duplex } from 'node:stream';\n\n/** The brand a Node-body response carries, keyed by a registry symbol. */\nexport const NODE_BODY = Symbol.for('timber.response.nodeBody');\n\n/**\n * What a Node-body response can do with its body, for code that cannot import\n * the class: platform-neutral modules, and the standalone `_compress.mjs`,\n * which reaches these through the same registry symbol. Each one takes the\n * body: the response it was called on no longer has one.\n */\nexport interface NodeBodyOps {\n /**\n * Whether the response still owns a body. False for a null-body status\n * (204, 205, 304, …) and once the body was taken. Being branded says\n * nothing about this — ask here instead of reading `.body`, which would\n * convert it.\n */\n readonly hasBody: boolean;\n /** The same body under a new status and headers. */\n rewrap(init: ResponseInit): Response;\n /** Release the body unread (HEAD, a discarded document), aborting its producer. */\n discard(): void;\n /** The same body, reporting stream timing when it ends (detailed Server-Timing). */\n timed(startTime: number): Response;\n /**\n * The body piped through `stream` (gzip), as a Node-body response under\n * `init`. An error or destroy on either end tears down both.\n */\n through(stream: Duplex, init: ResponseInit): Response;\n}\n\ninterface NodeBodyBranded {\n [NODE_BODY]: NodeBodyOps;\n}\n\nfunction isNodeBodyBranded(response: Response): response is Response & NodeBodyBranded {\n return NODE_BODY in response;\n}\n\n/** The Node-body operations of `response`, or `null` for a Web-body response. */\nexport function nodeBodyOps(response: Response): NodeBodyOps | null {\n return isNodeBodyBranded(response) ? response[NODE_BODY] : null;\n}\n\n/**\n * `response`'s body under a new status and headers. A Node body moves to the\n * new response without converting; a Web body is reused as is.\n */\nexport function withResponseInit(response: Response, init: ResponseInit): Response {\n return nodeBodyOps(response)?.rewrap(init) ?? new Response(response.body, init);\n}\n\n/**\n * Release a response's body unread. A live producer (an SSR render, a Flight\n * render) is behind it; dropping the reference without this leaks it for the\n * lifetime of the render (design/13-security.md A4).\n */\nexport function discardResponseBody(response: Response): void {\n const ops = nodeBodyOps(response);\n if (ops) {\n ops.discard();\n return;\n }\n // `cancel()` rejects if the stream is already errored and throws\n // synchronously if it is locked — neither is actionable, the body is being\n // discarded either way.\n try {\n response.body?.cancel().catch(() => {});\n } catch {\n /* stream already locked or disturbed */\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aACd,QACA,SACA,OACM;CACN,IAAI,CAAC,QAAQ;CACb,IAAI,OAAO,SAAS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CAAC;CACxC,QAAQ,CAER;AACF"}
|
|
1
|
+
{"version":3,"file":"node-response-8Vz29cGS.js","names":[],"sources":["../../src/server/abort-scope.ts","../../src/server/render-utils.ts","../../src/server/stream-utils.ts","../../src/server/node-response.ts"],"sourcesContent":["/**\n * Abort listeners scoped to the work they guard.\n *\n * A request's signal outlives the render, stream, or timer that listens to\n * it, and a listener left on it keeps everything its closure holds reachable\n * from the request. In production that only delays collection until the\n * request is garbage. In dev it pins the request forever: React's dev Flight\n * server tracks every live promise in an async-hook Map whose debug chains\n * reach the request, so any promise reachable from the request is never\n * collected and never leaves that Map (TIM-1589).\n *\n * So server code never calls `signal.addEventListener('abort', …)` itself\n * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}\n * takes the end of the listener's scope as a required argument, which makes\n * a listener without a removal unwritable.\n */\n\n/**\n * Call `onAbort` if `signal` aborts before the scope `until` ends. If\n * `signal` has already aborted, `onAbort` runs now.\n *\n * `until` is the scope: a promise (the listener is removed when it fulfills\n * or rejects, a microtask later) or an `AbortSignal` (removed synchronously\n * when it aborts; use one when an abort later in the same tick must not\n * fire, as after a timeout's `cancel()`).\n */\nexport function onAbortUntil(\n signal: AbortSignal | undefined,\n onAbort: () => void,\n until: PromiseLike<unknown> | AbortSignal\n): void {\n if (!signal) return;\n if (signal.aborted) {\n onAbort();\n return;\n }\n let scope: AbortSignal;\n if (until instanceof AbortSignal) {\n scope = until;\n } else {\n const ended = new AbortController();\n const end = (): void => endScope(ended);\n until.then(end, end);\n scope = ended.signal;\n }\n // addEventListener's own `signal` option removes the listener when the\n // scope aborts: the platform's one-step removal, no handle to keep.\n signal.addEventListener('abort', onAbort, { once: true, signal: scope });\n}\n\n/**\n * The reason every scope controller aborts with. Nothing reads a scope\n * signal's reason (it only removes listeners, through addEventListener's\n * `signal` option), and `abort()` with no reason builds a DOMException, stack\n * trace included, on every call: several per request, ~1.8% of an HTML\n * request's CPU (TIM-1626).\n */\nconst SCOPE_ENDED: unique symbol = Symbol('timber.scope-ended');\n\n/**\n * End a scope: abort a server-private controller whose signal only bounds\n * listeners (an `onAbortUntil` `until`). Never use it on a signal anything\n * reads a reason from — a render, fetch or stream would see this symbol\n * instead of an AbortError.\n */\nexport function endScope(scope: AbortController): void {\n scope.abort(SCOPE_ENDED);\n}\n","/**\n * Shared render-phase utilities — used by both the Node.js and Web\n * stream wrappers. Pure functions only; no stream-shape dependencies.\n *\n * Consolidated from duplicated copies in node-stream-transforms.ts,\n * ssr-render.ts, and rsc-entry/helpers.ts. See TIM-1071 item 1.\n */\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` in csp-nonce.ts and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n\n/**\n * The reason to abort a render with when its consumer releases it.\n *\n * The framework releases a Flight render it no longer needs — the renderer\n * once a deny or redirect is captured, a tee once either branch is done —\n * usually without a reason. React then reports the abort to the render's\n * `onError` as a plain `Error(\"The render was aborted by the server without a\n * reason.\")`, which reads as an application failure: a `metadata()` that\n * denies while the page is still fetching logged an unhandled render error\n * (TIM-1597). An `AbortError` is what {@link isAbortError} already treats as\n * not-an-error. A reason the caller did pass (a timeout, the tee's divergence\n * guard) is kept, so those still reach the log.\n */\nexport function releaseReason(reason: unknown): unknown {\n return reason ?? new DOMException('The render was released by its consumer.', 'AbortError');\n}\n\n/**\n * Check if an error is an abort error (connection closed by client).\n *\n * When the browser aborts a request (page refresh, navigation away),\n * the AbortSignal fires and React/streams throw an AbortError. This\n * is not an application error — suppress it from error boundaries and logs.\n *\n * A native `ReadableStream.tee()` cancels its source with an array of both\n * branches' reasons (Streams spec, ReadableStreamDefaultTee), so a Web\n * render released through a tee is aborted with `[reason1, reason2]`. That is\n * an abort when every entry is — a tee whose branches were both released\n * ({@link releaseReason}) — and an error when any entry is, such as the\n * divergence guard's.\n */\nexport function isAbortError(error: unknown): boolean {\n if (Array.isArray(error)) return error.length > 0 && error.every(isAbortError);\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n/**\n * Inline script that adds `<meta name=\"robots\" content=\"noindex\">` to the\n * document head. Injected when a render-phase error replaces the shell so\n * search engines don't index error pages.\n *\n * MUST be byte-identical across all stream wrappers (Node and Web) for a\n * given nonce to ensure consistent Content-Length headers — which is why\n * both wrappers call this one function rather than inlining the string.\n */\nexport function noindexScript(nonce?: string): string {\n return `<script${nonceAttr(nonce)}>document.head.appendChild(Object.assign(document.createElement(\"meta\"),{name:\"robots\",content:\"noindex\"}))</script>`;\n}\n","/**\n * Stream utilities for the RSC rendering pipeline.\n *\n * teeWithErrorPropagation — wraps native ReadableStream.tee() with:\n * 1. Cross-branch error propagation (error on one branch cancels the other)\n * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)\n *\n * This prevents two classes of bugs:\n * - Silent stalls when one tee branch errors and the other hangs indefinitely\n * - Unbounded memory growth when one consumer (SSR) is much slower than the other\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\"\n */\n\nimport { getLogger } from './logger.ts';\n\n/** Default maximum buffer divergence before cancellation (5MB). */\nexport const DEFAULT_MAX_BUFFER_BYTES = 5 * 1024 * 1024;\n\nexport interface TeeOptions {\n /**\n * Maximum byte divergence between the two branches before both are\n * cancelled. When one branch has consumed this many more bytes than\n * the other, the tee's internal buffer is at least this large.\n *\n * Default: 5MB.\n */\n maxBufferBytes?: number;\n}\n\n/**\n * Tee a ReadableStream with error propagation and buffer monitoring.\n *\n * Delegates to the native `stream.tee()` for the actual forking, then wraps\n * each branch in a ReadableStream that:\n * - Tracks bytes consumed per branch\n * - Cancels both branches if byte divergence exceeds `maxBufferBytes`\n * - Cancels the other branch if either branch is cancelled or errors\n *\n * The returned streams are drop-in replacements for the native tee branches.\n */\nexport function teeWithErrorPropagation(\n stream: ReadableStream<Uint8Array>,\n options?: TeeOptions\n): [ReadableStream<Uint8Array>, ReadableStream<Uint8Array>] {\n const maxBuffer = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n const [rawBranch1, rawBranch2] = stream.tee();\n\n // Shared state for cross-branch coordination\n let consumed1 = 0;\n let consumed2 = 0;\n let cancelled = false;\n\n // Readers and controllers are assigned when wrapBranch creates the wrapped\n // streams. We store them so cancelBoth can cancel raw tee branches AND\n // error the wrapped stream controllers for cross-branch propagation.\n let rawReader1: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rawReader2: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let controller1: ReadableStreamDefaultController<Uint8Array> | undefined;\n let controller2: ReadableStreamDefaultController<Uint8Array> | undefined;\n\n /**\n * Cancel both tee branches. `initiator` is the branch index (0 or 1)\n * that triggered the cancellation — its controller is already being\n * closed/errored by the pull/cancel that triggered this, so we skip it.\n * Pass -1 to cancel+error both (e.g., from the buffer divergence guard).\n *\n * Both raw readers are always canceled regardless of initiator, because\n * the tee source stream is only released when both branches are canceled.\n * ReadableStreamDefaultReader.cancel() is idempotent, so double-cancel\n * is safe.\n */\n function cancelBoth(reason: unknown, initiator: number = -1): void {\n if (cancelled) return;\n cancelled = true;\n // Cancel both raw readers — tee source requires both branches canceled.\n rawReader1?.cancel(reason).catch(() => {});\n rawReader2?.cancel(reason).catch(() => {});\n // Error wrapped controllers so consumers see the failure.\n // Skip the initiator's controller — it's already being closed/errored.\n if (initiator !== 0) {\n try {\n controller1?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n if (initiator !== 1) {\n try {\n controller2?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n }\n\n function wrapBranch(\n branchIndex: number,\n rawBranch: ReadableStream<Uint8Array>,\n assignReader: (r: ReadableStreamDefaultReader<Uint8Array>) => void,\n assignController: (c: ReadableStreamDefaultController<Uint8Array>) => void,\n addConsumed: (n: number) => void,\n getSelfConsumed: () => number,\n getOtherConsumed: () => number\n ): ReadableStream<Uint8Array> {\n const reader = rawBranch.getReader();\n assignReader(reader);\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n assignController(controller);\n },\n\n async pull(controller) {\n if (cancelled) {\n return;\n }\n\n try {\n const { done, value } = await reader.read();\n\n // Re-check after await — cancelBoth may have fired while we\n // were waiting on the raw reader.\n if (cancelled) return;\n\n if (done) {\n try {\n controller.close();\n } catch {\n /* controller already errored by cancelBoth */\n }\n return;\n }\n\n addConsumed(value.byteLength);\n\n // Check buffer divergence: the difference in consumed bytes\n // approximates the tee's internal buffer size.\n const divergence = getSelfConsumed() - getOtherConsumed();\n if (divergence > maxBuffer) {\n cancelBoth(teeBufferExceeded(maxBuffer, divergence));\n return;\n }\n\n controller.enqueue(value);\n } catch (err) {\n if (!cancelled) {\n // Source stream errored — propagate to both branches.\n // cancelBoth with initiator skips our own controller,\n // so we error it explicitly here.\n cancelBoth(err, branchIndex);\n try {\n controller.error(err);\n } catch {\n /* already closed/errored */\n }\n }\n }\n },\n\n cancel(reason) {\n // Consumer cancelled this branch — propagate to the other\n cancelBoth(reason, branchIndex);\n },\n });\n }\n\n const wrapped1 = wrapBranch(\n 0,\n rawBranch1,\n (r) => {\n rawReader1 = r;\n },\n (c) => {\n controller1 = c;\n },\n (n) => {\n consumed1 += n;\n },\n () => consumed1,\n () => consumed2\n );\n\n const wrapped2 = wrapBranch(\n 1,\n rawBranch2,\n (r) => {\n rawReader2 = r;\n },\n (c) => {\n controller2 = c;\n },\n (n) => {\n consumed2 += n;\n },\n () => consumed2,\n () => consumed1\n );\n\n return [wrapped1, wrapped2];\n}\n\n/**\n * Stream-lifecycle timing for one response body: firstChunk, lastChunk,\n * close, maxGap (largest inter-chunk gap), chunk count, and byte count,\n * logged once when the stream terminates (clean close OR\n * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`. The\n * Web body wrapper below and the Node body (`node-body-response.ts`) feed\n * the same recorder, so the two report identically.\n */\nexport interface StreamTimingRecorder {\n chunk(byteLength: number): void;\n end(cancelled: boolean): void;\n}\n\nexport function createStreamTimingRecorder(startTime: number): StreamTimingRecorder {\n let firstChunkMs = 0;\n let lastChunkMs = 0;\n let maxGapMs = 0;\n let prevChunkTime = 0;\n let chunks = 0;\n let bytes = 0;\n let ended = false;\n\n return {\n chunk(byteLength) {\n const now = performance.now();\n const relativeMs = Math.round(now - startTime);\n if (chunks === 0) {\n firstChunkMs = relativeMs;\n } else {\n const gap = Math.round(now - prevChunkTime);\n if (gap > maxGapMs) maxGapMs = gap;\n }\n prevChunkTime = now;\n lastChunkMs = relativeMs;\n chunks++;\n bytes += byteLength;\n },\n end(cancelled) {\n if (ended) return;\n ended = true;\n const closeMs = Math.round(performance.now() - startTime);\n getLogger().debug('stream-lifecycle', {\n firstChunkMs,\n lastChunkMs,\n closeMs,\n maxGapMs,\n chunks,\n bytes,\n ...(cancelled ? { cancelled: true } : {}),\n });\n },\n };\n}\n\n/**\n * Wrap a Web response body with stream-lifecycle timing instrumentation\n * ({@link createStreamTimingRecorder}).\n *\n * Uses a manual reader pump to guarantee logging on all termination\n * paths — TransformStream.flush() is not called on cancellation.\n */\nexport function wrapResponseWithStreamTiming(\n body: ReadableStream<Uint8Array>,\n startTime: number\n): ReadableStream<Uint8Array> {\n const timing = createStreamTimingRecorder(startTime);\n const reader = body.getReader();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n timing.end(false);\n controller.close();\n return;\n }\n timing.chunk(value.byteLength);\n controller.enqueue(value);\n } catch (err) {\n timing.end(false);\n controller.error(err);\n }\n },\n\n cancel(reason) {\n timing.end(true);\n reader.cancel(reason).catch(() => {});\n },\n });\n}\n\n/** Format bytes as human-readable string (e.g., \"5.00 MB\"). */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n}\n\n/**\n * The error both tee implementations (this Web one and the Node one in\n * `flight-source-node.ts`) cancel with when one branch lags the other by more\n * than `maxBuffer` bytes. Warns once, here, so the two cannot drift.\n */\nexport function teeBufferExceeded(maxBuffer: number, divergence: number): Error {\n const error = new Error(\n `RSC stream tee buffer exceeded ${formatBytes(maxBuffer)} ` +\n `(divergence: ${formatBytes(divergence)}). ` +\n `This usually means SSR is much slower than the inline stream consumer. ` +\n `Consider reducing RSC payload size or increasing the tee buffer limit.`\n );\n console.warn(`[timber] ${error.message}`);\n return error;\n}\n\n/**\n * A pull reader over any chunk stream: a Web reader, or the Flight reader in\n * `flight-source.ts`, which reads a Node or Web Flight source.\n */\nexport interface ChunkReader<T> {\n read(): Promise<ReadableStreamReadResult<T>>;\n cancel(reason?: unknown): void;\n}\n\n/**\n * Read a chunk stream to completion under one overall deadline. Every read\n * is raced against the time remaining, and the reader is cancelled on every\n * exit, so a stalled upstream never outlives the deadline. See\n * design/02-rendering-pipeline.md §\"Always Timeout-Guard Stream Reads\".\n *\n * @param label - Prefix for the timeout error message. Both ways the deadline\n * can pass (between reads, or while a read is pending) reject with the same\n * `${label} did not complete within ${timeoutMs}ms`.\n */\nexport async function drainWithDeadline<T>(\n reader: ChunkReader<T>,\n timeoutMs: number,\n label: string\n): Promise<T[]> {\n const chunks: T[] = [];\n const deadline = Date.now() + timeoutMs;\n const deadlineError = () => new Error(`${label} did not complete within ${timeoutMs}ms`);\n try {\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw deadlineError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(deadlineError()), remaining);\n });\n let result: Awaited<ReturnType<ChunkReader<T>['read']>>;\n try {\n result = await Promise.race([reader.read(), timeout]);\n } finally {\n clearTimeout(timer);\n }\n if (result.done) return chunks;\n chunks.push(result.value);\n }\n } finally {\n reader.cancel();\n }\n}\n\n/** Concatenate byte chunks into one array. */\nexport function concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Read a byte stream to completion under one overall deadline and return\n * the concatenated bytes ({@link drainWithDeadline}). The static generator's\n * body drain uses it; Flight renders use `collectFlightBytes`\n * (`flight-source.ts`), which reads either source kind the same way.\n */\nexport async function readAllBytesWithDeadline(\n stream: ReadableStream<Uint8Array>,\n timeoutMs: number,\n label: string\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks = await drainWithDeadline(\n { read: () => reader.read(), cancel: (reason) => void reader.cancel(reason).catch(() => {}) },\n timeoutMs,\n label\n );\n return concatBytes(chunks);\n}\n","/**\n * Responses with a Node body — the platform-neutral half.\n *\n * On Node, SSR's HTML and Flight payload bodies are Node `Readable`s. They\n * travel the pipeline as a `NodeBodyResponse` (`node-body-response.ts`, Node\n * only): a real `Response` whose body stays a Node stream until the adapter\n * pipes it to the socket, so a response is never converted Node → Web → Node\n * (LOCAL-1475). srvx (nitro, the dev server) and nitro-preview's sender take\n * the Node body through `_toNodeResponse()`. Any code that reads the body\n * through the Web API still works: the response then converts once.\n *\n * Pipeline code shared with Workers re-wraps, strips, or times a response\n * through the helpers here, which ask the response itself to do the Node\n * work, so this module never imports `node:stream`. A response is recognised\n * by a `Symbol.for` brand, not `instanceof`: the RSC and SSR environments\n * load separate copies of the class.\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport type { Duplex } from 'node:stream';\n\n/** The brand a Node-body response carries, keyed by a registry symbol. */\nexport const NODE_BODY = Symbol.for('timber.response.nodeBody');\n\n/**\n * What a Node-body response can do with its body, for code that cannot import\n * the class: platform-neutral modules, and the standalone `_compress.mjs`,\n * which reaches these through the same registry symbol. Each one takes the\n * body: the response it was called on no longer has one.\n */\nexport interface NodeBodyOps {\n /**\n * Whether the response still owns a body. False for a null-body status\n * (204, 205, 304, …) and once the body was taken. Being branded says\n * nothing about this — ask here instead of reading `.body`, which would\n * convert it.\n */\n readonly hasBody: boolean;\n /** The same body under a new status and headers. */\n rewrap(init: ResponseInit): Response;\n /** Release the body unread (HEAD, a discarded document), aborting its producer. */\n discard(): void;\n /** The same body, reporting stream timing when it ends (detailed Server-Timing). */\n timed(startTime: number): Response;\n /**\n * The body piped through `stream` (gzip), as a Node-body response under\n * `init`. An error or destroy on either end tears down both.\n */\n through(stream: Duplex, init: ResponseInit): Response;\n}\n\ninterface NodeBodyBranded {\n [NODE_BODY]: NodeBodyOps;\n}\n\nfunction isNodeBodyBranded(response: Response): response is Response & NodeBodyBranded {\n return NODE_BODY in response;\n}\n\n/** The Node-body operations of `response`, or `null` for a Web-body response. */\nexport function nodeBodyOps(response: Response): NodeBodyOps | null {\n return isNodeBodyBranded(response) ? response[NODE_BODY] : null;\n}\n\n/**\n * `response`'s body under a new status and headers. A Node body moves to the\n * new response without converting; a Web body is reused as is.\n */\nexport function withResponseInit(response: Response, init: ResponseInit): Response {\n return nodeBodyOps(response)?.rewrap(init) ?? new Response(response.body, init);\n}\n\n/**\n * Release a response's body unread. A live producer (an SSR render, a Flight\n * render) is behind it; dropping the reference without this leaks it for the\n * lifetime of the render (design/13-security.md A4).\n */\nexport function discardResponseBody(response: Response): void {\n const ops = nodeBodyOps(response);\n if (ops) {\n ops.discard();\n return;\n }\n // `cancel()` rejects if the stream is already errored and throws\n // synchronously if it is locked — neither is actionable, the body is being\n // discarded either way.\n try {\n response.body?.cancel().catch(() => {});\n } catch {\n /* stream already locked or disturbed */\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aACd,QACA,SACA,OACM;CACN,IAAI,CAAC,QAAQ;CACb,IAAI,OAAO,SAAS;EAClB,QAAQ;EACR;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CAER;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as INFERRED_RULES, t as EXPLICIT_MARKERS } from "./poison-rules-Bmz-lCPi.js";
|
|
2
|
-
import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-
|
|
2
|
+
import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-Y8S9C0Na.js";
|
|
3
3
|
import { parseAst } from "vite";
|
|
4
4
|
// src/analyze/poison-scan.ts
|
|
5
5
|
/**
|
|
@@ -95,4 +95,4 @@ function poisoningsFor(kind, pending, signals) {
|
|
|
95
95
|
}
|
|
96
96
|
export { importSignals as n, poisoningsFor as r, collectImportSpecifiers as t };
|
|
97
97
|
|
|
98
|
-
//# sourceMappingURL=poison-scan-
|
|
98
|
+
//# sourceMappingURL=poison-scan-Dpl3ibG-.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"poison-scan-
|
|
1
|
+
{"version":3,"file":"poison-scan-Dpl3ibG-.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,wBACP,YACS;CACT,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,OAAO,WAAW,OAAO,MAAM,EAAE,eAAe,UAAU,EAAE,eAAe,MAA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,KAAK;GACX,MAAM,KAAK;GACX;GACA,SAAS,KAAK;GACd,aAAa,KAAK;EACpB,CAAC;CAGP;CACA,OAAO;AACT;;;;;;;;AASA,SAAgB,cACd,MACA,SACA,SACa;CACb,IAAI,WAAW,QAAQ,WAAW,GAAG,OAAO,CAAC;CAC7C,MAAM,kBACJ,SAAS,qBAAqB,SAAS,qBAAqB,SAAS;CACvE,MAAM,kBAAkB,SAAS,YAAY,SAAS,YAAY,SAAS;CAC3E,OAAO,QAAQ,QACZ,WACE,OAAO,YAAY,iBAAiB,mBACpC,OAAO,YAAY,iBAAiB,eACzC;AACF"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as DEFAULT_PAGE_EXTENSIONS, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
|
|
2
2
|
import { a as findOrderDependentCollision, i as validateInterceptionPlacement, n as computeInterceptedBase, r as computeInterceptedUrlBase } from "./interception-CtNt9jPt.js";
|
|
3
3
|
import { a as isDynamicMetadataExtension, n as classifyMetadataRoute } from "./metadata-routes-MXNjWOt5.js";
|
|
4
|
-
import { b as swallow } from "./logger-
|
|
4
|
+
import { b as swallow } from "./logger-C4m8rfMy.js";
|
|
5
5
|
import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK135BN.js";
|
|
6
6
|
import { parseAst } from "vite";
|
|
7
7
|
import { basename, extname, join } from "node:path";
|
|
@@ -974,4 +974,4 @@ function findScriptExtFile(dirPath, name) {
|
|
|
974
974
|
}
|
|
975
975
|
export { fileHasAnyExport as a, fileHasStarExport as c, patternBinds as d, tryParse as f, fileDefaultExportIsLocalValue as i, getCsrfExport as l, scanRoutes as n, fileHasDefaultExport as o, readFileCached as p, TRANSPARENT_WRAPPERS as r, fileHasDirective as s, isRouteConventionFile as t, isScriptExtension as u };
|
|
976
976
|
|
|
977
|
-
//# sourceMappingURL=scanner-
|
|
977
|
+
//# sourceMappingURL=scanner-CCEHN9Jg.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scanner-DneYxQoY.js","names":[],"sources":["../../src/routing/collision-spaces.ts","../../src/routing/slot-placement.ts","../../src/routing/file-cache.ts","../../src/routing/export-detect.ts","../../src/routing/scanner.ts"],"sourcesContent":["/**\n * Route collision spaces.\n *\n * A collision space is a set of routes that compete for URLs with each other,\n * and there are three: the main tree, each parallel slot, and each intercepting\n * subtree. This module owns the first two; `interception.ts` owns the third.\n * All of them decide order-dependence with the one oracle in\n * `collision-probe.ts`, so they cannot drift on what counts as two routes\n * answering a single URL.\n *\n * See design/07-routing.md §\"Route Collisions\".\n */\n\nimport type { SegmentNode } from './types.ts';\nimport { computeInterceptedUrlBase } from './interception.ts';\nimport { findOrderDependentCollision, type ProbeLeaf } from './collision-probe.ts';\n\n/**\n * Validate that no two pages/routes in one collision space answer the same URL.\n *\n * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim\n * /login — the scanner must detect and reject this at build time.\n *\n * Each parallel slot is validated as its OWN collision space: a slot's pages\n * intentionally share URL paths with the parent tree (that's the point of\n * parallel routes), but two route groups INSIDE one slot claiming the same\n * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.\n */\nexport function validateRouteGroupCollisions(root: SegmentNode): void {\n validateCollisionSpace(root, '', root.urlPath);\n}\n\n/**\n * Validate one collision space — the main tree, or one parallel slot.\n *\n * **Two checks, and the difference between them matters.** Two leaves at the\n * same `urlPath` are decided by string equality, which is exact and needs no\n * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs\n * whatever the precedence rules are, and naming the shared path is the clearest\n * thing to tell the author.\n *\n * Everything else is decided by asking the matcher, through the shared oracle\n * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses\n * every pair that matches the same URLs while being *spelled* differently:\n * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority\n * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`\n * because an optional catch-all also matches zero parts. Both built before\n * TIM-1308 with filesystem enumeration order deciding which page renders,\n * which is precisely what this validator and `validateAffixedSiblingConflicts`\n * exist to reject.\n *\n * Segment *kinds* stay distinct without any special-casing here, because the\n * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside\n * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is\n * not reported. So does an affixed sibling against a bare one; the\n * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and\n * duplicating it here would double-report.\n */\nfunction validateCollisionSpace(spaceRoot: SegmentNode, segmentPath: string, base: string): void {\n const leaves: ProbeLeaf[] = [];\n collectRoutableLeaves(spaceRoot, new Map(), segmentPath, [], leaves, base);\n\n const collision = findOrderDependentCollision(spaceRoot, leaves, base);\n if (!collision) return;\n\n throw new Error(\n `Build error: route collision — two pages/routes answer the same URL.\\n` +\n ` URL: ${collision.url}\\n` +\n ` File 1: ${collision.first}\\n` +\n ` File 2: ${collision.second}\\n` +\n `Both match it, so which one renders would be decided by filesystem enumeration ` +\n `order — renaming a route group can flip it. Rename or move one of them.\\n` +\n `Routes are compared by the URLs they match, not by how they are spelled: [id] and ` +\n `[slug] match the same URLs, and an optional catch-all also matches with zero ` +\n `segments.`\n );\n}\n\n/**\n * Walk one collision space and collect its routable leaves (page or route\n * files), throwing on an exact `urlPath` collision. Each slot recurses as its\n * OWN space — slots are parallel routes that intentionally share URL paths with\n * their parent tree, but collisions within a single slot are real errors.\n *\n * The early return at an intercepting node drops that subtree's own pages from\n * this space, but not its slots: a slot is its own collision space wherever it\n * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before\n * returning.\n *\n * `chain` accumulates the URL-contributing nodes from the space root down, for\n * the probe oracle. Route groups are excluded because they are transparent for\n * matching, and the space root itself is excluded because `matchUrlParts`\n * matches parts against its *children* — the root consumes nothing.\n */\nfunction collectRoutableLeaves(\n node: SegmentNode,\n seen: Map<string, { filePath: string; segmentPath: string }>,\n segmentPath: string,\n chain: SegmentNode[],\n leaves: ProbeLeaf[],\n base: string\n): void {\n // Intercepting routes are resolved by the interception resolvers, not URL\n // matching, and their computed urlPaths are not addresses — an interception\n // mirrors the canonical route it replaces, so comparing those paths here\n // would reject every correct interception. Skipping is not \"unvalidated\":\n // `assertNoInterceptedPatternCollisions` gives each intercepting subtree its\n // own collision space, keyed by the intercepted pattern rather than by these\n // paths (TIM-1305). See design/07-routing.md §\"Collisions Inside an\n // Intercepting Subtree\" and §\"Why urlPath Stays Parent-Relative Inside an\n // Intercepting Subtree\".\n const currentPath = segmentPath\n ? `${segmentPath}/${node.segmentName}`\n : node.segmentName || '(root)';\n\n // The intercepting subtree's own pages leave this space — but its SLOTS do\n // not leave every space, so they are picked up before returning. See\n // `validateSlotsInsideInterceptingSubtree`.\n if (node.segmentType === 'intercepting') {\n // `node.urlPath` on an intercepting node is its OWNER's path — the input\n // `computeInterceptedUrlBase` wants — because an intercepting segment adds\n // no URL depth.\n validateSlotsInsideInterceptingSubtree(\n node,\n currentPath,\n interceptedBaseOf(node, node.urlPath)\n );\n return;\n }\n\n const routableFile = node.page ?? node.route;\n if (routableFile) {\n const existing = seen.get(node.urlPath);\n if (existing) {\n throw new Error(\n `Build error: route collision — multiple route groups produce a page/route at the same URL path.\\n` +\n ` URL path: ${urlFromChain(base, chain)}\\n` +\n ` File 1: ${existing.filePath} (via ${existing.segmentPath})\\n` +\n ` File 2: ${routableFile.filePath} (via ${currentPath})\\n` +\n `Each URL path must map to exactly one page or route handler. ` +\n `Rename or move one of the conflicting files.`\n );\n }\n seen.set(node.urlPath, { filePath: routableFile.filePath, segmentPath: currentPath });\n leaves.push({ filePath: routableFile.filePath, chain });\n }\n\n // Recurse into children. A route group contributes no URL part, so it is\n // absent from the chain — exactly as `collectEffectiveChildren` flattens it\n // away in the matcher.\n for (const child of node.children) {\n const isGroup = child.segmentType === 'group';\n collectRoutableLeaves(\n child,\n seen,\n currentPath,\n isGroup ? chain : [...chain, child],\n leaves,\n base\n );\n }\n\n // Recurse into slots — each slot is its own collision space, with its own\n // seen map, its own leaf set and its own probe run.\n //\n // The base is accumulated from this space's own base rather than read off\n // `slotNode.urlPath`, because this walk also runs on slot spaces nested inside\n // an intercepting subtree, where `urlPath` is parent-relative and not an\n // address. Outside one the two are identical by construction.\n for (const slotNode of Object.values(node.slots)) {\n validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));\n }\n}\n\n/**\n * Validate every parallel slot nested anywhere inside an intercepting subtree.\n *\n * Two walks each skip these slots for their own good reason, and together they\n * left them checked by nothing: `collectRoutableLeaves` returns at the\n * intercepting node before it reaches them, and `walkInterceptedLeaves`\n * deliberately does not descend slots — correct for rewrite generation, since a\n * slot inside an intercepting subtree produces no rewrite. But \"produces no\n * rewrite\" answers the rewrite question and not the resolution one, so\n * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor\n * built with filesystem order picking the page — the ordinary per-slot\n * collision that fails the build anywhere else in the tree (codex, on PR #1002).\n *\n * A slot is its own collision space wherever it sits, so each one is validated\n * as one.\n *\n * **Which interception shape this still applies to.** TIM-1311 answered the\n * question this was written under — whether such a slot renders at all — and\n * the answer is per-shape:\n *\n * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node\n * joins the main route chain, so `route-element-builder.ts` resolves slots on\n * it and below it like any other chain segment. They render, and this is the\n * space where the check is load-bearing.\n * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another\n * slot's subtree, which no renderer descends for slots — so it never renders,\n * and `validateSlotPlacement` now rejects the placement before this runs.\n * That rule subsumes this one for the modal shape rather than conflicting\n * with it, exactly as anticipated.\n *\n * So this walk is reached only for children-path interceptors in a valid tree.\n * It is not narrowed to them: the rule it states — a slot is its own collision\n * space wherever it sits — is shape-independent, and making it conditional on a\n * property the placement validator already guarantees would just be a second\n * place for the two to disagree.\n *\n * The walk covers the whole subtree, not just the interceptor's direct slot\n * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the\n * same reason as `(...)photo/@side`.\n */\nfunction validateSlotsInsideInterceptingSubtree(\n node: SegmentNode,\n segmentPath: string,\n base: string\n): void {\n for (const slotNode of Object.values(node.slots)) {\n // A slot adds no URL depth, so it answers its owner's base.\n validateCollisionSpace(slotNode, segmentPath, base);\n }\n for (const child of node.children) {\n validateSlotsInsideInterceptingSubtree(\n child,\n `${segmentPath}/${child.segmentName}`,\n childInterceptedBase(child, base)\n );\n }\n}\n\n/**\n * The URL a leaf answers, built from its space's base and its own chain.\n *\n * Read instead of `node.urlPath` because `urlPath` inside an intercepting\n * subtree is parent-relative and is not an address — the collision URL has to\n * be one the author can actually find. Outside an intercepting subtree the two\n * are identical by construction: the base is the space root's `urlPath` and the\n * chain is every URL-contributing segment below it.\n */\nfunction urlFromChain(base: string, chain: SegmentNode[]): string {\n if (chain.length === 0) return base || '/';\n const tail = chain.map((n) => n.segmentName).join('/');\n return `${base === '/' ? '' : base}/${tail}`;\n}\n\n/**\n * The intercepted URL an intercepting directory's own page sits at.\n *\n * `urlPath` inside an intercepting subtree is deliberately parent-relative and\n * is **not** an address (see design/07-routing.md §\"Why urlPath Stays\n * Parent-Relative Inside an Intercepting Subtree\"), so a collision reported\n * from one names a URL the author cannot find. The intercepted base is the real\n * address, and it is what rewrite generation and the interception collision\n * validator both already use.\n */\nfunction interceptedBaseOf(node: SegmentNode, ownerUrlPath: string): string {\n return computeInterceptedUrlBase(\n ownerUrlPath,\n node.interceptionMarker ?? '(.)',\n node.interceptedSegmentName ?? node.segmentName\n );\n}\n\n/**\n * Extend an intercepted base by one child segment.\n *\n * Route groups are transparent and contribute nothing. A nested intercepting\n * node re-bases from its own marker rather than appending — that tree is\n * rejected by `validateInterceptionPlacement`, but collision validation runs\n * first, so it still has to produce a sensible URL rather than one containing a\n * literal \"(.)b\".\n */\nfunction childInterceptedBase(child: SegmentNode, base: string): string {\n // Slots are not in `children` — `scanChildren` files them under `slots` — so\n // only groups are transparent here.\n if (child.segmentType === 'group') return base;\n if (child.segmentType === 'intercepting') return interceptedBaseOf(child, base);\n return base === '/' ? `/${child.segmentName}` : `${base}/${child.segmentName}`;\n}\n","/**\n * Parallel slot placement.\n *\n * One rule: a slot is resolved only for a segment on the **matched route\n * chain**, and a slot's own subtree is never on that chain. So a slot declared\n * anywhere inside another slot's subtree can never render, and is rejected at\n * build time rather than left as a directory the author will keep editing.\n *\n * See design/07-routing.md §\"Parallel Routes\".\n */\n\nimport type { SegmentNode } from './types.ts';\n\n/**\n * Reject every parallel slot that no renderer reaches.\n *\n * **Where slots are resolved.** Two places read `segment.slots`, and both walk\n * the main route chain: `route-element-builder.ts` (the RSC render).\n * It is not reachable from inside a slot. The slot's own\n * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched\n * chain to apply that chain's layouts, error boundaries and access gates\n * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`\n * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and\n * everything below it is dead: the file is scanned, typed, code-split and\n * shipped, and no request can render it.\n *\n * That is the TIM-1278 failure — a directory that silently never renders —\n * and the reason it is a build error rather than a documented limit is that\n * nothing at request time can report it. A slot that does not match renders\n * `default.tsx` or `null`, which is exactly what a slot the resolver never\n * looked at also produces, so the author sees the *designed* behaviour of a\n * non-matching slot and has no signal to distinguish it from a slot that\n * cannot match at all.\n *\n * **Interception is incidental.** TIM-1311 arrived as\n * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the\n * identical `feed/@modal/photo/@side` never renders either, for the same\n * reason and with no marker anywhere. Rejecting only the intercepting spelling\n * would have drawn a line the author cannot see from the directory names.\n *\n * The children-path interception shape is **not** affected and must not be:\n * its intercepting node joins the main chain (`server/children-interception.ts`\n * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary\n * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below\n * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`\n * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot\n * boundary, which is what this walk tracks — not the marker.\n */\nexport function validateSlotPlacement(root: SegmentNode): void {\n walkForSlotPlacement(root, '', null);\n}\n\n/**\n * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or\n * above `node`, or null on the main chain. It is carried rather than recomputed\n * so the error can name the slot that swallows the offender — \"this is inside\n * @modal\" is the part of the diagnosis the author cannot see from the offending\n * path alone.\n */\nfunction walkForSlotPlacement(\n node: SegmentNode,\n path: string,\n enclosingSlotPath: string | null\n): void {\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;\n if (enclosingSlotPath !== null) {\n throwNestedSlot(slotPath, enclosingSlotPath);\n }\n walkForSlotPlacement(slotNode, slotPath, slotPath);\n }\n\n for (const child of node.children) {\n walkForSlotPlacement(\n child,\n path ? `${path}/${child.segmentName}` : child.segmentName,\n enclosingSlotPath\n );\n }\n}\n\nfunction throwNestedSlot(slotPath: string, enclosingSlotPath: string): never {\n throw new Error(\n `Build error: parallel slot nested inside another parallel slot.\\n` +\n ` Directory: app/${slotPath}\\n` +\n ` Inside: app/${enclosingSlotPath}\\n` +\n `A parallel slot is resolved only for a segment on the matched route chain, and a ` +\n `slot's own subtree is never on that chain — the slot resolver walks the slot's ` +\n `matched chain to apply its layouts, error boundaries and access gates, and never ` +\n `looks at slots declared inside it. So app/${slotPath} and everything below it can ` +\n `never render, and no request-time signal can tell you: an unreachable slot ` +\n `produces exactly what a slot that simply did not match produces.\\n` +\n `Declare the slot on a segment of the main route chain instead, or move its pages ` +\n `into app/${enclosingSlotPath}'s own subtree.\\n` +\n `See design/07-routing.md §\"Parallel Routes\".`\n );\n}\n","import { readFileSync, statSync } from 'node:fs';\n\nconst cache = new Map<string, { mtimeMs: number; size: number; content: string }>();\n\n/**\n * Read a file's text content, returning a cached copy when the file\n * hasn't been modified since the last read (checked via mtime + size).\n *\n * Falls back to a fresh read on any stat/read error.\n */\nexport function readFileCached(filePath: string): string {\n try {\n const stat = statSync(filePath);\n const entry = cache.get(filePath);\n if (entry && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) return entry.content;\n const content = readFileSync(filePath, 'utf-8');\n cache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, content });\n return content;\n } catch {\n cache.delete(filePath);\n return readFileSync(filePath, 'utf-8');\n }\n}\n","/**\n * AST-based export detection for route files.\n *\n * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and\n * default exports, replacing the regex-based approach that was fragile\n * with TypeScript syntax (type exports, `as` aliases, comments, etc.).\n */\n\nimport { existsSync } from 'node:fs';\nimport { parseAst } from 'vite';\nimport { readFileCached } from './file-cache.ts';\n\ninterface AstNode {\n type: string;\n exportKind?: string;\n declaration?: AstNode;\n specifiers?: Array<{\n exported?: { name: string };\n local?: { name: string };\n exportKind?: string;\n }>;\n id?: { name: string };\n declarations?: Array<{ id?: { name: string }; init?: AstNode }>;\n /** Set on re-exports: `export { X } from './y'`. Absent on local exports. */\n source?: { value?: string } | null;\n /** Set on runtime-transparent wrappers: `X as T`, `X satisfies T`, `(X)`, `X!`. */\n expression?: AstNode;\n /** Set on `Identifier` nodes. */\n name?: string;\n}\n\ninterface ProgramNode {\n body: AstNode[];\n}\n\n/**\n * Parse a module. `lang` defaults to `tsx`; pass `ts` for `.ts` files, where\n * an angle-bracket cast or a generic arrow (`<T>(x: T) => x`) is valid\n * TypeScript but a TSX parse error.\n */\nexport function tryParse(source: string, lang: 'ts' | 'tsx' = 'tsx'): ProgramNode | null {\n try {\n return parseAst(source, { lang }) as unknown as ProgramNode;\n } catch {\n return null;\n }\n}\n\n/**\n * Collect all named export identifiers from a parsed program.\n * Handles: `export function X`, `export const X`, `export { X }`,\n * `export { X } from '...'`, `export { Y as X }`.\n */\nfunction collectNamedExports(program: ProgramNode): Set<string> {\n const names = new Set<string>();\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n // Skip `export type ...` declarations — they're erased at runtime\n if (stmt.exportKind === 'type') continue;\n\n if (stmt.declaration) {\n if (stmt.declaration.id?.name) {\n names.add(stmt.declaration.id.name);\n }\n if (stmt.declaration.declarations) {\n for (const decl of stmt.declaration.declarations) {\n if (decl.id?.name) names.add(decl.id.name);\n }\n }\n }\n\n if (stmt.specifiers) {\n for (const spec of stmt.specifiers) {\n // Skip `export { type X }` — per-specifier type exports\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name && spec.exported.name !== 'default') {\n names.add(spec.exported.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * The specifier exporting a *runtime* default from this statement, if any.\n *\n * Type-only exports erase, so they are not default exports at runtime — and\n * TypeScript spells that two ways, on two different nodes: `export type { X as\n * default }` marks the **statement**, `export { type X as default }` marks the\n * **specifier**. Both have to be checked, or a type alias reads as a component:\n * a status file whose only default is a type has nothing for the error boundary\n * to receive (the renderer's `mod?.default` skips it), so treating it as one\n * would fail a build over a file that cannot break anything.\n *\n * One implementation because two callers must agree on what \"has a default\n * export\" means: `hasDefaultExport` decides whether to warn that a page has\n * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.\n */\nfunction defaultSpecifier(stmt: AstNode): NonNullable<AstNode['specifiers']>[number] | null {\n if (stmt.type !== 'ExportNamedDeclaration' || !stmt.specifiers) return null;\n if (stmt.exportKind === 'type') return null;\n for (const spec of stmt.specifiers) {\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name === 'default') return spec;\n }\n return null;\n}\n\n/**\n * Check whether a program has a default export.\n * Handles: `export default ...`, `export { X as default }`,\n * `export { default } from '...'`. Type-only defaults do not count —\n * see `defaultSpecifier`.\n */\nfunction hasDefaultExport(program: ProgramNode): boolean {\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') return true;\n if (defaultSpecifier(stmt)) return true;\n }\n return false;\n}\n\n/**\n * Check whether a program has any bare `export * from '...'` declarations.\n * Excludes `export * as X from '...'` (namespace re-exports) since those\n * create a namespace object, not individual top-level exports.\n */\nfunction hasStarExport(program: ProgramNode): boolean {\n return program.body.some(\n (stmt) =>\n stmt.type === 'ExportAllDeclaration' && !(stmt as any).exported && stmt.exportKind !== 'type'\n );\n}\n\n/**\n * Check if a file exports a specific named export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return collectNamedExports(program).has(exportName);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any of the given named exports.\n * Returns the set of matching export names.\n */\nexport function fileHasAnyExport(filePath: string, exportNames: readonly string[]): Set<string> {\n const matches = new Set<string>();\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return matches;\n const exports = collectNamedExports(program);\n for (const name of exportNames) {\n if (exports.has(name)) matches.add(name);\n }\n } catch {\n // Graceful fallback: return empty set\n }\n return matches;\n}\n\n/**\n * Check if a file has a default export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasDefaultExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasDefaultExport(program);\n } catch {\n return false;\n }\n}\n\n/** Node types whose value is unambiguously constructed by this module. */\nconst FUNCTION_LIKE = new Set([\n 'FunctionDeclaration',\n 'FunctionExpression',\n 'ArrowFunctionExpression',\n 'ClassDeclaration',\n 'ClassExpression',\n]);\n\n/**\n * Expression wrappers that erase at runtime and so cannot change where a value\n * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.\n */\nexport const TRANSPARENT_WRAPPERS: ReadonlySet<string> = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n 'TSInstantiationExpression',\n 'ParenthesizedExpression',\n]);\n\n/**\n * Strip runtime-transparent wrappers so the node underneath can be classified.\n *\n * Without this, `(() => <h1 />) satisfies React.FC` reads as a\n * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a\n * provably-local component is misread as one whose origin cannot be\n * determined — turning a build error into a warning.\n */\nfunction unwrapTransparent(node: AstNode): AstNode {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) {\n current = current.expression;\n }\n return current;\n}\n\n/**\n * Whether `name` is bound at module top level to a function or class written\n * in this file. An imported binding can never match: imports are\n * `ImportDeclaration` specifiers, not function/class/variable declarations,\n * and a module-level name cannot be both.\n */\nfunction bindsLocalFunction(program: ProgramNode, name: string): boolean {\n for (const stmt of program.body) {\n // `export function X() {}` binds X locally too — unwrap the export.\n const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;\n if (!decl) continue;\n if (\n (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') &&\n decl.id?.name === name\n ) {\n return true;\n }\n if (decl.type === 'VariableDeclaration') {\n for (const d of decl.declarations ?? []) {\n if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the default export is *provably* a value constructed by this module:\n * `export default function/class/() => {}`, or a name bound to a function or\n * class declared here — whether it leaves via `export default Name` or\n * `export { Name as default }`. Both spellings are the same fact about where\n * the value was built, so both must answer the same way.\n *\n * This is the sound half of \"is this a server component?\". A file with no\n * `'use client'` directive whose default export is built here is a server\n * component, full stop. Everything else — `export { default } from\n * './client-thing'`, `export default Imported`, `export default memo(X)`,\n * an unparseable file — returns false, because the exported value may have\n * been minted in a module that *does* carry the directive. Callers must not\n * infer \"server component\" from a missing directive alone.\n */\nexport function fileDefaultExportIsLocalValue(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') {\n const decl = stmt.declaration && unwrapTransparent(stmt.declaration);\n if (!decl) return false;\n if (FUNCTION_LIKE.has(decl.type)) return true;\n if (decl.type === 'Identifier' && decl.name) {\n return bindsLocalFunction(program, decl.name);\n }\n return false;\n }\n\n // `export { Name as default }` — the same default export by another\n // spelling. `hasDefaultExport` already counts it, so an analysis that\n // skipped it here would let the exact defect this powers slip through\n // as a warning.\n const spec = defaultSpecifier(stmt);\n if (spec) {\n // `export { X as default } from './client-thing'` re-exports another\n // module's value — the directive governing it lives over there.\n if (stmt.source) return false;\n return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any `export * from '...'` declarations.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasStarExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasStarExport(program);\n } catch {\n return false;\n }\n}\n\n/**\n * How a file declares the per-route CSRF exemption.\n *\n * - `'absent'` — no runtime export named `csrf`.\n * - `'exempt'` — exactly `export const csrf = false` (wrappers like\n * `false as const` allowed), declared in this file.\n * - `'invalid'` — some other `csrf` export: another value, `let`, a\n * destructured binding, a specifier or named re-export (`export { csrf }`,\n * `export { x as \"csrf\" }`), a function or class. `export * from` is not\n * followed: a `csrf` it carries is neither exempt nor an error.\n *\n * The exemption is read from source at build time, never from the loaded\n * module, because the CSRF gate runs before any user code (see\n * design/08-forms-and-actions.md §\"Per-route exemption\"). Only the literal\n * form can be read that way; any other spelling is a build error rather\n * than a silent \"not exempt\", so what the developer wrote is what runs.\n */\nexport type CsrfExport = 'absent' | 'exempt' | 'invalid';\n\nexport function getCsrfExport(filePath: string): CsrfExport {\n if (!existsSync(filePath)) return 'absent';\n // Unparseable: not exempt (fail closed). The compiler reports the syntax\n // error; guessing at a half-written file would misreport it.\n const program = tryParse(readFileCached(filePath));\n if (!program) return 'absent';\n\n // Walk the statements directly rather than through `collectNamedExports`:\n // every spelling that exports a runtime `csrf` must be seen here, and\n // that helper does not see destructured declarations or string-literal\n // specifier names. What cannot be seen at all — `export * from` — is\n // not read, and is documented as such.\n let found: CsrfExport = 'absent';\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type') continue;\n for (const spec of stmt.specifiers ?? []) {\n if (spec.exportKind !== 'type' && specifierName(spec.exported) === 'csrf') {\n return 'invalid';\n }\n }\n const decl = stmt.declaration as (AstNode & { kind?: string }) | undefined;\n if (!decl) continue;\n if (decl.id?.name === 'csrf') return 'invalid'; // function or class\n if (decl.type !== 'VariableDeclaration') continue;\n for (const d of decl.declarations ?? []) {\n const id = d.id as AstNode | undefined;\n if (id?.type === 'Identifier') {\n if (id.name !== 'csrf') continue;\n const init = d.init && (unwrapTransparent(d.init) as AstNode & { value?: unknown });\n const literalFalse = init?.type === 'Literal' && init.value === false;\n if (decl.kind !== 'const' || !literalFalse) return 'invalid';\n found = 'exempt';\n } else if (id && patternBinds(id, 'csrf')) {\n return 'invalid'; // `export const { csrf } = …`\n }\n }\n }\n return found;\n}\n\n/** An export specifier's name: `csrf` or the string literal `\"csrf\"`. */\nfunction specifierName(node: { name?: string; value?: unknown } | undefined): string | undefined {\n if (!node) return undefined;\n return typeof node.value === 'string' ? node.value : node.name;\n}\n\n/** Whether a destructuring pattern binds `name` anywhere inside it. */\nexport function patternBinds(node: unknown, name: string): boolean {\n if (!node || typeof node !== 'object') return false;\n const n = node as Record<string, unknown>;\n switch (n.type) {\n case 'Identifier':\n return n.name === name;\n case 'ObjectPattern':\n return ((n.properties as unknown[]) ?? []).some((prop) => {\n const p = prop as Record<string, unknown>;\n return patternBinds(p.type === 'RestElement' ? p.argument : p.value, name);\n });\n case 'ArrayPattern':\n return ((n.elements as unknown[]) ?? []).some((el) => patternBinds(el, name));\n case 'RestElement':\n return patternBinds(n.argument, name);\n case 'AssignmentPattern':\n return patternBinds(n.left, name);\n default:\n return false;\n }\n}\n\n/**\n * Check if a file starts with a specific directive (e.g. \"use client\").\n * Directives are string literal expression statements at the top of the file.\n */\nexport function fileHasDirective(filePath: string, directive: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type !== 'ExpressionStatement') break;\n const expr = (stmt as any).expression;\n if (expr?.type !== 'Literal' || typeof expr.value !== 'string') break;\n if (expr.value === directive) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/** Route files the AST checks can read; `.mdx` and `.json` are skipped. */\nexport function isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n","/**\n * Route discovery scanner.\n *\n * Pure function: (appDir, config) → RouteTree\n *\n * Scans the app/ directory and builds a segment tree recognizing all\n * timber.js file conventions. Does NOT handle request matching — this\n * is discovery only.\n */\n\nimport { readdirSync, statSync } from 'node:fs';\nimport { join, extname, basename } from 'node:path';\nimport type {\n RouteTree,\n SegmentNode,\n SegmentType,\n RouteFile,\n ScannerConfig,\n InterceptionMarker,\n} from './types.ts';\nimport { classifySegment, effectiveUrlSegment } from './segment-classify.ts';\nimport { validateInterceptionPlacement, computeInterceptedBase } from './interception.ts';\nimport { validateRouteGroupCollisions } from './collision-spaces.ts';\nimport { validateSlotPlacement } from './slot-placement.ts';\nimport { DEFAULT_PAGE_EXTENSIONS } from './types.ts';\nimport { classifyMetadataRoute, isDynamicMetadataExtension } from '../server/metadata-routes.ts';\nimport { swallow } from '../server/logger.ts';\nimport { getCsrfExport } from './export-detect.ts';\nimport { ENCODED_SEPARATOR_RE, NULL_BYTE_RE } from '../server/canonicalize.ts';\n\n/**\n * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)\n * `error` is excluded — it only accepts script extensions (TIM-1505).\n */\nconst PAGE_EXT_CONVENTIONS = new Set(['page', 'layout', 'default', 'denied']);\n\n/**\n * File convention names that are always .ts/.tsx (never .mdx etc.)\n */\nconst FIXED_CONVENTIONS = new Set(['middleware', 'access', 'route']);\n\n/**\n * Status-code file patterns:\n * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx\n * - Category catch-alls: 4xx.tsx, 5xx.tsx\n */\nconst STATUS_CODE_PATTERN = /^(\\d{3}|[45]xx)$/;\n\n/**\n * Whether a basename + extension pair is a route-convention file the\n * framework itself imports: page/layout/default/denied on pageExtensions,\n * error/global-error and status-code files on script extensions only,\n * middleware/access/route/proxy on .ts/.tsx/.js/.jsx only, and\n * status-code .json files — mirroring this scanner's own recognition\n * rules per family.\n *\n * Exported for the analyze classifier so its provisional classification\n * (design/47 §2) derives from the scanner's real conventions instead of\n * a duplicate list that can drift.\n */\nexport function isRouteConventionFile(\n base: string,\n ext: string,\n pageExtensions: readonly string[] = DEFAULT_PAGE_EXTENSIONS\n): boolean {\n const isPageExt = pageExtensions.includes(ext);\n const isScriptExt = /^[jt]sx?$/.test(ext);\n if (PAGE_EXT_CONVENTIONS.has(base) && isPageExt) return true;\n if ((base === 'error' || base === 'global-error') && isScriptExt) return true;\n if ((FIXED_CONVENTIONS.has(base) || base === 'proxy') && isScriptExt) return true;\n if (STATUS_CODE_PATTERN.test(base) && (isScriptExt || ext === 'json')) return true;\n return false;\n}\n\n/**\n * Scan the app/ directory and build the route tree.\n *\n * @param appDir - Absolute path to the app/ directory\n * @param config - Scanner configuration\n * @returns The complete route tree\n */\nexport function scanRoutes(appDir: string, config: ScannerConfig = {}): RouteTree {\n const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;\n const extSet = new Set(pageExtensions);\n\n const tree: RouteTree = {\n root: createSegmentNode('', 'static', '/'),\n };\n\n // Check for proxy.ts at app root\n const proxyFile = findFixedFile(appDir, 'proxy');\n if (proxyFile) {\n tree.proxy = proxyFile;\n }\n\n // Check for global-error.{tsx,ts,jsx,js} at app root.\n // Tier 2 error page — renders standalone (no layouts) when no segment-level\n // error file is found. Script extensions only — MDX not supported (TIM-1505).\n // See design/10-error-handling.md §\"Tier 2\".\n const globalErrorFile = findScriptExtFile(appDir, 'global-error');\n if (globalErrorFile) {\n tree.globalError = globalErrorFile;\n }\n\n // Scan the root directory's files\n scanSegmentFiles(appDir, tree.root, extSet);\n\n // Scan children recursively\n scanChildren(appDir, tree.root, extSet);\n\n // Validate: every parallel slot sits where a renderer reaches it. First,\n // because a slot nested inside another slot never renders, and a collision\n // reported from inside one would send the author to fix an ambiguity between\n // two pages that were both already dead.\n validateSlotPlacement(tree.root);\n\n // Validate: detect route group collisions (different groups producing pages at the same URL)\n validateRouteGroupCollisions(tree.root);\n\n // Validate: detect duplicate param names in nested dynamic segments\n // e.g., /[id]/items/[id] — same param name in ancestor and descendant\n validateDuplicateParamNames(tree.root);\n\n // Validate: detect same param name used with different bracket forms\n // e.g., [id] in one route and [...id] in another\n validateUniqueBracketForms(tree.root);\n\n // Validate: detect affixed dynamic siblings with equal specificity\n // e.g., a-[id] and [slug]-b both have prefix+suffix length = 2\n validateAffixedSiblingConflicts(tree.root);\n\n // Validate: intercepting routes must be direct children of a parallel slot —\n // the slot resolver is the only thing that can render one.\n validateInterceptionPlacement(tree.root);\n\n return tree;\n}\n\n/**\n * Create an empty segment node.\n */\nfunction createSegmentNode(\n segmentName: string,\n segmentType: SegmentType,\n urlPath: string,\n paramName?: string,\n interceptionMarker?: InterceptionMarker,\n interceptedSegmentName?: string,\n paramPrefix?: string,\n paramSuffix?: string\n): SegmentNode {\n return {\n segmentName,\n segmentType,\n urlPath,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n children: [],\n slots: {},\n };\n}\n\n/**\n * Compute the URL path for a child segment given its parent's URL path.\n * Route groups, slots, and intercepting routes do NOT add URL depth.\n */\nfunction computeUrlPath(parentUrlPath: string, dirName: string, segmentType: SegmentType): string {\n // Groups, slots, and intercepting routes don't add to URL path\n if (segmentType === 'group' || segmentType === 'slot' || segmentType === 'intercepting') {\n return parentUrlPath;\n }\n\n const parentPath = parentUrlPath === '/' ? '' : parentUrlPath;\n return `${parentPath}/${dirName}`;\n}\n\n/**\n * Scan a directory for file conventions and populate the segment node.\n */\nfunction scanSegmentFiles(dirPath: string, node: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n // Skip directories — handled by scanChildren\n try {\n if (statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n const ext = extname(entry).slice(1); // remove leading dot\n const name = basename(entry, `.${ext}`);\n\n // Page-extension conventions (page, layout, default, denied)\n if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {\n const key = name as 'page' | 'layout' | 'default' | 'denied';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // error.tsx — script extensions only, not MDX/MD (TIM-1505).\n if (name === 'error' && /^[jt]sx?$/.test(ext)) {\n const existing = node.error;\n if (existing) {\n throwDuplicateConvention('error', existing.filePath, fullPath);\n }\n node.error = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Fixed conventions (middleware, access, route) — only\n // .ts/.tsx/.js/.jsx, never pageExtensions like .mdx. The regex is\n // anchored: mts/cts/mjs/cjs (and stray tail matches like `.foots`)\n // are NOT recognized. See design/07-routing.md §\"Page Extensions\".\n if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {\n const key = name as 'middleware' | 'access' | 'route';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // JSON status-code files (401.json, 4xx.json, 503.json, 5xx.json)\n // Recognized regardless of pageExtensions — .json is a data format, not a page extension.\n if (STATUS_CODE_PATTERN.test(name) && ext === 'json') {\n if (!node.jsonStatusFiles) {\n node.jsonStatusFiles = {};\n }\n node.jsonStatusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Status-code files (401.tsx, 4xx.tsx, 503.tsx, 5xx.tsx) — script extensions only (TIM-1505)\n if (STATUS_CODE_PATTERN.test(name) && /^[jt]sx?$/.test(ext)) {\n if (!node.statusFiles) {\n node.statusFiles = {};\n }\n const existing = node.statusFiles[name];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node.statusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Metadata route files (sitemap.ts, robots.ts, icon.tsx, opengraph-image.tsx, etc.)\n // Both static (.xml, .txt, .png, .ico, etc.) and dynamic (.ts, .tsx) files are recognized.\n // When both exist for the same base name, dynamic takes precedence.\n // Two files of the SAME kind (static+static or dynamic+dynamic) are a\n // build error — picking one by readdir order is platform-dependent.\n // See design/16-metadata.md §\"Metadata Routes\"\n const metaInfo = classifyMetadataRoute(entry);\n if (metaInfo) {\n if (!metaInfo.nestable && node.segmentName !== '') {\n throw new Error(\n `Build error: '${name}' is a root-only metadata convention and must be in the app root directory.\\n` +\n ` File: ${fullPath}\\n` +\n ` Move this file to the app root (not a route group or nested segment).`\n );\n }\n if (!node.metadataRoutes) {\n node.metadataRoutes = {};\n }\n const existing = node.metadataRoutes[name];\n if (existing) {\n const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);\n const newIsDynamic = isDynamicMetadataExtension(name, ext);\n if (existingIsDynamic === newIsDynamic) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n // Dynamic > static precedence: overwrite only when the new file is dynamic.\n if (newIsDynamic) {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n } else {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n }\n }\n\n // Validate: route.ts + page.* is a hard build error\n if (node.route && node.page) {\n throw new Error(\n `Build error: route.ts and page.* cannot coexist in the same segment.\\n` +\n ` route.ts: ${node.route.filePath}\\n` +\n ` page: ${node.page.filePath}\\n` +\n `A URL is either an API endpoint or a rendered page, not both.`\n );\n }\n\n // The per-route CSRF exemption is read from source here, at scan time, so\n // the manifest carries it and the request gate never loads user code to\n // decide it. Any other spelling of the export is a lint error\n // (convention-lint.ts `checkCsrfExports`).\n if (node.route && getCsrfExport(node.route.filePath) === 'exempt') {\n node.csrfExempt = true;\n }\n}\n\n/**\n * Throw a build error for two files claiming the same convention slot in\n * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first\n * is platform-dependent (APFS sorts entries, ext4 does not) — silently\n * picking one would let macOS dev and Linux CI serve different\n * implementations of the same route.\n */\nfunction throwDuplicateConvention(\n convention: string,\n firstPath: string,\n secondPath: string\n): never {\n throw new Error(\n `Build error: duplicate '${convention}' files in the same route segment.\\n` +\n ` File 1: ${firstPath}\\n` +\n ` File 2: ${secondPath}\\n` +\n `Each segment may define '${convention}' at most once. Remove one of the files.`\n );\n}\n\n/**\n * Recursively scan child directories and build the segment tree.\n */\nfunction scanChildren(dirPath: string, parentNode: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n try {\n if (!statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n // Reject directories with encoded path delimiters or null bytes.\n // These can cause route collisions when decoded at the URL boundary.\n // See design/13-security.md §\"Encoded separators rejected\" and §\"Null bytes rejected\".\n if (ENCODED_SEPARATOR_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded path delimiter (%2F or %5C).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded separators in directory names cause route collisions when decoded. ` +\n `Rename the directory to remove the encoded delimiter.`\n );\n }\n // `@children` is the implicit slot a layout's `children` prop fills, and\n // the key of the outlet that carries it (`childrenOutletKey`). A slot\n // directory by that name would claim the same outlet and be rendered in\n // place of the children (design/52-segment-hash-dedupe.md).\n if (entry === '@children') {\n throw new Error(\n `Build error: \"@children\" is reserved and cannot be a slot directory.\\n` +\n ` Directory: ${fullPath}\\n` +\n `A layout's children fill the implicit children slot. Put this content in the ` +\n `parent segment's page, or give the slot another name.`\n );\n }\n if (NULL_BYTE_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded null byte (%00).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded null bytes in directory names are not allowed. ` +\n `Rename the directory to remove the null byte encoding.`\n );\n }\n\n const {\n type,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n } = classifySegment(entry);\n\n // Skip private folders — underscore-prefixed dirs are excluded from routing\n if (type === 'private') continue;\n\n const urlPath = computeUrlPath(parentNode.urlPath, entry, type);\n const childNode = createSegmentNode(\n entry,\n type,\n urlPath,\n paramName,\n interceptionMarker,\n interceptedSegmentName,\n paramPrefix,\n paramSuffix\n );\n\n // Scan this segment's files\n scanSegmentFiles(fullPath, childNode, extSet);\n\n // Recurse into subdirectories\n scanChildren(fullPath, childNode, extSet);\n\n // Attach to parent: slots go into slots record, everything else is a child\n if (type === 'slot') {\n const slotName = entry.slice(1); // remove @\n parentNode.slots[slotName] = childNode;\n } else {\n parentNode.children.push(childNode);\n }\n }\n}\n\n/**\n * Validate that no route chain contains duplicate dynamic param names.\n *\n * Example violation:\n * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.\n *\n * Route groups are transparent — params accumulate through them.\n * Slots are independent — duplicate detection does NOT cross slot boundaries.\n *\n * See design/07-routing.md §\"Duplicate Param Name Detection\"\n */\nfunction validateDuplicateParamNames(root: SegmentNode): void {\n walkForDuplicateParams(root, new Map());\n}\n\n/**\n * Recursively walk the segment tree, tracking seen param names → segment paths.\n * Throws on the first duplicate found.\n */\nfunction walkForDuplicateParams(node: SegmentNode, seen: Map<string, string>): void {\n // Read through the effective identity so an intercepting directory is seen\n // as the segment it intercepts: the scanner leaves `paramName` unset on\n // `(.)[id]`, so a validator reading the node directly is blind to a param\n // the resolver goes on to bind — `@modal/(.)[id]/[id]` would pass here and\n // then silently overwrite the outer `id` at match time, where the ordinary\n // `/[id]/[id]` is rejected. See TIM-1288.\n const { paramName } = effectiveUrlSegment(node);\n\n // If this node introduces a param name, check for duplicates\n if (paramName) {\n const existing = seen.get(paramName);\n if (existing) {\n throw new Error(\n `[timber] Duplicate param name '${paramName}' in route chain.\\n` +\n ` First defined at: ${existing}\\n` +\n ` Duplicate at: ${node.urlPath || '/'}\\n` +\n ` Rename one of the segments to avoid ambiguity.`\n );\n }\n // Add to seen for descendants (use a new Map to avoid polluting siblings)\n seen = new Map(seen);\n seen.set(paramName, node.urlPath || '/');\n }\n\n // Recurse into children (they inherit the accumulated params)\n for (const child of node.children) {\n walkForDuplicateParams(child, seen);\n }\n\n // A slot INHERITS the ancestor params rather than starting fresh: a slot\n // child may not reuse a name its owner already bound\n // (`app/gallery/[id]/@modal/[id]` is rejected). The copy is so sibling\n // slots don't see each other's names, not so the chain is reset.\n //\n // Whether that rule is right is a separate question — slot params are\n // merged over the main route's at read time, so a collision is defined\n // rather than ambiguous — but changing it would change every slot.\n // Tracked as TIM-1287; do not \"fix\" this by making the map fresh without\n // deciding that.\n for (const slotNode of Object.values(node.slots)) {\n walkForDuplicateParams(slotNode, new Map(seen));\n }\n}\n\n/**\n * Validate that each param name uses a single bracket form across the entire route tree.\n *\n * Different bracket forms produce different types:\n * [id] → string\n * [...id] → string[]\n * [[...id]] → string[] | undefined\n *\n * If the same param name appears with multiple forms, the no-argument\n * getSegmentParams() / useSegmentParams() return type becomes ambiguous.\n *\n * Same name + same form across different routes is fine and expected.\n */\nfunction validateUniqueBracketForms(root: SegmentNode): void {\n const forms = new Map<string, { segmentType: SegmentType; urlPath: string }>();\n collectBracketForms(root, forms);\n}\n\nfunction collectBracketForms(\n node: SegmentNode,\n forms: Map<string, { segmentType: SegmentType; urlPath: string }>\n): void {\n // Effective identity, so `(.)[...rest]` is compared as the catch-all it\n // intercepts rather than skipped as an 'intercepting' node (TIM-1288).\n const { paramName, segmentType } = effectiveUrlSegment(node);\n\n if (paramName && segmentType !== 'static' && segmentType !== 'group') {\n const existing = forms.get(paramName);\n if (existing && existing.segmentType !== segmentType) {\n const bracketExamples: Record<string, string> = {\n 'dynamic': `[${paramName}]`,\n 'catch-all': `[...${paramName}]`,\n 'optional-catch-all': `[[...${paramName}]]`,\n };\n throw new Error(\n `[timber] Param name '${paramName}' uses multiple bracket forms.\\n` +\n ` ${bracketExamples[existing.segmentType] ?? existing.segmentType} at: ${existing.urlPath}\\n` +\n ` ${bracketExamples[segmentType] ?? segmentType} at: ${node.urlPath || '/'}\\n` +\n ` Each param name must use a single bracket form across all routes.\\n` +\n ` Rename one of the segments to fix this (e.g., [${paramName}] → [${paramName}Id]).`\n );\n }\n if (!existing) {\n forms.set(paramName, {\n segmentType,\n urlPath: node.urlPath || '/',\n });\n }\n }\n\n for (const child of node.children) {\n collectBracketForms(child, forms);\n }\n for (const slotNode of Object.values(node.slots)) {\n collectBracketForms(slotNode, forms);\n }\n}\n\n/**\n * Validate that no sibling affixed dynamic segments have equal specificity.\n *\n * Among affixed siblings, longer combined prefix+suffix length wins. When two\n * siblings tie (same total affix length), the router would fall back to\n * filesystem scan order — which is platform-dependent. This is a build error.\n *\n * Route groups are URL-transparent, so affixed segments inside different groups\n * at the same level still conflict with each other.\n *\n * Ambiguity requires the two segments to be candidates for the *same* URL\n * part, which is narrower than \"same parent\" once interception is involved:\n *\n * - Plain children and intercepting children never compete. They are resolved\n * by different walks — `findSlotMatch` matches the slot subtree (where\n * `tree-match.ts` ignores intercepting nodes outright) and\n * `findInterceptingMatch` builds a synthetic parent holding only\n * interceptors.\n * - Two interceptors compete only at the same anchor. `(.)a-[id]` and\n * `(..)[slug]-b` in one slot are based at different URL depths, so no\n * pathname reaches both, and `anchorIndex` rejects the one whose base does\n * not match the target. Grouping them together would fail the build for a\n * pair that can never be ambiguous.\n *\n * So candidates are keyed by the position they contend for, then by affix\n * length. See design/07-routing.md §\"Priority\" and §\"Intercepting Routes\".\n */\nfunction validateAffixedSiblingConflicts(node: SegmentNode): void {\n const affixed = collectEffectiveAffixed(node);\n\n if (affixed.length >= 2) {\n const byLength = new Map<string, SegmentNode[]>();\n for (const child of affixed) {\n // `\\0` as the separator, written as the escape rather than a literal\n // byte: a raw NUL in the source makes git and grep treat this file as\n // binary. A contention key is a URL path, which cannot contain one, so\n // the two halves of the key can never run together.\n const key = `${contentionKey(node, child)}\\0${affixLengthOf(child)}`;\n const group = byLength.get(key);\n if (group) {\n group.push(child);\n } else {\n byLength.set(key, [child]);\n }\n }\n\n for (const [, group] of byLength) {\n if (group.length >= 2) {\n throw new Error(\n `Build error: ambiguous affixed dynamic siblings with equal specificity.\\n` +\n ` Parent: ${node.urlPath || '/'}\\n` +\n ` Segments: ${group.map((s) => s.segmentName).join(', ')}\\n` +\n ` Combined prefix+suffix length: ${affixLengthOf(group[0]!)}\\n` +\n `The router cannot deterministically choose between these — filesystem scan order is platform-dependent.\\n` +\n `Rename one segment to give it a longer or shorter combined affix.`\n );\n }\n }\n }\n\n for (const child of node.children) {\n validateAffixedSiblingConflicts(child);\n }\n for (const slotNode of Object.values(node.slots)) {\n validateAffixedSiblingConflicts(slotNode);\n }\n}\n\n/**\n * The URL position a child contends for, as a comparable key.\n *\n * Plain children contend for the parent's next part. An intercepting child\n * contends for a part determined by its marker's intercepted base, so two\n * markers of different depth are simply different positions — and two markers\n * that compute the *same* base do contend, which is why the key is the base\n * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).\n *\n * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical\n * statement of that grouping — it is what the resolver walks and what the\n * collision validator checks. This computes the same key from the same\n * `computeInterceptedBase` rather than calling it, because affix ambiguity is\n * decided per *child* and `collectEffectiveAffixed` looks through route groups,\n * so the two do not partition the same set of nodes.\n */\nfunction contentionKey(parent: SegmentNode, child: SegmentNode): string {\n if (child.segmentType !== 'intercepting') return 'child';\n return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? '(.)')}`;\n}\n\n/** Combined affix length of a node, read through its effective identity. */\nfunction affixLengthOf(node: SegmentNode): number {\n const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);\n return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);\n}\n\n/**\n * Collect affixed dynamic segments that are effective children of a node.\n * Route groups are URL-transparent, so we look through them recursively.\n *\n * Segments are read through `effectiveUrlSegment`, so an intercepting\n * directory counts as the affixed segment it intercepts: `(.)a-[id]` is\n * `a-[id]`. The proxy the slot resolver builds hands those affixes to\n * `matchUrlParts`, whose equal-length sort is not stable across equal\n * specificity — so two intercepting siblings with the same combined affix\n * length would resolve by filesystem enumeration order, which is precisely\n * what this validator exists to prevent for ordinary siblings (TIM-1288).\n */\nfunction collectEffectiveAffixed(node: SegmentNode): SegmentNode[] {\n const result: SegmentNode[] = [];\n for (const child of node.children) {\n const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);\n if (segmentType === 'dynamic' && (paramPrefix || paramSuffix)) {\n result.push(child);\n } else if (segmentType === 'group') {\n result.push(...collectEffectiveAffixed(child));\n }\n }\n return result;\n}\n\n/**\n * Find a fixed-extension file (proxy.ts) in a directory.\n */\nfunction findFixedFile(dirPath: string, name: string): RouteFile | undefined {\n for (const ext of ['ts', 'tsx']) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n\n/**\n * Find a file with script extensions (tsx, ts, jsx, js) in a directory.\n * Used for app-root conventions like global-error that only accept script\n * extensions (TIM-1505).\n */\nfunction findScriptExtFile(dirPath: string, name: string): RouteFile | undefined {\n for (const ext of ['tsx', 'ts', 'jsx', 'js']) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n"],"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OAAO,KAAK,KAAK;OACZ,IAAI,gBAAgB,SACzB,OAAO,KAAK,GAAG,wBAAwB,KAAK,CAAC;CAEjD;CACA,OAAO;AACT;;;;AAKA,SAAS,cAAc,SAAiB,MAAqC;CAC3E,KAAK,MAAM,OAAO,CAAC,MAAM,KAAK,GAAG;EAC/B,MAAM,WAAW,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;EAC/C,IAAI;GACF,IAAI,SAAS,QAAQ,CAAC,CAAC,OAAO,GAC5B,OAAO;IAAE,UAAU;IAAU,WAAW;GAAI;EAEhD,QAAQ,CAER;CACF;AAEF;;;;;;AAOA,SAAS,kBAAkB,SAAiB,MAAqC;CAC/E,KAAK,MAAM,OAAO;EAAC;EAAO;EAAM;EAAO;CAAI,GAAG;EAC5C,MAAM,WAAW,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;EAC/C,IAAI;GACF,IAAI,SAAS,QAAQ,CAAC,CAAC,OAAO,GAC5B,OAAO;IAAE,UAAU;IAAU,WAAW;GAAI;EAEhD,QAAQ,CAER;CACF;AAEF"}
|
|
1
|
+
{"version":3,"file":"scanner-CCEHN9Jg.js","names":[],"sources":["../../src/routing/collision-spaces.ts","../../src/routing/slot-placement.ts","../../src/routing/file-cache.ts","../../src/routing/export-detect.ts","../../src/routing/scanner.ts"],"sourcesContent":["/**\n * Route collision spaces.\n *\n * A collision space is a set of routes that compete for URLs with each other,\n * and there are three: the main tree, each parallel slot, and each intercepting\n * subtree. This module owns the first two; `interception.ts` owns the third.\n * All of them decide order-dependence with the one oracle in\n * `collision-probe.ts`, so they cannot drift on what counts as two routes\n * answering a single URL.\n *\n * See design/07-routing.md §\"Route Collisions\".\n */\n\nimport type { SegmentNode } from './types.ts';\nimport { computeInterceptedUrlBase } from './interception.ts';\nimport { findOrderDependentCollision, type ProbeLeaf } from './collision-probe.ts';\n\n/**\n * Validate that no two pages/routes in one collision space answer the same URL.\n *\n * Two route groups like (auth)/login/page.tsx and (marketing)/login/page.tsx both claim\n * /login — the scanner must detect and reject this at build time.\n *\n * Each parallel slot is validated as its OWN collision space: a slot's pages\n * intentionally share URL paths with the parent tree (that's the point of\n * parallel routes), but two route groups INSIDE one slot claiming the same\n * URL — e.g. @side/(a)/x/page.tsx + @side/(b)/x/page.tsx — still collide.\n */\nexport function validateRouteGroupCollisions(root: SegmentNode): void {\n validateCollisionSpace(root, '', root.urlPath);\n}\n\n/**\n * Validate one collision space — the main tree, or one parallel slot.\n *\n * **Two checks, and the difference between them matters.** Two leaves at the\n * same `urlPath` are decided by string equality, which is exact and needs no\n * probing: `(auth)/login` and `(marketing)/login` claim one set of URLs\n * whatever the precedence rules are, and naming the shared path is the clearest\n * thing to tell the author.\n *\n * Everything else is decided by asking the matcher, through the shared oracle\n * in `collision-probe.ts` (TIM-1308). Comparing `urlPath` spellings misses\n * every pair that matches the same URLs while being *spelled* differently:\n * `x/(a)/[id]` beside `x/(b)/[slug]` are two bare dynamics in one priority\n * tier, and `x/(a)/page.tsx` beside `x/(b)/[[...rest]]` both answer `/x`\n * because an optional catch-all also matches zero parts. Both built before\n * TIM-1308 with filesystem enumeration order deciding which page renders,\n * which is precisely what this validator and `validateAffixedSiblingConflicts`\n * exist to reject.\n *\n * Segment *kinds* stay distinct without any special-casing here, because the\n * oracle inherits `matchNode`'s priority ordering: `x/(a)/[id]` beside\n * `x/(b)/[...rest]` resolves the same way in either `children` order, so it is\n * not reported. So does an affixed sibling against a bare one; the\n * equal-specificity affix tie is `validateAffixedSiblingConflicts`' job, and\n * duplicating it here would double-report.\n */\nfunction validateCollisionSpace(spaceRoot: SegmentNode, segmentPath: string, base: string): void {\n const leaves: ProbeLeaf[] = [];\n collectRoutableLeaves(spaceRoot, new Map(), segmentPath, [], leaves, base);\n\n const collision = findOrderDependentCollision(spaceRoot, leaves, base);\n if (!collision) return;\n\n throw new Error(\n `Build error: route collision — two pages/routes answer the same URL.\\n` +\n ` URL: ${collision.url}\\n` +\n ` File 1: ${collision.first}\\n` +\n ` File 2: ${collision.second}\\n` +\n `Both match it, so which one renders would be decided by filesystem enumeration ` +\n `order — renaming a route group can flip it. Rename or move one of them.\\n` +\n `Routes are compared by the URLs they match, not by how they are spelled: [id] and ` +\n `[slug] match the same URLs, and an optional catch-all also matches with zero ` +\n `segments.`\n );\n}\n\n/**\n * Walk one collision space and collect its routable leaves (page or route\n * files), throwing on an exact `urlPath` collision. Each slot recurses as its\n * OWN space — slots are parallel routes that intentionally share URL paths with\n * their parent tree, but collisions within a single slot are real errors.\n *\n * The early return at an intercepting node drops that subtree's own pages from\n * this space, but not its slots: a slot is its own collision space wherever it\n * sits, so `validateSlotsInsideInterceptingSubtree` picks those up before\n * returning.\n *\n * `chain` accumulates the URL-contributing nodes from the space root down, for\n * the probe oracle. Route groups are excluded because they are transparent for\n * matching, and the space root itself is excluded because `matchUrlParts`\n * matches parts against its *children* — the root consumes nothing.\n */\nfunction collectRoutableLeaves(\n node: SegmentNode,\n seen: Map<string, { filePath: string; segmentPath: string }>,\n segmentPath: string,\n chain: SegmentNode[],\n leaves: ProbeLeaf[],\n base: string\n): void {\n // Intercepting routes are resolved by the interception resolvers, not URL\n // matching, and their computed urlPaths are not addresses — an interception\n // mirrors the canonical route it replaces, so comparing those paths here\n // would reject every correct interception. Skipping is not \"unvalidated\":\n // `assertNoInterceptedPatternCollisions` gives each intercepting subtree its\n // own collision space, keyed by the intercepted pattern rather than by these\n // paths (TIM-1305). See design/07-routing.md §\"Collisions Inside an\n // Intercepting Subtree\" and §\"Why urlPath Stays Parent-Relative Inside an\n // Intercepting Subtree\".\n const currentPath = segmentPath\n ? `${segmentPath}/${node.segmentName}`\n : node.segmentName || '(root)';\n\n // The intercepting subtree's own pages leave this space — but its SLOTS do\n // not leave every space, so they are picked up before returning. See\n // `validateSlotsInsideInterceptingSubtree`.\n if (node.segmentType === 'intercepting') {\n // `node.urlPath` on an intercepting node is its OWNER's path — the input\n // `computeInterceptedUrlBase` wants — because an intercepting segment adds\n // no URL depth.\n validateSlotsInsideInterceptingSubtree(\n node,\n currentPath,\n interceptedBaseOf(node, node.urlPath)\n );\n return;\n }\n\n const routableFile = node.page ?? node.route;\n if (routableFile) {\n const existing = seen.get(node.urlPath);\n if (existing) {\n throw new Error(\n `Build error: route collision — multiple route groups produce a page/route at the same URL path.\\n` +\n ` URL path: ${urlFromChain(base, chain)}\\n` +\n ` File 1: ${existing.filePath} (via ${existing.segmentPath})\\n` +\n ` File 2: ${routableFile.filePath} (via ${currentPath})\\n` +\n `Each URL path must map to exactly one page or route handler. ` +\n `Rename or move one of the conflicting files.`\n );\n }\n seen.set(node.urlPath, { filePath: routableFile.filePath, segmentPath: currentPath });\n leaves.push({ filePath: routableFile.filePath, chain });\n }\n\n // Recurse into children. A route group contributes no URL part, so it is\n // absent from the chain — exactly as `collectEffectiveChildren` flattens it\n // away in the matcher.\n for (const child of node.children) {\n const isGroup = child.segmentType === 'group';\n collectRoutableLeaves(\n child,\n seen,\n currentPath,\n isGroup ? chain : [...chain, child],\n leaves,\n base\n );\n }\n\n // Recurse into slots — each slot is its own collision space, with its own\n // seen map, its own leaf set and its own probe run.\n //\n // The base is accumulated from this space's own base rather than read off\n // `slotNode.urlPath`, because this walk also runs on slot spaces nested inside\n // an intercepting subtree, where `urlPath` is parent-relative and not an\n // address. Outside one the two are identical by construction.\n for (const slotNode of Object.values(node.slots)) {\n validateCollisionSpace(slotNode, currentPath, urlFromChain(base, chain));\n }\n}\n\n/**\n * Validate every parallel slot nested anywhere inside an intercepting subtree.\n *\n * Two walks each skip these slots for their own good reason, and together they\n * left them checked by nothing: `collectRoutableLeaves` returns at the\n * intercepting node before it reaches them, and `walkInterceptedLeaves`\n * deliberately does not descend slots — correct for rewrite generation, since a\n * slot inside an intercepting subtree produces no rewrite. But \"produces no\n * rewrite\" answers the rewrite question and not the resolution one, so\n * `@side/(a)/x/page.tsx` beside `@side/(b)/x/page.tsx` under an interceptor\n * built with filesystem order picking the page — the ordinary per-slot\n * collision that fails the build anywhere else in the tree (codex, on PR #1002).\n *\n * A slot is its own collision space wherever it sits, so each one is validated\n * as one.\n *\n * **Which interception shape this still applies to.** TIM-1311 answered the\n * question this was written under — whether such a slot renders at all — and\n * the answer is per-shape:\n *\n * - **Children path** (`(browse)/(...)photo/@side`): the intercepting node\n * joins the main route chain, so `route-element-builder.ts` resolves slots on\n * it and below it like any other chain segment. They render, and this is the\n * space where the check is load-bearing.\n * - **Modal** (`feed/@modal/(.)photo/@side`): the slot sits inside another\n * slot's subtree, which no renderer descends for slots — so it never renders,\n * and `validateSlotPlacement` now rejects the placement before this runs.\n * That rule subsumes this one for the modal shape rather than conflicting\n * with it, exactly as anticipated.\n *\n * So this walk is reached only for children-path interceptors in a valid tree.\n * It is not narrowed to them: the rule it states — a slot is its own collision\n * space wherever it sits — is shape-independent, and making it conditional on a\n * property the placement validator already guarantees would just be a second\n * place for the two to disagree.\n *\n * The walk covers the whole subtree, not just the interceptor's direct slot\n * children: `(...)photo/[id]/@side` is reached by neither walk for exactly the\n * same reason as `(...)photo/@side`.\n */\nfunction validateSlotsInsideInterceptingSubtree(\n node: SegmentNode,\n segmentPath: string,\n base: string\n): void {\n for (const slotNode of Object.values(node.slots)) {\n // A slot adds no URL depth, so it answers its owner's base.\n validateCollisionSpace(slotNode, segmentPath, base);\n }\n for (const child of node.children) {\n validateSlotsInsideInterceptingSubtree(\n child,\n `${segmentPath}/${child.segmentName}`,\n childInterceptedBase(child, base)\n );\n }\n}\n\n/**\n * The URL a leaf answers, built from its space's base and its own chain.\n *\n * Read instead of `node.urlPath` because `urlPath` inside an intercepting\n * subtree is parent-relative and is not an address — the collision URL has to\n * be one the author can actually find. Outside an intercepting subtree the two\n * are identical by construction: the base is the space root's `urlPath` and the\n * chain is every URL-contributing segment below it.\n */\nfunction urlFromChain(base: string, chain: SegmentNode[]): string {\n if (chain.length === 0) return base || '/';\n const tail = chain.map((n) => n.segmentName).join('/');\n return `${base === '/' ? '' : base}/${tail}`;\n}\n\n/**\n * The intercepted URL an intercepting directory's own page sits at.\n *\n * `urlPath` inside an intercepting subtree is deliberately parent-relative and\n * is **not** an address (see design/07-routing.md §\"Why urlPath Stays\n * Parent-Relative Inside an Intercepting Subtree\"), so a collision reported\n * from one names a URL the author cannot find. The intercepted base is the real\n * address, and it is what rewrite generation and the interception collision\n * validator both already use.\n */\nfunction interceptedBaseOf(node: SegmentNode, ownerUrlPath: string): string {\n return computeInterceptedUrlBase(\n ownerUrlPath,\n node.interceptionMarker ?? '(.)',\n node.interceptedSegmentName ?? node.segmentName\n );\n}\n\n/**\n * Extend an intercepted base by one child segment.\n *\n * Route groups are transparent and contribute nothing. A nested intercepting\n * node re-bases from its own marker rather than appending — that tree is\n * rejected by `validateInterceptionPlacement`, but collision validation runs\n * first, so it still has to produce a sensible URL rather than one containing a\n * literal \"(.)b\".\n */\nfunction childInterceptedBase(child: SegmentNode, base: string): string {\n // Slots are not in `children` — `scanChildren` files them under `slots` — so\n // only groups are transparent here.\n if (child.segmentType === 'group') return base;\n if (child.segmentType === 'intercepting') return interceptedBaseOf(child, base);\n return base === '/' ? `/${child.segmentName}` : `${base}/${child.segmentName}`;\n}\n","/**\n * Parallel slot placement.\n *\n * One rule: a slot is resolved only for a segment on the **matched route\n * chain**, and a slot's own subtree is never on that chain. So a slot declared\n * anywhere inside another slot's subtree can never render, and is rejected at\n * build time rather than left as a directory the author will keep editing.\n *\n * See design/07-routing.md §\"Parallel Routes\".\n */\n\nimport type { SegmentNode } from './types.ts';\n\n/**\n * Reject every parallel slot that no renderer reaches.\n *\n * **Where slots are resolved.** Two places read `segment.slots`, and both walk\n * the main route chain: `route-element-builder.ts` (the RSC render).\n * It is not reachable from inside a slot. The slot's own\n * subtree is rendered by `slot-resolver.ts`, which walks the slot's matched\n * chain to apply that chain's layouts, error boundaries and access gates\n * (`wrapWithIntermediateSegments`, `wrapWithLayout`) and never reads `.slots`\n * on any of those nodes. So `app/feed/@modal/photo/@side/page.tsx` and\n * everything below it is dead: the file is scanned, typed, code-split and\n * shipped, and no request can render it.\n *\n * That is the TIM-1278 failure — a directory that silently never renders —\n * and the reason it is a build error rather than a documented limit is that\n * nothing at request time can report it. A slot that does not match renders\n * `default.tsx` or `null`, which is exactly what a slot the resolver never\n * looked at also produces, so the author sees the *designed* behaviour of a\n * non-matching slot and has no signal to distinguish it from a slot that\n * cannot match at all.\n *\n * **Interception is incidental.** TIM-1311 arrived as\n * `feed/@modal/(.)photo/@side`, and the interception contributes nothing: the\n * identical `feed/@modal/photo/@side` never renders either, for the same\n * reason and with no marker anywhere. Rejecting only the intercepting spelling\n * would have drawn a line the author cannot see from the directory names.\n *\n * The children-path interception shape is **not** affected and must not be:\n * its intercepting node joins the main chain (`server/children-interception.ts`\n * splices `[…owner ancestors, interceptingNode, …descendants]` into an ordinary\n * `RouteMatch`), so `route-element-builder.ts` resolves slots on it and below\n * it exactly as it does for any other chain segment. `(browse)/(...)photo/[id]/@side`\n * renders; `feed/@modal/(.)photo/@side` does not. The discriminator is the slot\n * boundary, which is what this walk tracks — not the marker.\n */\nexport function validateSlotPlacement(root: SegmentNode): void {\n walkForSlotPlacement(root, '', null);\n}\n\n/**\n * `enclosingSlotPath` is the `app/`-relative path of the nearest slot at or\n * above `node`, or null on the main chain. It is carried rather than recomputed\n * so the error can name the slot that swallows the offender — \"this is inside\n * @modal\" is the part of the diagnosis the author cannot see from the offending\n * path alone.\n */\nfunction walkForSlotPlacement(\n node: SegmentNode,\n path: string,\n enclosingSlotPath: string | null\n): void {\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotPath = path ? `${path}/@${slotName}` : `@${slotName}`;\n if (enclosingSlotPath !== null) {\n throwNestedSlot(slotPath, enclosingSlotPath);\n }\n walkForSlotPlacement(slotNode, slotPath, slotPath);\n }\n\n for (const child of node.children) {\n walkForSlotPlacement(\n child,\n path ? `${path}/${child.segmentName}` : child.segmentName,\n enclosingSlotPath\n );\n }\n}\n\nfunction throwNestedSlot(slotPath: string, enclosingSlotPath: string): never {\n throw new Error(\n `Build error: parallel slot nested inside another parallel slot.\\n` +\n ` Directory: app/${slotPath}\\n` +\n ` Inside: app/${enclosingSlotPath}\\n` +\n `A parallel slot is resolved only for a segment on the matched route chain, and a ` +\n `slot's own subtree is never on that chain — the slot resolver walks the slot's ` +\n `matched chain to apply its layouts, error boundaries and access gates, and never ` +\n `looks at slots declared inside it. So app/${slotPath} and everything below it can ` +\n `never render, and no request-time signal can tell you: an unreachable slot ` +\n `produces exactly what a slot that simply did not match produces.\\n` +\n `Declare the slot on a segment of the main route chain instead, or move its pages ` +\n `into app/${enclosingSlotPath}'s own subtree.\\n` +\n `See design/07-routing.md §\"Parallel Routes\".`\n );\n}\n","import { readFileSync, statSync } from 'node:fs';\n\nconst cache = new Map<string, { mtimeMs: number; size: number; content: string }>();\n\n/**\n * Read a file's text content, returning a cached copy when the file\n * hasn't been modified since the last read (checked via mtime + size).\n *\n * Falls back to a fresh read on any stat/read error.\n */\nexport function readFileCached(filePath: string): string {\n try {\n const stat = statSync(filePath);\n const entry = cache.get(filePath);\n if (entry && entry.mtimeMs === stat.mtimeMs && entry.size === stat.size) return entry.content;\n const content = readFileSync(filePath, 'utf-8');\n cache.set(filePath, { mtimeMs: stat.mtimeMs, size: stat.size, content });\n return content;\n } catch {\n cache.delete(filePath);\n return readFileSync(filePath, 'utf-8');\n }\n}\n","/**\n * AST-based export detection for route files.\n *\n * Uses Vite's `parseAst` (backed by oxc) to precisely detect named and\n * default exports, replacing the regex-based approach that was fragile\n * with TypeScript syntax (type exports, `as` aliases, comments, etc.).\n */\n\nimport { existsSync } from 'node:fs';\nimport { parseAst } from 'vite';\nimport { readFileCached } from './file-cache.ts';\n\ninterface AstNode {\n type: string;\n exportKind?: string;\n declaration?: AstNode;\n specifiers?: Array<{\n exported?: { name: string };\n local?: { name: string };\n exportKind?: string;\n }>;\n id?: { name: string };\n declarations?: Array<{ id?: { name: string }; init?: AstNode }>;\n /** Set on re-exports: `export { X } from './y'`. Absent on local exports. */\n source?: { value?: string } | null;\n /** Set on runtime-transparent wrappers: `X as T`, `X satisfies T`, `(X)`, `X!`. */\n expression?: AstNode;\n /** Set on `Identifier` nodes. */\n name?: string;\n}\n\ninterface ProgramNode {\n body: AstNode[];\n}\n\n/**\n * Parse a module. `lang` defaults to `tsx`; pass `ts` for `.ts` files, where\n * an angle-bracket cast or a generic arrow (`<T>(x: T) => x`) is valid\n * TypeScript but a TSX parse error.\n */\nexport function tryParse(source: string, lang: 'ts' | 'tsx' = 'tsx'): ProgramNode | null {\n try {\n return parseAst(source, { lang }) as unknown as ProgramNode;\n } catch {\n return null;\n }\n}\n\n/**\n * Collect all named export identifiers from a parsed program.\n * Handles: `export function X`, `export const X`, `export { X }`,\n * `export { X } from '...'`, `export { Y as X }`.\n */\nfunction collectNamedExports(program: ProgramNode): Set<string> {\n const names = new Set<string>();\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n // Skip `export type ...` declarations — they're erased at runtime\n if (stmt.exportKind === 'type') continue;\n\n if (stmt.declaration) {\n if (stmt.declaration.id?.name) {\n names.add(stmt.declaration.id.name);\n }\n if (stmt.declaration.declarations) {\n for (const decl of stmt.declaration.declarations) {\n if (decl.id?.name) names.add(decl.id.name);\n }\n }\n }\n\n if (stmt.specifiers) {\n for (const spec of stmt.specifiers) {\n // Skip `export { type X }` — per-specifier type exports\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name && spec.exported.name !== 'default') {\n names.add(spec.exported.name);\n }\n }\n }\n }\n return names;\n}\n\n/**\n * The specifier exporting a *runtime* default from this statement, if any.\n *\n * Type-only exports erase, so they are not default exports at runtime — and\n * TypeScript spells that two ways, on two different nodes: `export type { X as\n * default }` marks the **statement**, `export { type X as default }` marks the\n * **specifier**. Both have to be checked, or a type alias reads as a component:\n * a status file whose only default is a type has nothing for the error boundary\n * to receive (the renderer's `mod?.default` skips it), so treating it as one\n * would fail a build over a file that cannot break anything.\n *\n * One implementation because two callers must agree on what \"has a default\n * export\" means: `hasDefaultExport` decides whether to warn that a page has\n * none, and `fileDefaultExportIsLocalValue` decides whether to fail the build.\n */\nfunction defaultSpecifier(stmt: AstNode): NonNullable<AstNode['specifiers']>[number] | null {\n if (stmt.type !== 'ExportNamedDeclaration' || !stmt.specifiers) return null;\n if (stmt.exportKind === 'type') return null;\n for (const spec of stmt.specifiers) {\n if (spec.exportKind === 'type') continue;\n if (spec.exported?.name === 'default') return spec;\n }\n return null;\n}\n\n/**\n * Check whether a program has a default export.\n * Handles: `export default ...`, `export { X as default }`,\n * `export { default } from '...'`. Type-only defaults do not count —\n * see `defaultSpecifier`.\n */\nfunction hasDefaultExport(program: ProgramNode): boolean {\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') return true;\n if (defaultSpecifier(stmt)) return true;\n }\n return false;\n}\n\n/**\n * Check whether a program has any bare `export * from '...'` declarations.\n * Excludes `export * as X from '...'` (namespace re-exports) since those\n * create a namespace object, not individual top-level exports.\n */\nfunction hasStarExport(program: ProgramNode): boolean {\n return program.body.some(\n (stmt) =>\n stmt.type === 'ExportAllDeclaration' && !(stmt as any).exported && stmt.exportKind !== 'type'\n );\n}\n\n/**\n * Check if a file exports a specific named export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasExport(filePath: string, exportName: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return collectNamedExports(program).has(exportName);\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any of the given named exports.\n * Returns the set of matching export names.\n */\nexport function fileHasAnyExport(filePath: string, exportNames: readonly string[]): Set<string> {\n const matches = new Set<string>();\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return matches;\n const exports = collectNamedExports(program);\n for (const name of exportNames) {\n if (exports.has(name)) matches.add(name);\n }\n } catch {\n // Graceful fallback: return empty set\n }\n return matches;\n}\n\n/**\n * Check if a file has a default export.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasDefaultExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasDefaultExport(program);\n } catch {\n return false;\n }\n}\n\n/** Node types whose value is unambiguously constructed by this module. */\nconst FUNCTION_LIKE = new Set([\n 'FunctionDeclaration',\n 'FunctionExpression',\n 'ArrowFunctionExpression',\n 'ClassDeclaration',\n 'ClassExpression',\n]);\n\n/**\n * Expression wrappers that erase at runtime and so cannot change where a value\n * was constructed: `X as T`, `X satisfies T`, `<T>X`, `X!`, `X<T>`, `(X)`.\n */\nexport const TRANSPARENT_WRAPPERS: ReadonlySet<string> = new Set([\n 'TSAsExpression',\n 'TSSatisfiesExpression',\n 'TSTypeAssertion',\n 'TSNonNullExpression',\n 'TSInstantiationExpression',\n 'ParenthesizedExpression',\n]);\n\n/**\n * Strip runtime-transparent wrappers so the node underneath can be classified.\n *\n * Without this, `(() => <h1 />) satisfies React.FC` reads as a\n * `TSSatisfiesExpression` rather than the arrow function it compiles to, and a\n * provably-local component is misread as one whose origin cannot be\n * determined — turning a build error into a warning.\n */\nfunction unwrapTransparent(node: AstNode): AstNode {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type) && current.expression) {\n current = current.expression;\n }\n return current;\n}\n\n/**\n * Whether `name` is bound at module top level to a function or class written\n * in this file. An imported binding can never match: imports are\n * `ImportDeclaration` specifiers, not function/class/variable declarations,\n * and a module-level name cannot be both.\n */\nfunction bindsLocalFunction(program: ProgramNode, name: string): boolean {\n for (const stmt of program.body) {\n // `export function X() {}` binds X locally too — unwrap the export.\n const decl = stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt;\n if (!decl) continue;\n if (\n (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') &&\n decl.id?.name === name\n ) {\n return true;\n }\n if (decl.type === 'VariableDeclaration') {\n for (const d of decl.declarations ?? []) {\n if (d.id?.name === name && d.init && FUNCTION_LIKE.has(unwrapTransparent(d.init).type)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\n/**\n * Whether the default export is *provably* a value constructed by this module:\n * `export default function/class/() => {}`, or a name bound to a function or\n * class declared here — whether it leaves via `export default Name` or\n * `export { Name as default }`. Both spellings are the same fact about where\n * the value was built, so both must answer the same way.\n *\n * This is the sound half of \"is this a server component?\". A file with no\n * `'use client'` directive whose default export is built here is a server\n * component, full stop. Everything else — `export { default } from\n * './client-thing'`, `export default Imported`, `export default memo(X)`,\n * an unparseable file — returns false, because the exported value may have\n * been minted in a module that *does* carry the directive. Callers must not\n * infer \"server component\" from a missing directive alone.\n */\nexport function fileDefaultExportIsLocalValue(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type === 'ExportDefaultDeclaration') {\n const decl = stmt.declaration && unwrapTransparent(stmt.declaration);\n if (!decl) return false;\n if (FUNCTION_LIKE.has(decl.type)) return true;\n if (decl.type === 'Identifier' && decl.name) {\n return bindsLocalFunction(program, decl.name);\n }\n return false;\n }\n\n // `export { Name as default }` — the same default export by another\n // spelling. `hasDefaultExport` already counts it, so an analysis that\n // skipped it here would let the exact defect this powers slip through\n // as a warning.\n const spec = defaultSpecifier(stmt);\n if (spec) {\n // `export { X as default } from './client-thing'` re-exports another\n // module's value — the directive governing it lives over there.\n if (stmt.source) return false;\n return spec.local?.name ? bindsLocalFunction(program, spec.local.name) : false;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a file has any `export * from '...'` declarations.\n * Returns false if the file doesn't exist or can't be parsed.\n */\nexport function fileHasStarExport(filePath: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n return hasStarExport(program);\n } catch {\n return false;\n }\n}\n\n/**\n * How a file declares the per-route CSRF exemption.\n *\n * - `'absent'` — no runtime export named `csrf`.\n * - `'exempt'` — exactly `export const csrf = false` (wrappers like\n * `false as const` allowed), declared in this file.\n * - `'invalid'` — some other `csrf` export: another value, `let`, a\n * destructured binding, a specifier or named re-export (`export { csrf }`,\n * `export { x as \"csrf\" }`), a function or class. `export * from` is not\n * followed: a `csrf` it carries is neither exempt nor an error.\n *\n * The exemption is read from source at build time, never from the loaded\n * module, because the CSRF gate runs before any user code (see\n * design/08-forms-and-actions.md §\"Per-route exemption\"). Only the literal\n * form can be read that way; any other spelling is a build error rather\n * than a silent \"not exempt\", so what the developer wrote is what runs.\n */\nexport type CsrfExport = 'absent' | 'exempt' | 'invalid';\n\nexport function getCsrfExport(filePath: string): CsrfExport {\n if (!existsSync(filePath)) return 'absent';\n // Unparseable: not exempt (fail closed). The compiler reports the syntax\n // error; guessing at a half-written file would misreport it.\n const program = tryParse(readFileCached(filePath));\n if (!program) return 'absent';\n\n // Walk the statements directly rather than through `collectNamedExports`:\n // every spelling that exports a runtime `csrf` must be seen here, and\n // that helper does not see destructured declarations or string-literal\n // specifier names. What cannot be seen at all — `export * from` — is\n // not read, and is documented as such.\n let found: CsrfExport = 'absent';\n for (const stmt of program.body) {\n if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type') continue;\n for (const spec of stmt.specifiers ?? []) {\n if (spec.exportKind !== 'type' && specifierName(spec.exported) === 'csrf') {\n return 'invalid';\n }\n }\n const decl = stmt.declaration as (AstNode & { kind?: string }) | undefined;\n if (!decl) continue;\n if (decl.id?.name === 'csrf') return 'invalid'; // function or class\n if (decl.type !== 'VariableDeclaration') continue;\n for (const d of decl.declarations ?? []) {\n const id = d.id as AstNode | undefined;\n if (id?.type === 'Identifier') {\n if (id.name !== 'csrf') continue;\n const init = d.init && (unwrapTransparent(d.init) as AstNode & { value?: unknown });\n const literalFalse = init?.type === 'Literal' && init.value === false;\n if (decl.kind !== 'const' || !literalFalse) return 'invalid';\n found = 'exempt';\n } else if (id && patternBinds(id, 'csrf')) {\n return 'invalid'; // `export const { csrf } = …`\n }\n }\n }\n return found;\n}\n\n/** An export specifier's name: `csrf` or the string literal `\"csrf\"`. */\nfunction specifierName(node: { name?: string; value?: unknown } | undefined): string | undefined {\n if (!node) return undefined;\n return typeof node.value === 'string' ? node.value : node.name;\n}\n\n/** Whether a destructuring pattern binds `name` anywhere inside it. */\nexport function patternBinds(node: unknown, name: string): boolean {\n if (!node || typeof node !== 'object') return false;\n const n = node as Record<string, unknown>;\n switch (n.type) {\n case 'Identifier':\n return n.name === name;\n case 'ObjectPattern':\n return ((n.properties as unknown[]) ?? []).some((prop) => {\n const p = prop as Record<string, unknown>;\n return patternBinds(p.type === 'RestElement' ? p.argument : p.value, name);\n });\n case 'ArrayPattern':\n return ((n.elements as unknown[]) ?? []).some((el) => patternBinds(el, name));\n case 'RestElement':\n return patternBinds(n.argument, name);\n case 'AssignmentPattern':\n return patternBinds(n.left, name);\n default:\n return false;\n }\n}\n\n/**\n * Check if a file starts with a specific directive (e.g. \"use client\").\n * Directives are string literal expression statements at the top of the file.\n */\nexport function fileHasDirective(filePath: string, directive: string): boolean {\n if (!existsSync(filePath)) return false;\n try {\n const source = readFileCached(filePath);\n const program = tryParse(source);\n if (!program) return false;\n for (const stmt of program.body) {\n if (stmt.type !== 'ExpressionStatement') break;\n const expr = (stmt as any).expression;\n if (expr?.type !== 'Literal' || typeof expr.value !== 'string') break;\n if (expr.value === directive) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/** Route files the AST checks can read; `.mdx` and `.json` are skipped. */\nexport function isScriptExtension(ext: string): boolean {\n return ext === 'tsx' || ext === 'ts' || ext === 'jsx' || ext === 'js';\n}\n","/**\n * Route discovery scanner.\n *\n * Pure function: (appDir, config) → RouteTree\n *\n * Scans the app/ directory and builds a segment tree recognizing all\n * timber.js file conventions. Does NOT handle request matching — this\n * is discovery only.\n */\n\nimport { readdirSync, statSync } from 'node:fs';\nimport { join, extname, basename } from 'node:path';\nimport type {\n RouteTree,\n SegmentNode,\n SegmentType,\n RouteFile,\n ScannerConfig,\n InterceptionMarker,\n} from './types.ts';\nimport { classifySegment, effectiveUrlSegment } from './segment-classify.ts';\nimport { validateInterceptionPlacement, computeInterceptedBase } from './interception.ts';\nimport { validateRouteGroupCollisions } from './collision-spaces.ts';\nimport { validateSlotPlacement } from './slot-placement.ts';\nimport { DEFAULT_PAGE_EXTENSIONS } from './types.ts';\nimport { classifyMetadataRoute, isDynamicMetadataExtension } from '../server/metadata-routes.ts';\nimport { swallow } from '../server/logger.ts';\nimport { getCsrfExport } from './export-detect.ts';\nimport { ENCODED_SEPARATOR_RE, NULL_BYTE_RE } from '../server/canonicalize.ts';\n\n/**\n * File convention names that use pageExtensions (can be .tsx, .ts, .jsx, .js, .mdx, etc.)\n * `error` is excluded — it only accepts script extensions (TIM-1505).\n */\nconst PAGE_EXT_CONVENTIONS = new Set(['page', 'layout', 'default', 'denied']);\n\n/**\n * File convention names that are always .ts/.tsx (never .mdx etc.)\n */\nconst FIXED_CONVENTIONS = new Set(['middleware', 'access', 'route']);\n\n/**\n * Status-code file patterns:\n * - Exact 3-digit codes: 401.tsx, 429.tsx, 503.tsx\n * - Category catch-alls: 4xx.tsx, 5xx.tsx\n */\nconst STATUS_CODE_PATTERN = /^(\\d{3}|[45]xx)$/;\n\n/**\n * Whether a basename + extension pair is a route-convention file the\n * framework itself imports: page/layout/default/denied on pageExtensions,\n * error/global-error and status-code files on script extensions only,\n * middleware/access/route/proxy on .ts/.tsx/.js/.jsx only, and\n * status-code .json files — mirroring this scanner's own recognition\n * rules per family.\n *\n * Exported for the analyze classifier so its provisional classification\n * (design/47 §2) derives from the scanner's real conventions instead of\n * a duplicate list that can drift.\n */\nexport function isRouteConventionFile(\n base: string,\n ext: string,\n pageExtensions: readonly string[] = DEFAULT_PAGE_EXTENSIONS\n): boolean {\n const isPageExt = pageExtensions.includes(ext);\n const isScriptExt = /^[jt]sx?$/.test(ext);\n if (PAGE_EXT_CONVENTIONS.has(base) && isPageExt) return true;\n if ((base === 'error' || base === 'global-error') && isScriptExt) return true;\n if ((FIXED_CONVENTIONS.has(base) || base === 'proxy') && isScriptExt) return true;\n if (STATUS_CODE_PATTERN.test(base) && (isScriptExt || ext === 'json')) return true;\n return false;\n}\n\n/**\n * Scan the app/ directory and build the route tree.\n *\n * @param appDir - Absolute path to the app/ directory\n * @param config - Scanner configuration\n * @returns The complete route tree\n */\nexport function scanRoutes(appDir: string, config: ScannerConfig = {}): RouteTree {\n const pageExtensions = config.pageExtensions ?? DEFAULT_PAGE_EXTENSIONS;\n const extSet = new Set(pageExtensions);\n\n const tree: RouteTree = {\n root: createSegmentNode('', 'static', '/'),\n };\n\n // Check for proxy.ts at app root\n const proxyFile = findFixedFile(appDir, 'proxy');\n if (proxyFile) {\n tree.proxy = proxyFile;\n }\n\n // Check for global-error.{tsx,ts,jsx,js} at app root.\n // Tier 2 error page — renders standalone (no layouts) when no segment-level\n // error file is found. Script extensions only — MDX not supported (TIM-1505).\n // See design/10-error-handling.md §\"Tier 2\".\n const globalErrorFile = findScriptExtFile(appDir, 'global-error');\n if (globalErrorFile) {\n tree.globalError = globalErrorFile;\n }\n\n // Scan the root directory's files\n scanSegmentFiles(appDir, tree.root, extSet);\n\n // Scan children recursively\n scanChildren(appDir, tree.root, extSet);\n\n // Validate: every parallel slot sits where a renderer reaches it. First,\n // because a slot nested inside another slot never renders, and a collision\n // reported from inside one would send the author to fix an ambiguity between\n // two pages that were both already dead.\n validateSlotPlacement(tree.root);\n\n // Validate: detect route group collisions (different groups producing pages at the same URL)\n validateRouteGroupCollisions(tree.root);\n\n // Validate: detect duplicate param names in nested dynamic segments\n // e.g., /[id]/items/[id] — same param name in ancestor and descendant\n validateDuplicateParamNames(tree.root);\n\n // Validate: detect same param name used with different bracket forms\n // e.g., [id] in one route and [...id] in another\n validateUniqueBracketForms(tree.root);\n\n // Validate: detect affixed dynamic siblings with equal specificity\n // e.g., a-[id] and [slug]-b both have prefix+suffix length = 2\n validateAffixedSiblingConflicts(tree.root);\n\n // Validate: intercepting routes must be direct children of a parallel slot —\n // the slot resolver is the only thing that can render one.\n validateInterceptionPlacement(tree.root);\n\n return tree;\n}\n\n/**\n * Create an empty segment node.\n */\nfunction createSegmentNode(\n segmentName: string,\n segmentType: SegmentType,\n urlPath: string,\n paramName?: string,\n interceptionMarker?: InterceptionMarker,\n interceptedSegmentName?: string,\n paramPrefix?: string,\n paramSuffix?: string\n): SegmentNode {\n return {\n segmentName,\n segmentType,\n urlPath,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n children: [],\n slots: {},\n };\n}\n\n/**\n * Compute the URL path for a child segment given its parent's URL path.\n * Route groups, slots, and intercepting routes do NOT add URL depth.\n */\nfunction computeUrlPath(parentUrlPath: string, dirName: string, segmentType: SegmentType): string {\n // Groups, slots, and intercepting routes don't add to URL path\n if (segmentType === 'group' || segmentType === 'slot' || segmentType === 'intercepting') {\n return parentUrlPath;\n }\n\n const parentPath = parentUrlPath === '/' ? '' : parentUrlPath;\n return `${parentPath}/${dirName}`;\n}\n\n/**\n * Scan a directory for file conventions and populate the segment node.\n */\nfunction scanSegmentFiles(dirPath: string, node: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanSegmentFiles: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n // Skip directories — handled by scanChildren\n try {\n if (statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n const ext = extname(entry).slice(1); // remove leading dot\n const name = basename(entry, `.${ext}`);\n\n // Page-extension conventions (page, layout, default, denied)\n if (PAGE_EXT_CONVENTIONS.has(name) && extSet.has(ext)) {\n const key = name as 'page' | 'layout' | 'default' | 'denied';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // error.tsx — script extensions only, not MDX/MD (TIM-1505).\n if (name === 'error' && /^[jt]sx?$/.test(ext)) {\n const existing = node.error;\n if (existing) {\n throwDuplicateConvention('error', existing.filePath, fullPath);\n }\n node.error = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Fixed conventions (middleware, access, route) — only\n // .ts/.tsx/.js/.jsx, never pageExtensions like .mdx. The regex is\n // anchored: mts/cts/mjs/cjs (and stray tail matches like `.foots`)\n // are NOT recognized. See design/07-routing.md §\"Page Extensions\".\n if (FIXED_CONVENTIONS.has(name) && /^[jt]sx?$/.test(ext)) {\n const key = name as 'middleware' | 'access' | 'route';\n const existing = node[key];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node[key] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // JSON status-code files (401.json, 4xx.json, 503.json, 5xx.json)\n // Recognized regardless of pageExtensions — .json is a data format, not a page extension.\n if (STATUS_CODE_PATTERN.test(name) && ext === 'json') {\n if (!node.jsonStatusFiles) {\n node.jsonStatusFiles = {};\n }\n node.jsonStatusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Status-code files (401.tsx, 4xx.tsx, 503.tsx, 5xx.tsx) — script extensions only (TIM-1505)\n if (STATUS_CODE_PATTERN.test(name) && /^[jt]sx?$/.test(ext)) {\n if (!node.statusFiles) {\n node.statusFiles = {};\n }\n const existing = node.statusFiles[name];\n if (existing) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n node.statusFiles[name] = { filePath: fullPath, extension: ext };\n continue;\n }\n\n // Metadata route files (sitemap.ts, robots.ts, icon.tsx, opengraph-image.tsx, etc.)\n // Both static (.xml, .txt, .png, .ico, etc.) and dynamic (.ts, .tsx) files are recognized.\n // When both exist for the same base name, dynamic takes precedence.\n // Two files of the SAME kind (static+static or dynamic+dynamic) are a\n // build error — picking one by readdir order is platform-dependent.\n // See design/16-metadata.md §\"Metadata Routes\"\n const metaInfo = classifyMetadataRoute(entry);\n if (metaInfo) {\n if (!metaInfo.nestable && node.segmentName !== '') {\n throw new Error(\n `Build error: '${name}' is a root-only metadata convention and must be in the app root directory.\\n` +\n ` File: ${fullPath}\\n` +\n ` Move this file to the app root (not a route group or nested segment).`\n );\n }\n if (!node.metadataRoutes) {\n node.metadataRoutes = {};\n }\n const existing = node.metadataRoutes[name];\n if (existing) {\n const existingIsDynamic = isDynamicMetadataExtension(name, existing.extension);\n const newIsDynamic = isDynamicMetadataExtension(name, ext);\n if (existingIsDynamic === newIsDynamic) {\n throwDuplicateConvention(name, existing.filePath, fullPath);\n }\n // Dynamic > static precedence: overwrite only when the new file is dynamic.\n if (newIsDynamic) {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n } else {\n node.metadataRoutes[name] = { filePath: fullPath, extension: ext };\n }\n }\n }\n\n // Validate: route.ts + page.* is a hard build error\n if (node.route && node.page) {\n throw new Error(\n `Build error: route.ts and page.* cannot coexist in the same segment.\\n` +\n ` route.ts: ${node.route.filePath}\\n` +\n ` page: ${node.page.filePath}\\n` +\n `A URL is either an API endpoint or a rendered page, not both.`\n );\n }\n\n // The per-route CSRF exemption is read from source here, at scan time, so\n // the manifest carries it and the request gate never loads user code to\n // decide it. Any other spelling of the export is a lint error\n // (convention-lint.ts `checkCsrfExports`).\n if (node.route && getCsrfExport(node.route.filePath) === 'exempt') {\n node.csrfExempt = true;\n }\n}\n\n/**\n * Throw a build error for two files claiming the same convention slot in\n * one segment (e.g. page.tsx + page.jsx). Which file readdir returns first\n * is platform-dependent (APFS sorts entries, ext4 does not) — silently\n * picking one would let macOS dev and Linux CI serve different\n * implementations of the same route.\n */\nfunction throwDuplicateConvention(\n convention: string,\n firstPath: string,\n secondPath: string\n): never {\n throw new Error(\n `Build error: duplicate '${convention}' files in the same route segment.\\n` +\n ` File 1: ${firstPath}\\n` +\n ` File 2: ${secondPath}\\n` +\n `Each segment may define '${convention}' at most once. Remove one of the files.`\n );\n}\n\n/**\n * Recursively scan child directories and build the segment tree.\n */\nfunction scanChildren(dirPath: string, parentNode: SegmentNode, extSet: Set<string>): void {\n let entries: string[];\n try {\n entries = readdirSync(dirPath);\n } catch (err) {\n swallow(err, `scanChildren: unreadable directory ${dirPath}`, { level: 'warn' });\n return;\n }\n\n for (const entry of entries) {\n const fullPath = join(dirPath, entry);\n\n try {\n if (!statSync(fullPath).isDirectory()) continue;\n } catch {\n continue;\n }\n\n // Reject directories with encoded path delimiters or null bytes.\n // These can cause route collisions when decoded at the URL boundary.\n // See design/13-security.md §\"Encoded separators rejected\" and §\"Null bytes rejected\".\n if (ENCODED_SEPARATOR_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded path delimiter (%2F or %5C).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded separators in directory names cause route collisions when decoded. ` +\n `Rename the directory to remove the encoded delimiter.`\n );\n }\n // `@children` is the implicit slot a layout's `children` prop fills, and\n // the key of the outlet that carries it (`childrenOutletKey`). A slot\n // directory by that name would claim the same outlet and be rendered in\n // place of the children.\n if (entry === '@children') {\n throw new Error(\n `Build error: \"@children\" is reserved and cannot be a slot directory.\\n` +\n ` Directory: ${fullPath}\\n` +\n `A layout's children fill the implicit children slot. Put this content in the ` +\n `parent segment's page, or give the slot another name.`\n );\n }\n if (NULL_BYTE_RE.test(entry)) {\n throw new Error(\n `Build error: directory name contains an encoded null byte (%00).\\n` +\n ` Directory: ${fullPath}\\n` +\n `Encoded null bytes in directory names are not allowed. ` +\n `Rename the directory to remove the null byte encoding.`\n );\n }\n\n const {\n type,\n paramName,\n paramPrefix,\n paramSuffix,\n interceptionMarker,\n interceptedSegmentName,\n } = classifySegment(entry);\n\n // Skip private folders — underscore-prefixed dirs are excluded from routing\n if (type === 'private') continue;\n\n const urlPath = computeUrlPath(parentNode.urlPath, entry, type);\n const childNode = createSegmentNode(\n entry,\n type,\n urlPath,\n paramName,\n interceptionMarker,\n interceptedSegmentName,\n paramPrefix,\n paramSuffix\n );\n\n // Scan this segment's files\n scanSegmentFiles(fullPath, childNode, extSet);\n\n // Recurse into subdirectories\n scanChildren(fullPath, childNode, extSet);\n\n // Attach to parent: slots go into slots record, everything else is a child\n if (type === 'slot') {\n const slotName = entry.slice(1); // remove @\n parentNode.slots[slotName] = childNode;\n } else {\n parentNode.children.push(childNode);\n }\n }\n}\n\n/**\n * Validate that no route chain contains duplicate dynamic param names.\n *\n * Example violation:\n * app/[id]/items/[id]/page.tsx — 'id' appears twice in the ancestor chain.\n *\n * Route groups are transparent — params accumulate through them.\n * Slots are independent — duplicate detection does NOT cross slot boundaries.\n *\n * See design/07-routing.md §\"Duplicate Param Name Detection\"\n */\nfunction validateDuplicateParamNames(root: SegmentNode): void {\n walkForDuplicateParams(root, new Map());\n}\n\n/**\n * Recursively walk the segment tree, tracking seen param names → segment paths.\n * Throws on the first duplicate found.\n */\nfunction walkForDuplicateParams(node: SegmentNode, seen: Map<string, string>): void {\n // Read through the effective identity so an intercepting directory is seen\n // as the segment it intercepts: the scanner leaves `paramName` unset on\n // `(.)[id]`, so a validator reading the node directly is blind to a param\n // the resolver goes on to bind — `@modal/(.)[id]/[id]` would pass here and\n // then silently overwrite the outer `id` at match time, where the ordinary\n // `/[id]/[id]` is rejected. See TIM-1288.\n const { paramName } = effectiveUrlSegment(node);\n\n // If this node introduces a param name, check for duplicates\n if (paramName) {\n const existing = seen.get(paramName);\n if (existing) {\n throw new Error(\n `[timber] Duplicate param name '${paramName}' in route chain.\\n` +\n ` First defined at: ${existing}\\n` +\n ` Duplicate at: ${node.urlPath || '/'}\\n` +\n ` Rename one of the segments to avoid ambiguity.`\n );\n }\n // Add to seen for descendants (use a new Map to avoid polluting siblings)\n seen = new Map(seen);\n seen.set(paramName, node.urlPath || '/');\n }\n\n // Recurse into children (they inherit the accumulated params)\n for (const child of node.children) {\n walkForDuplicateParams(child, seen);\n }\n\n // A slot INHERITS the ancestor params rather than starting fresh: a slot\n // child may not reuse a name its owner already bound\n // (`app/gallery/[id]/@modal/[id]` is rejected). The copy is so sibling\n // slots don't see each other's names, not so the chain is reset.\n //\n // Whether that rule is right is a separate question — slot params are\n // merged over the main route's at read time, so a collision is defined\n // rather than ambiguous — but changing it would change every slot.\n // Tracked as TIM-1287; do not \"fix\" this by making the map fresh without\n // deciding that.\n for (const slotNode of Object.values(node.slots)) {\n walkForDuplicateParams(slotNode, new Map(seen));\n }\n}\n\n/**\n * Validate that each param name uses a single bracket form across the entire route tree.\n *\n * Different bracket forms produce different types:\n * [id] → string\n * [...id] → string[]\n * [[...id]] → string[] | undefined\n *\n * If the same param name appears with multiple forms, the no-argument\n * getSegmentParams() / useSegmentParams() return type becomes ambiguous.\n *\n * Same name + same form across different routes is fine and expected.\n */\nfunction validateUniqueBracketForms(root: SegmentNode): void {\n const forms = new Map<string, { segmentType: SegmentType; urlPath: string }>();\n collectBracketForms(root, forms);\n}\n\nfunction collectBracketForms(\n node: SegmentNode,\n forms: Map<string, { segmentType: SegmentType; urlPath: string }>\n): void {\n // Effective identity, so `(.)[...rest]` is compared as the catch-all it\n // intercepts rather than skipped as an 'intercepting' node (TIM-1288).\n const { paramName, segmentType } = effectiveUrlSegment(node);\n\n if (paramName && segmentType !== 'static' && segmentType !== 'group') {\n const existing = forms.get(paramName);\n if (existing && existing.segmentType !== segmentType) {\n const bracketExamples: Record<string, string> = {\n 'dynamic': `[${paramName}]`,\n 'catch-all': `[...${paramName}]`,\n 'optional-catch-all': `[[...${paramName}]]`,\n };\n throw new Error(\n `[timber] Param name '${paramName}' uses multiple bracket forms.\\n` +\n ` ${bracketExamples[existing.segmentType] ?? existing.segmentType} at: ${existing.urlPath}\\n` +\n ` ${bracketExamples[segmentType] ?? segmentType} at: ${node.urlPath || '/'}\\n` +\n ` Each param name must use a single bracket form across all routes.\\n` +\n ` Rename one of the segments to fix this (e.g., [${paramName}] → [${paramName}Id]).`\n );\n }\n if (!existing) {\n forms.set(paramName, {\n segmentType,\n urlPath: node.urlPath || '/',\n });\n }\n }\n\n for (const child of node.children) {\n collectBracketForms(child, forms);\n }\n for (const slotNode of Object.values(node.slots)) {\n collectBracketForms(slotNode, forms);\n }\n}\n\n/**\n * Validate that no sibling affixed dynamic segments have equal specificity.\n *\n * Among affixed siblings, longer combined prefix+suffix length wins. When two\n * siblings tie (same total affix length), the router would fall back to\n * filesystem scan order — which is platform-dependent. This is a build error.\n *\n * Route groups are URL-transparent, so affixed segments inside different groups\n * at the same level still conflict with each other.\n *\n * Ambiguity requires the two segments to be candidates for the *same* URL\n * part, which is narrower than \"same parent\" once interception is involved:\n *\n * - Plain children and intercepting children never compete. They are resolved\n * by different walks — `findSlotMatch` matches the slot subtree (where\n * `tree-match.ts` ignores intercepting nodes outright) and\n * `findInterceptingMatch` builds a synthetic parent holding only\n * interceptors.\n * - Two interceptors compete only at the same anchor. `(.)a-[id]` and\n * `(..)[slug]-b` in one slot are based at different URL depths, so no\n * pathname reaches both, and `anchorIndex` rejects the one whose base does\n * not match the target. Grouping them together would fail the build for a\n * pair that can never be ambiguous.\n *\n * So candidates are keyed by the position they contend for, then by affix\n * length. See design/07-routing.md §\"Priority\" and §\"Intercepting Routes\".\n */\nfunction validateAffixedSiblingConflicts(node: SegmentNode): void {\n const affixed = collectEffectiveAffixed(node);\n\n if (affixed.length >= 2) {\n const byLength = new Map<string, SegmentNode[]>();\n for (const child of affixed) {\n // `\\0` as the separator, written as the escape rather than a literal\n // byte: a raw NUL in the source makes git and grep treat this file as\n // binary. A contention key is a URL path, which cannot contain one, so\n // the two halves of the key can never run together.\n const key = `${contentionKey(node, child)}\\0${affixLengthOf(child)}`;\n const group = byLength.get(key);\n if (group) {\n group.push(child);\n } else {\n byLength.set(key, [child]);\n }\n }\n\n for (const [, group] of byLength) {\n if (group.length >= 2) {\n throw new Error(\n `Build error: ambiguous affixed dynamic siblings with equal specificity.\\n` +\n ` Parent: ${node.urlPath || '/'}\\n` +\n ` Segments: ${group.map((s) => s.segmentName).join(', ')}\\n` +\n ` Combined prefix+suffix length: ${affixLengthOf(group[0]!)}\\n` +\n `The router cannot deterministically choose between these — filesystem scan order is platform-dependent.\\n` +\n `Rename one segment to give it a longer or shorter combined affix.`\n );\n }\n }\n }\n\n for (const child of node.children) {\n validateAffixedSiblingConflicts(child);\n }\n for (const slotNode of Object.values(node.slots)) {\n validateAffixedSiblingConflicts(slotNode);\n }\n}\n\n/**\n * The URL position a child contends for, as a comparable key.\n *\n * Plain children contend for the parent's next part. An intercepting child\n * contends for a part determined by its marker's intercepted base, so two\n * markers of different depth are simply different positions — and two markers\n * that compute the *same* base do contend, which is why the key is the base\n * rather than the marker (`(..)` and `(...)` under `/feed` both base at `/`).\n *\n * `groupByInterceptedAnchor` (`routing/interception.ts`) is the canonical\n * statement of that grouping — it is what the resolver walks and what the\n * collision validator checks. This computes the same key from the same\n * `computeInterceptedBase` rather than calling it, because affix ambiguity is\n * decided per *child* and `collectEffectiveAffixed` looks through route groups,\n * so the two do not partition the same set of nodes.\n */\nfunction contentionKey(parent: SegmentNode, child: SegmentNode): string {\n if (child.segmentType !== 'intercepting') return 'child';\n return `intercept:${computeInterceptedBase(parent.urlPath, child.interceptionMarker ?? '(.)')}`;\n}\n\n/** Combined affix length of a node, read through its effective identity. */\nfunction affixLengthOf(node: SegmentNode): number {\n const { paramPrefix, paramSuffix } = effectiveUrlSegment(node);\n return (paramPrefix?.length ?? 0) + (paramSuffix?.length ?? 0);\n}\n\n/**\n * Collect affixed dynamic segments that are effective children of a node.\n * Route groups are URL-transparent, so we look through them recursively.\n *\n * Segments are read through `effectiveUrlSegment`, so an intercepting\n * directory counts as the affixed segment it intercepts: `(.)a-[id]` is\n * `a-[id]`. The proxy the slot resolver builds hands those affixes to\n * `matchUrlParts`, whose equal-length sort is not stable across equal\n * specificity — so two intercepting siblings with the same combined affix\n * length would resolve by filesystem enumeration order, which is precisely\n * what this validator exists to prevent for ordinary siblings (TIM-1288).\n */\nfunction collectEffectiveAffixed(node: SegmentNode): SegmentNode[] {\n const result: SegmentNode[] = [];\n for (const child of node.children) {\n const { segmentType, paramPrefix, paramSuffix } = effectiveUrlSegment(child);\n if (segmentType === 'dynamic' && (paramPrefix || paramSuffix)) {\n result.push(child);\n } else if (segmentType === 'group') {\n result.push(...collectEffectiveAffixed(child));\n }\n }\n return result;\n}\n\n/**\n * Find a fixed-extension file (proxy.ts) in a directory.\n */\nfunction findFixedFile(dirPath: string, name: string): RouteFile | undefined {\n for (const ext of ['ts', 'tsx']) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n\n/**\n * Find a file with script extensions (tsx, ts, jsx, js) in a directory.\n * Used for app-root conventions like global-error that only accept script\n * extensions (TIM-1505).\n */\nfunction findScriptExtFile(dirPath: string, name: string): RouteFile | undefined {\n for (const ext of ['tsx', 'ts', 'jsx', 'js']) {\n const fullPath = join(dirPath, `${name}.${ext}`);\n try {\n if (statSync(fullPath).isFile()) {\n return { filePath: fullPath, extension: ext };\n }\n } catch {\n // File doesn't exist\n }\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,6BAA6B,MAAyB;CACpE,uBAAuB,MAAM,IAAI,KAAK,OAAO;AAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAS,uBAAuB,WAAwB,aAAqB,MAAoB;CAC/F,MAAM,SAAsB,CAAC;CAC7B,sBAAsB,2BAAW,IAAI,IAAI,GAAG,aAAa,CAAC,GAAG,QAAQ,IAAI;CAEzE,MAAM,YAAY,4BAA4B,WAAW,QAAQ,IAAI;CACrE,IAAI,CAAC,WAAW;CAEhB,MAAM,IAAI,MACR,mFACe,UAAU,IAAI,cACd,UAAU,MAAM,cAChB,UAAU,OAAO,mUAMlC;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAS,sBACP,MACA,MACA,aACA,OACA,QACA,MACM;CAUN,MAAM,cAAc,cAChB,GAAG,YAAY,GAAG,KAAK,gBACvB,KAAK,eAAe;CAKxB,IAAI,KAAK,gBAAgB,gBAAgB;E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