@timber-js/app 0.2.0-alpha.241 → 0.2.0-alpha.243
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-DoTj0Jd3.js} +78 -32
- package/dist/_chunks/actions-DoTj0Jd3.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-D3HmgsFh.js} +5 -5
- package/dist/_chunks/{cache-api-n5FL4wFs.js.map → cache-api-D3HmgsFh.js.map} +1 -1
- package/dist/_chunks/{chains-IswOWMnq.js → chains-BpvDwp08.js} +2 -2
- package/dist/_chunks/{chains-IswOWMnq.js.map → chains-BpvDwp08.js.map} +1 -1
- package/dist/_chunks/chains-CjlZZ5ad.js +1 -0
- package/dist/_chunks/{classify-B08RCF6s.js → classify-Bbb_lKjH.js} +2 -2
- package/dist/_chunks/{classify-B08RCF6s.js.map → classify-Bbb_lKjH.js.map} +1 -1
- package/dist/_chunks/{cli-check-tpFb6pBU.js → cli-check-DlQBSKIN.js} +3 -3
- package/dist/_chunks/{cli-check-tpFb6pBU.js.map → cli-check-DlQBSKIN.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-DRNJutey.js → cli-schema-sync-CWkGFlYu.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-DRNJutey.js.map → cli-schema-sync-CWkGFlYu.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-C0pXBtzG.js → cli-schema-sync-Dyvdkv_I.js} +1 -1
- package/dist/_chunks/{client-dep-entries-Dw5Dvatr.js → client-dep-entries-Dka67elj.js} +2 -2
- package/dist/_chunks/{client-dep-entries-Dw5Dvatr.js.map → client-dep-entries-Dka67elj.js.map} +1 -1
- package/dist/_chunks/{convention-lint-BfC_dAhZ.js → convention-lint-CGGcseNn.js} +19 -5
- package/dist/_chunks/convention-lint-CGGcseNn.js.map +1 -0
- package/dist/_chunks/dev-server-DrjLscqT.js +1 -0
- package/dist/_chunks/{dev-server-3R6Bl9_R.js → dev-server-LO4McfQi.js} +3 -4
- package/dist/_chunks/dev-server-LO4McfQi.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-BeF00Wo_.js} +4 -7
- package/dist/_chunks/flight-source-node-BeF00Wo_.js.map +1 -0
- package/dist/_chunks/{interception-CtNt9jPt.js → interception-D1dCGNmQ.js} +6 -6
- package/dist/_chunks/{interception-CtNt9jPt.js.map → interception-D1dCGNmQ.js.map} +1 -1
- package/dist/_chunks/{json-lossy-check-5KFcC1yt.js → json-lossy-check-DpXneTBm.js} +2 -2
- package/dist/_chunks/{json-lossy-check-5KFcC1yt.js.map → json-lossy-check-DpXneTBm.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-DXhz6A_X.js} +4 -4
- package/dist/_chunks/{live-graph-D1dfVqoT.js.map → live-graph-DXhz6A_X.js.map} +1 -1
- package/dist/_chunks/{logger-BvGxPd1e.js → logger-D1sWX2I0.js} +18 -3
- package/dist/_chunks/logger-D1sWX2I0.js.map +1 -0
- package/dist/_chunks/metadata-routes-MXNjWOt5.js.map +1 -1
- package/dist/_chunks/{node-response-D5cfiyWP.js → node-response-Cp62CtH1.js} +2 -2
- package/dist/_chunks/{node-response-D5cfiyWP.js.map → node-response-Cp62CtH1.js.map} +1 -1
- package/dist/_chunks/{poison-scan-CX02ilxN.js → poison-scan-DdkJoHvP.js} +2 -2
- package/dist/_chunks/{poison-scan-CX02ilxN.js.map → poison-scan-DdkJoHvP.js.map} +1 -1
- package/dist/_chunks/{scanner-DneYxQoY.js → scanner-B6V2RqqF.js} +20 -3
- package/dist/_chunks/scanner-B6V2RqqF.js.map +1 -0
- package/dist/_chunks/{sizeof-BtQ3ErLf.js → sizeof-BKA6qOZq.js} +2 -2
- package/dist/_chunks/{sizeof-BtQ3ErLf.js.map → sizeof-BKA6qOZq.js.map} +1 -1
- package/dist/_chunks/{walkers-C9R2A4jN.js → walkers-BAZoAlfI.js} +3 -3
- package/dist/_chunks/{walkers-C9R2A4jN.js.map → walkers-BAZoAlfI.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/document-withdrawal.d.ts +2 -0
- package/dist/client/document-withdrawal.d.ts.map +1 -0
- 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 +28 -42
- package/dist/client/outlet-content-cache.d.ts.map +1 -1
- package/dist/client/outlet-scope-context.d.ts +9 -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 +2 -18
- 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 +3 -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/cookie-context.js +7 -7
- package/dist/native/rsc/server/cookie-context.js.map +1 -1
- package/dist/native/rsc/server/deny-boundary.js +2 -1
- package/dist/native/rsc/server/deny-boundary.js.map +1 -1
- package/dist/native/rsc/server/dev-overlay-report.js +13 -0
- package/dist/native/rsc/server/dev-overlay-report.js.map +1 -0
- 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/logger.js +6 -1
- package/dist/native/rsc/server/logger.js.map +1 -1
- package/dist/native/rsc/server/pipeline-interception.js +4 -1
- package/dist/native/rsc/server/pipeline-interception.js.map +1 -1
- package/dist/native/rsc/server/pipeline.js.map +1 -1
- package/dist/native/rsc/server/request-context.js +6 -6
- 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 +45 -12
- package/dist/native/rsc/server/segment-lifetime/read-rule.js.map +1 -1
- package/dist/native/rsc/server/segment-lifetime/read-scope.js +50 -8
- 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 +8 -7
- package/dist/native/rsc/server/slot-resolver.js.map +1 -1
- package/dist/native/rsc/server/slot-subtree-contain.js +2 -1
- package/dist/native/rsc/server/slot-subtree-contain.js.map +1 -1
- package/dist/native/rsc/server/subtree-walk.js +14 -5
- package/dist/native/rsc/server/subtree-walk.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/document-withdrawal.js +17 -0
- package/dist/native/ssr/client/document-withdrawal.js.map +1 -0
- package/dist/native/ssr/client/outlet-content-cache.js +10 -25
- 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 +17 -21
- package/dist/native/ssr/client/segment-outlet.js.map +1 -1
- package/dist/native/ssr/manifest.json +6 -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/cookie-context.js +7 -7
- package/dist/native/ssr/server/cookie-context.js.map +1 -1
- package/dist/native/ssr/server/deny-boundary.js +2 -1
- package/dist/native/ssr/server/deny-boundary.js.map +1 -1
- package/dist/native/ssr/server/dev-overlay-report.js +6 -0
- package/dist/native/ssr/server/dev-overlay-report.js.map +1 -0
- 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/logger.js +6 -1
- package/dist/native/ssr/server/logger.js.map +1 -1
- package/dist/native/ssr/server/pipeline-interception.js +4 -1
- package/dist/native/ssr/server/pipeline-interception.js.map +1 -1
- package/dist/native/ssr/server/pipeline.js.map +1 -1
- package/dist/native/ssr/server/request-context.js +6 -6
- package/dist/native/ssr/server/request-context.js.map +1 -1
- package/dist/native/ssr/server/segment-lifetime/outlet-gate.js +11 -0
- package/dist/native/ssr/server/segment-lifetime/outlet-gate.js.map +1 -0
- package/dist/native/ssr/server/segment-lifetime/read-rule.js +45 -12
- package/dist/native/ssr/server/segment-lifetime/read-rule.js.map +1 -1
- package/dist/native/ssr/server/segment-lifetime/read-scope.js +16 -0
- package/dist/native/ssr/server/segment-lifetime/read-scope.js.map +1 -0
- package/dist/native/ssr/server/subtree-walk.js +149 -0
- package/dist/native/ssr/server/subtree-walk.js.map +1 -0
- package/dist/native/ssr/server/utils/element-type.js +21 -9
- package/dist/native/ssr/server/utils/element-type.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 +3 -3
- 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/routing/slot-placement.d.ts +23 -4
- package/dist/routing/slot-placement.d.ts.map +1 -1
- package/dist/server/als-registry.d.ts +20 -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/deny-boundary.d.ts.map +1 -1
- package/dist/server/dev-overlay-report.d.ts +13 -0
- package/dist/server/dev-overlay-report.d.ts.map +1 -0
- 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 +105 -26
- package/dist/server/internal.js.map +1 -1
- package/dist/server/logger.d.ts +10 -0
- package/dist/server/logger.d.ts.map +1 -1
- package/dist/server/pipeline-interception.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts +13 -1
- package/dist/server/pipeline.d.ts.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 +19 -13
- package/dist/server/segment-lifetime/read-rule.d.ts.map +1 -1
- package/dist/server/segment-lifetime/read-scope.d.ts +48 -6
- 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 +3 -3
- 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/slot-subtree-contain.d.ts.map +1 -1
- package/dist/server/subtree-walk.d.ts +17 -3
- package/dist/server/subtree-walk.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 +3 -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/docs/api/34-api-config.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/document-withdrawal.tsx +41 -0
- package/src/client/error-boundary.tsx +1 -1
- package/src/client/navigation-commit.ts +4 -18
- package/src/client/outlet-content-cache.ts +38 -60
- package/src/client/outlet-scope-context.ts +10 -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 +28 -54
- package/src/client/stale-segment.ts +2 -2
- package/src/config-types.ts +2 -18
- package/src/config-validation.ts +0 -1
- package/src/plugins/entries.ts +0 -1
- package/src/routing/interception.ts +5 -5
- 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/routing/slot-placement.ts +41 -4
- package/src/rsc-runtime/vendor-types.d.ts +1 -1
- package/src/server/als-registry.ts +16 -23
- package/src/server/client-state-tree.ts +7 -18
- package/src/server/cookie-context.ts +7 -7
- package/src/server/deny-boundary.ts +4 -1
- package/src/server/dev-overlay-report.ts +22 -0
- 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/logger.ts +13 -0
- package/src/server/pipeline-interception.ts +11 -2
- package/src/server/pipeline.ts +13 -1
- package/src/server/request-context.ts +12 -11
- package/src/server/route-element-builder.ts +15 -16
- package/src/server/rsc-entry/helpers.ts +1 -1
- package/src/server/rsc-entry/index.ts +7 -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 +110 -22
- package/src/server/segment-lifetime/read-scope.ts +131 -15
- package/src/server/segment-lifetime/segment-key.ts +31 -3
- package/src/server/segment-lifetime/slot-outlets.ts +6 -6
- package/src/server/slot-resolver.ts +30 -18
- package/src/server/slot-subtree-contain.ts +2 -1
- package/src/server/subtree-walk.ts +34 -9
- package/src/server/types.ts +8 -2
- package/src/server/vite-handoff-rsc.ts +3 -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/_chunks/logger-BvGxPd1e.js.map +0 -1
- package/dist/_chunks/scanner-DneYxQoY.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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"actions-BCYVyoFl.js","names":["upstreamParseSetCookie","_getWaitUntil"],"sources":["../../src/server/react-cache-scope.ts","../../src/server/segment-lifetime/read-rule.ts","../../src/server/request-context.ts","../../src/server/cookie-parsing.ts","../../src/server/cookie-context.ts","../../src/server/primitives.ts","../../src/server/form-data.ts","../../src/server/actions.ts"],"sourcesContent":["/**\n * React.cache scopes — opening, resuming, and leaving the per-request\n * `React.cache` scope that `react-cache-bridge.ts` makes Flight read.\n *\n * Kept apart from the bridge so request-context and cookie code can use\n * it without importing `react`. See design/spike-TIM-1529-react-cache-bridge.md.\n */\n\nimport { reactCacheScopeAls, type ReactCacheScope } from './als-registry.ts';\nimport { isDevMode } from './debug.ts';\n\nexport type { ReactCacheScope };\n\n/** A new, empty `React.cache` scope. */\nexport function createReactCacheScope(): ReactCacheScope {\n return new Map();\n}\n\n/**\n * Run `fn` in a `React.cache` scope — a fresh one unless `scope` is given.\n * Every `React.cache` call made from `fn` — synchronously, in its async\n * continuations, and in any Flight render it starts — shares one memo table.\n *\n * Opened by `runWithRequestContext`, so each request context gets its own\n * scope. Pass `scope` to resume one across two ALS runs: the post-action\n * revalidation opens a fresh scope for the target route's middleware and\n * renders the revalidated tree in that same scope later.\n */\nexport function runWithReactCacheScope<T>(\n fn: () => T,\n scope: ReactCacheScope = createReactCacheScope()\n): T {\n return reactCacheScopeAls.run(scope, fn);\n}\n\n/**\n * Run `fn` with no timber scope, so `React.cache` behaves as stock React:\n * no dedupe outside a render, Flight's own per-render cache inside one.\n *\n * Used for server action bodies — an action reads, writes cookies, and\n * mutates, so memoized reads would go stale mid-action (the same choice\n * Next.js makes) — and for renders whose output outlives the request\n * (`cache.component` capture), which must not bake request-memoized values\n * into a cross-request cache entry.\n */\nexport function runOutsideReactCacheScope<T>(fn: () => T): T {\n return reactCacheScopeAls.exit(fn);\n}\n\n// ─── Dev diagnostic: cookie written after a cached read ──────────────────\n//\n// A value React.cache stored was computed from the request inputs it read,\n// and does not see a later write — a cached getUser() that read the session\n// cookie still returns the old user after middleware deletes the cookie.\n// The scope is deliberately NOT cleared on a write: that would silently\n// discard every value middleware warmed (spike doc §Decisions D3). Instead,\n// dev mode flags the one case that can go stale: a cookie read while the\n// scope held values, then written later in the same request. Tracking is\n// per scope, so it ends with the request; production does none of it.\n\n/** Stands for \"every cookie\" — a getAll()/size read, or a clear() write. */\nexport const ANY_COOKIE = '*';\n\nconst cookieReads = new WeakMap<ReactCacheScope, Set<string>>();\nconst warnedScopes = new WeakSet<ReactCacheScope>();\n\n/**\n * Dev-only: record that cookie `name` (or {@link ANY_COOKIE}) was read\n * while `React.cache` held values in this request — the read may have\n * happened inside a cached function.\n */\nexport function noteCookieReadForReactCache(name: string): void {\n if (!isDevMode()) return;\n const scope = reactCacheScopeAls.getStore();\n if (!scope || scope.size === 0) return;\n let reads = cookieReads.get(scope);\n if (!reads) {\n reads = new Set();\n cookieReads.set(scope, reads);\n }\n reads.add(name);\n}\n\n/**\n * Dev-only: warn (once per request) when a cookie recorded by\n * {@link noteCookieReadForReactCache} is written. `name` is the written\n * cookie, or {@link ANY_COOKIE} for `clear()`. Dev-only because reads are\n * only recorded in dev.\n */\nexport function warnIfCachedCookieIsWritten(name: string): void {\n const scope = reactCacheScopeAls.getStore();\n if (!scope || warnedScopes.has(scope)) return;\n const reads = cookieReads.get(scope);\n if (!reads) return;\n const stale = name === ANY_COOKIE ? reads.size > 0 : reads.has(name) || reads.has(ANY_COOKIE);\n if (!stale) return;\n warnedScopes.add(scope);\n const which = name === ANY_COOKIE ? 'Cookies were cleared' : `Cookie \"${name}\" was written`;\n console.warn(\n `[timber] ${which} after being read while React.cache held values for this request. ` +\n `A cached function that read it keeps returning the old result — pass the cookie ` +\n `value in as an argument (e.g. getUser(sessionToken)) so a change is a new cache key.`\n );\n}\n","/**\n * The checks every request-input accessor runs inside a `'document'`\n * segment's read scope (`read-scope.ts`, design/53-segment-lifetime.md §\"What\n * a 'document' segment may read\"). No React and no render machinery: the\n * accessors in `request-context.ts` and `cookie-context.ts` import this.\n */\n\nimport { documentReadScopeAls, type DocumentReadScope } from '../als-registry.ts';\nimport type { CoercedParams } from '../../shared/param-value.ts';\nimport type { SearchParamsReader } from '../../shared/als-slots.ts';\n\n/** The read scope the current render runs in, if it is a `'document'` segment's. */\nexport function currentReadScope(): DocumentReadScope | undefined {\n return documentReadScopeAls.getStore();\n}\n\n/** Which part of a key would allow a read, for the error's fix. */\ntype KeyPart = 'segmentParams' | 'searchParams' | 'cookies';\n\n/**\n * The error for a read outside the key. Names the segment, what was read, and\n * the fix: add it to the key, or make the segment `'request'`.\n */\nexport function readOutsideKey(scope: DocumentReadScope, what: string, part?: KeyPart): Error {\n const fix = part\n ? `Add it to key.${part}, or declare lifetime: 'request'.`\n : \"A 'document' segment cannot depend on it; declare lifetime: 'request'.\";\n return new Error(\n `[timber] ${scope.segmentPath} is lifetime: 'document' (declared, or from defaultLayoutLifetime) ` +\n `and read ${what}, which is not in its key. ` +\n `${fix} The segment is skipped without rendering while its key is unchanged, so the read ` +\n `would freeze at its first value. See design/53-segment-lifetime.md ` +\n `§\"What a 'document' segment may read\".`\n );\n}\n\n/** Throw if the current render may not read `what` at all (headers, raw search params). */\nexport function assertUnscopedRead(what: string): void {\n const scope = currentReadScope();\n if (scope) throw readOutsideKey(scope, what);\n}\n\n/**\n * Throw if the current render reads search-param fields outside its key. A\n * field is in the key only when the key's definition reads it through the\n * same codec and URL key — a `.pick()` of the keyed definition, or the keyed\n * definition itself. Another definition with a field of the same name may map\n * it to another URL parameter or parse it differently.\n */\nexport function assertSearchParamsRead(reader: SearchParamsReader): void {\n const scope = currentReadScope();\n if (!scope) return;\n const outside = Object.keys(reader.codecs).filter((field) => {\n const keyed = scope.searchParams.get(field);\n return (\n !keyed ||\n keyed.codec !== reader.codecs[field] ||\n keyed.urlKey !== (reader.urlKeys[field] ?? field)\n );\n });\n if (outside.length > 0) {\n throw readOutsideKey(scope, `the search params ${outside.join(', ')}`, 'searchParams');\n }\n}\n\n/**\n * Throw if the current render reads a cookie outside its key. A keyed cookie\n * is in the key only as its definition parses it, so it may be read only\n * through that definition (`codec` is the reader's); a raw read, or another\n * definition of the same name, could see a difference the key does not.\n */\nexport function assertCookieRead(name: string, codec?: unknown): void {\n const scope = currentReadScope();\n if (!scope) return;\n if (!scope.cookies.has(name)) {\n throw readOutsideKey(scope, `the cookie \"${name}\"`, 'cookies');\n }\n if (codec === undefined || scope.cookies.get(name) !== codec) {\n throw readOutsideKey(\n scope,\n `the raw value of the cookie \"${name}\" (read it through the definition in its key)`,\n 'cookies'\n );\n }\n}\n\n/**\n * Property names that serializers and runtimes read on any object — Flight\n * and `await` probe `then`, React `$$typeof`, JSON `toJSON`. No param can\n * be named these in a way a reader means: they are never refused.\n */\nconst OBJECT_PROBES: ReadonlySet<string> = new Set([\n 'then',\n 'toJSON',\n '$$typeof',\n 'constructor',\n 'valueOf',\n 'toString',\n '__proto__',\n]);\n\n/**\n * The params a scoped render sees: reading one outside the key throws. Its\n * own keys are only the params in the key, so spreading it, or passing it to\n * a client component, carries exactly what the segment may depend on.\n */\nexport function scopedParams<T extends CoercedParams>(params: T): T {\n const scope = currentReadScope();\n if (!scope) return params;\n // Refused: every name the key leaves out — a param on the segment's path, a\n // descendant's or a slot's, present in this request or not. Absence is a\n // value too: a layout reading a child's param that this URL lacks would\n // freeze `undefined` across the URLs that have it. Only the names runtimes\n // probe on any object pass.\n const refused = (name: string | symbol) =>\n typeof name === 'string' && !scope.params.has(name) && !OBJECT_PROBES.has(name);\n const allowed = (name: string | symbol) => !refused(name);\n // Over a copy: the trap hides keys, which a frozen or non-configurable\n // target would forbid, and the request's own record stays untouched.\n const target = Object.assign(\n Object.create(Object.getPrototypeOf(params) as object | null) as T,\n params\n );\n return new Proxy(target, {\n get(target, name, receiver) {\n if (refused(name)) {\n throw readOutsideKey(scope, `the segment param \"${String(name)}\"`, 'segmentParams');\n }\n return Reflect.get(target, name, receiver);\n },\n has: (target, name) => allowed(name) && Reflect.has(target, name),\n ownKeys: (target) => Reflect.ownKeys(target).filter(allowed),\n getOwnPropertyDescriptor: (target, name) =>\n allowed(name) ? Reflect.getOwnPropertyDescriptor(target, name) : undefined,\n });\n}\n","/**\n * Request Context — per-request ALS store for headers, search params,\n * segment params, and request scope lifecycle.\n *\n * Follows the same pattern as tracing.ts: a module-level AsyncLocalStorage\n * instance, public accessor functions that throw outside request scope,\n * and a framework-internal `runWithRequestContext()` to establish scope.\n *\n * Cookie state lives in `cookie-context.ts` (split out in TIM-853). The\n * scope set up here owns the cookie jar / parsedCookies fields on the\n * store, but the cookie API and helpers are in the cookie module.\n *\n * See design/04-authorization.md §\"AccessContext does not include cookies or headers\"\n * and design/11-platform.md §\"AsyncLocalStorage\".\n */\n\nimport type { CoercedParams } from '../shared/param-value.ts';\nimport {\n requestContextAls,\n type ActionErrorForRender,\n type RequestContextStore,\n} from './als-registry.ts';\nimport {\n _setGetSearchParamsFn,\n _setGetSegmentParamsFn,\n type SearchParamsReader,\n} from '../shared/als-slots.ts';\nimport { appVisibleSearch } from '../shared/rsc-cache-key.ts';\nimport {\n mergeSlotParams,\n resolveSegmentParams,\n type SlotParamsRecord,\n} from '../shared/slot-params.ts';\nimport { isDebug } from './debug.ts';\nimport { runWithReactCacheScope, type ReactCacheScope } from './react-cache-scope.ts';\nimport {\n assertSearchParamsRead,\n assertUnscopedRead,\n scopedParams,\n} from './segment-lifetime/read-rule.ts';\nimport type { ReactFormState } from 'react-dom/client';\n\n// Re-export the ALS for framework-internal consumers that need direct access.\nexport { requestContextAls };\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns a read-only view of the current request's headers.\n *\n * Available in middleware, access checks, server components, and server actions.\n * Throws if called outside a request context (security principle #2: no global fallback).\n */\nexport function getHeaders(): ReadonlyHeaders {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getHeaders() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n // A 'document' segment may not depend on headers — nor on the pathname,\n // which reaches a component only through one (design/53).\n assertUnscopedRead('the request headers');\n\n return store.headers;\n}\n\n/**\n * Returns the value of a single request header, or undefined if absent.\n *\n * Thin wrapper over `getHeaders().get(name)` for the common case where\n * you need exactly one header.\n *\n * @internal — not part of the public API. Use `getHeaders().get(name)` instead.\n */\nexport function getHeader(name: string): string | undefined {\n const headers = getHeaders();\n return headers.get(name) ?? undefined;\n}\n\n/**\n * Returns the current request's raw URLSearchParams.\n *\n * @internal — not part of the public API. Use `defineSearchParams().get()` instead.\n *\n * @param reader The definition the caller parses through (its fields, codecs\n * and URL keys), checked against a 'document' segment's key. Omitted for a\n * raw read.\n */\nexport function getSearchParams(reader?: SearchParamsReader): URLSearchParams {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getSearchParams() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n // A definition's `.get()` passes what it parses; a 'document' segment may\n // read only fields its key reads the same way, and never the raw params.\n if (reader) assertSearchParamsRead(reader);\n else assertUnscopedRead('the raw search params');\n\n return store.searchParams;\n}\n\n// Eagerly register getSearchParams with the search-params module so\n// searchParams.get() can call it without a dynamic import.\n// Dynamic imports lose ALS context in React's RSC Flight renderer,\n// breaking getSearchParams() in parallel slot pages. See TIM-523.\n_setGetSearchParamsFn(getSearchParams);\n\n// Eagerly register getSegmentParams with the segment-params module so\n// segmentParams.get() can call it without a dynamic import.\n// Same pattern as search params — dynamic imports lose ALS context. See TIM-523.\n_setGetSegmentParamsFn(getSegmentParams);\n\n/**\n * Returns the current request's coerced segment params.\n *\n * The optional `segmentPath` argument exists only for TypeScript narrowing —\n * it does not affect the runtime return value. Pass a segment path\n * (e.g. `'/(browse)/[artistSlug]/[year]'`) to narrow the return type to the\n * exact params shape for that segment.\n *\n * Without an argument, returns all coerced params with optional types.\n *\n * See design/41-global-params.md §Function Signatures\n */\nexport function getSegmentParams(segmentPath?: string): CoercedParams {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getSegmentParams() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n if (!store.segmentParams) {\n throw new Error(\n '[timber] getSegmentParams() called before route matching completed. ' +\n 'Segment params are not available until after the route is matched.'\n );\n }\n\n // Parallel slots may derive a param the main route never had, or the same\n // name with a different type (catch-all [...year] → string[] vs dynamic\n // [year] → string). `resolveSegmentParams` is the shared definition the\n // client's useSegmentParams() also reads, so the two halves of one\n // documented API cannot drift (TIM-1285).\n const slotResolved = resolveSegmentParams(store.segmentParams, store.slotParams, segmentPath);\n // Inside a 'document' segment, a param outside its key throws (design/53).\n if (slotResolved !== store.segmentParams) return scopedParams(slotResolved);\n\n // Dev-mode validation: warn when the segment path expects dynamic\n // segments that don't exist on the actual matched segment. This catches\n // bugs like passing a child segment's $segment to a parent layout.\n // Skip for slot paths — they're validated against their own chain.\n // See design/41-global-params.md §Runtime Validation\n if (segmentPath && isDebug() && store.matchedSegmentPath) {\n const expected = extractDynamicSegments(segmentPath);\n const actual = extractDynamicSegments(store.matchedSegmentPath);\n const missing = expected.filter((s) => !actual.includes(s));\n\n if (missing.length > 0) {\n console.warn(\n `[timber] getSegmentParams('${segmentPath}') called but current segment is '${store.matchedSegmentPath}'\\n` +\n ` Missing params: ${missing.join(', ')}\\n` +\n ` These will be undefined at runtime despite the type annotation.`\n );\n }\n }\n\n return scopedParams(store.segmentParams);\n}\n\n/**\n * Set the segment params on the current request context.\n * Called by the pipeline after route matching and param coercion.\n *\n * @internal — framework use only\n */\nexport function setSegmentParams(params: CoercedParams): void {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] setSegmentParams() called outside of a request context.');\n }\n store.segmentParams = params;\n}\n\n/**\n * Store per-slot coerced segment params in the current request context.\n * Called by the route element builder when resolving parallel slots.\n *\n * @param segmentPath — The slot's full tree path (e.g. '/(browse)/@shows/[artistSlug]/[...year]')\n * @param params — The slot's coerced segment params\n * @internal — framework use only\n */\nexport function setSlotParams(segmentPath: string, params: CoercedParams): void {\n const store = requestContextAls.getStore();\n if (!store) return; // non-throwing — optional diagnostic\n if (!store.slotParams) store.slotParams = Object.create(null) as SlotParamsRecord;\n store.slotParams[segmentPath] = params;\n}\n\n/**\n * Run `fn` with the segment params a parallel slot's own chain produced, so\n * a no-arg `getSegmentParams()` inside that slot returns the slot's params\n * rather than the main route's.\n *\n * ALS is the only channel available: the slot's page and layouts are plain\n * components that receive no params prop and cannot know their own tree\n * path, so they have no way to ask for the keyed overload. The slot resolver\n * invokes each of them itself (page through `SafeSlotPage`, layouts and\n * access functions through their wrappers), and this scopes those calls.\n *\n * The store is wrapped in a Proxy rather than cloned. Everything a slot\n * renders can write to the *live* request store — `setDenyStatus` from an\n * access gate, cookie writes, the flush flag — and a clone would silently\n * strand those writes in a copy the pipeline never reads. Only the two\n * params fields are shadowed; every other read and every write passes\n * straight through to the real store.\n *\n * Returns `fn()`'s result unchanged, and no-ops outside a request context or\n * before route matching has set the main params. See TIM-1283.\n *\n * @internal — framework use only\n */\nexport function runWithSlotSegmentParams<T>(\n slotSegmentPath: string | undefined,\n slotParams: CoercedParams,\n fn: () => T\n): T {\n const store = requestContextAls.getStore();\n if (!store?.segmentParams) return fn();\n return runWithSegmentParams(\n slotSegmentPath ?? store.matchedSegmentPath,\n mergeSlotParams(store.segmentParams, slotParams),\n fn\n );\n}\n\n/**\n * Run `fn` with exactly these segment params, and this matched segment\n * path, standing in for the main route's — what a no-arg\n * `getSegmentParams()` returns inside it.\n *\n * The parallel-slot scope above is one use. The other is an intercepted\n * navigation (TIM-1607): the URL's own middleware and access.ts run while the\n * request publishes the *rendered* route's params, and each must see the\n * params of the route it was written for. Same Proxy, for the same reason:\n * every write still reaches the live store.\n *\n * @internal — framework use only\n */\nexport function runWithSegmentParams<T>(\n matchedSegmentPath: string | undefined,\n segmentParams: CoercedParams,\n fn: () => T\n): T {\n const store = requestContextAls.getStore();\n if (!store) return fn();\n const scoped = new Proxy(store, {\n get(target, prop, receiver) {\n if (prop === 'segmentParams') return segmentParams;\n if (prop === 'matchedSegmentPath') return matchedSegmentPath;\n return Reflect.get(target, prop, receiver);\n },\n });\n return requestContextAls.run(scoped, fn);\n}\n\n/**\n * The main route's coerced params, or an empty record before route matching.\n *\n * Non-throwing, unlike `getSegmentParams()`: the deny payload path publishes\n * params from wherever the pipeline happened to fail, which may be before\n * matching completed.\n *\n * @internal — framework use only. See TIM-1285.\n */\nexport function getSegmentParamsForClient(): CoercedParams {\n return requestContextAls.getStore()?.segmentParams ?? {};\n}\n\n/**\n * The per-slot params to publish to the client, or `undefined` when the\n * request rendered no slot with params of its own.\n *\n * The client cannot derive these: a slot matches the URL through its own\n * sub-tree, and the browser only ever sees the main route's record. Reading\n * the map here — rather than threading it back out of the element builder —\n * keeps one producer, since `setSlotParams` already writes it during slot\n * resolution and every serialization site runs after that completes.\n *\n * @internal — framework use only. See TIM-1285.\n */\nexport function getSlotParamsForClient(): SlotParamsRecord | undefined {\n const store = requestContextAls.getStore();\n if (!store?.slotParams) return undefined;\n return Object.keys(store.slotParams).length > 0 ? store.slotParams : undefined;\n}\n\n/**\n * Store the matched segment path (e.g. '/(browse)/[artistSlug]/[year]') for\n * dev-mode validation in getSegmentParams().\n *\n * @internal — framework use only\n */\nexport function setMatchedSegmentPath(segmentPath: string): void {\n const store = requestContextAls.getStore();\n if (!store) return; // non-throwing — optional diagnostic\n store.matchedSegmentPath = segmentPath;\n}\n\n/**\n * Extract dynamic segment names from a route pattern.\n * '/[artistSlug]/[year]' → ['artistSlug', 'year']\n * '/docs/[...slug]' → ['slug']\n */\nfunction extractDynamicSegments(route: string): string[] {\n const segments: string[] = [];\n // Match [paramName], [...paramName], [[...paramName]]\n const re = /\\[{1,2}\\.{0,3}(\\w+)\\]{1,2}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(route)) !== null) {\n segments.push(m[1]);\n }\n return segments;\n}\n\n/**\n * Returns the raw search string from the current request URL (e.g. \"?foo=bar\").\n * Synchronous — safe for use in `redirect()` which throws synchronously.\n *\n * Returns empty string if called outside a request context (non-throwing for\n * use in redirect's optional preserveSearchParams path).\n *\n * @internal — used by redirect() for preserveSearchParams support.\n */\nexport function getRequestSearchString(): string {\n const store = requestContextAls.getStore();\n // A 'document' segment's redirect cannot carry search params outside its\n // key (design/53): what it redirects to would freeze.\n if (store) assertUnscopedRead('the raw search params');\n return store?.searchString ?? '';\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Read-only Headers interface. The standard Headers class is mutable;\n * this type narrows it to read-only methods. The underlying object is\n * still a Headers instance, but user code should not mutate it.\n */\nexport type ReadonlyHeaders = Pick<\n Headers,\n 'get' | 'has' | 'entries' | 'keys' | 'values' | 'forEach' | typeof Symbol.iterator\n>;\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/** Options for `runWithRequestContext()`. */\nexport interface RequestContextOptions {\n /**\n * Resume this `React.cache` scope instead of opening a fresh one. Only the\n * post-action revalidation passes it.\n */\n reactCacheScope?: ReactCacheScope;\n /**\n * The request's cookies, already parsed. Re-entry callers (the no-JS form\n * rerender and the revalidation middleware) pass the action's\n * post-mutation cookie state here instead of round-tripping it through a\n * `Cookie:` header — the same parse the H-3 smuggling primitive abused\n * (TIM-868).\n */\n cookies?: Map<string, string>;\n /**\n * The form state of the no-JS action this render answers. Only the\n * action dispatcher's re-entry passes it; see `RequestContextStore.formState`.\n */\n formState?: ReactFormState;\n /**\n * The error of the no-JS action this render answers. Only the action\n * dispatcher's re-entry passes it; see `RequestContextStore.actionError`.\n */\n actionError?: ActionErrorForRender;\n}\n\n/**\n * Run a callback within a request context. Used by the pipeline to establish\n * per-request ALS scope so that `getHeaders()` and `getCookies()` work.\n *\n * When `options.cookies` is given, the context's `parsedCookies` map is a\n * copy of it and the raw `cookieHeader` is left empty, so\n * `parseCookieHeader` never runs for that request. Re-entry callers pass the\n * action's post-mutation cookie state this way (TIM-868).\n *\n * Each request context also opens its own `React.cache` scope, shared by\n * everything that runs inside it — proxy.ts, middleware.ts, route handlers,\n * and the render (design/02-rendering-pipeline.md §\"Cache Scoping Model\").\n *\n * @param req - The incoming Request object.\n * @param fn - The function to run within the request context.\n */\nexport function runWithRequestContext<T>(\n req: Request,\n fn: () => T,\n { reactCacheScope, cookies, formState, actionError }: RequestContextOptions = {}\n): T {\n const originalCopy = new Headers(req.headers);\n const appVisible = appVisibleSearch(new URL(req.url));\n // A copy: the caller keeps its map, and this request's writes stay here.\n const seed = cookies ? new Map(cookies) : undefined;\n const store: RequestContextStore = {\n request: req,\n headers: freezeHeaders(req.headers),\n originalHeaders: originalCopy,\n // Given parsed cookies, leave the raw header empty — parseCookieHeader is the\n // exact code path the smuggling primitive abused, and lazy parsing is\n // gated on `parsedCookies` being undefined.\n cookieHeader: seed ? '' : (req.headers.get('cookie') ?? ''),\n parsedCookies: seed,\n // Not `parsedUrl.searchParams` / `parsedUrl.search`: this store is what\n // `getSearchParams()` and `redirect({ preserveSearchParams })` read, and\n // the RSC payload URL carries the framework's `_rsc` cache key that no\n // other request has (TIM-1272).\n searchParams: appVisible.params,\n searchString: appVisible.search,\n cookieJar: new Map(),\n flushed: false,\n mutableContext: false,\n formState,\n actionError,\n };\n return requestContextAls.run(store, () => runWithReactCacheScope(fn, reactCacheScope));\n}\n\n/**\n * Enable cookie mutation for the current context. Called by the framework\n * when entering middleware.ts, server actions, or route.ts handlers.\n *\n * See design/29-cookies.md §\"Context Tracking\"\n */\nexport function setMutableCookieContext(mutable: boolean): void {\n const store = requestContextAls.getStore();\n if (store) {\n store.mutableContext = mutable;\n }\n}\n\n/**\n * Mark the response as flushed (headers committed). After this point,\n * cookie mutations log a warning instead of throwing.\n *\n * See design/29-cookies.md §\"Streaming Constraint: Post-Flush Cookie Warning\"\n */\nexport function markResponseFlushed(): void {\n const store = requestContextAls.getStore();\n if (store) {\n store.flushed = true;\n }\n}\n\n/**\n * Apply middleware-injected request headers to the current request context.\n *\n * Called by the pipeline after middleware.ts runs. Merges overlay headers\n * on top of the original request headers so downstream code (access.ts,\n * server components, server actions) sees them via `getHeaders()`.\n *\n * The original request headers are never mutated — a new frozen Headers\n * object is created with the overlay applied on top.\n *\n * See design/07-routing.md §\"Request Header Injection\"\n */\nexport function applyRequestHeaderOverlay(overlay: Headers): void {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] applyRequestHeaderOverlay() called outside of a request context.');\n }\n\n // Check if the overlay has any headers — skip if empty\n let hasOverlay = false;\n overlay.forEach(() => {\n hasOverlay = true;\n });\n if (!hasOverlay) return;\n\n // Merge: start with original headers, overlay on top\n const merged = new Headers(store.originalHeaders);\n overlay.forEach((value, key) => {\n merged.set(key, value);\n });\n store.headers = freezeHeaders(merged);\n}\n\n// ─── Read-Only Headers ────────────────────────────────────────────────────\n\nconst MUTATING_METHODS = new Set(['set', 'append', 'delete']);\n\n/**\n * Wrap a Headers object in a Proxy that throws on mutating methods.\n * Object.freeze doesn't work on Headers (native internal slots), so we\n * intercept property access and reject set/append/delete at runtime.\n *\n * Read methods (get, has, entries, etc.) must be bound to the underlying\n * Headers instance because they access private #headersList slots.\n */\nfunction freezeHeaders(source: Headers): Headers {\n const copy = new Headers(source);\n return new Proxy(copy, {\n get(target, prop) {\n if (typeof prop === 'string' && MUTATING_METHODS.has(prop)) {\n return () => {\n throw new Error(\n `[timber] getHeaders() returns a read-only Headers object. ` +\n `Calling .${prop}() is not allowed. ` +\n `Use ctx.requestHeaders in middleware to inject headers for downstream components.`\n );\n };\n }\n const value = Reflect.get(target, prop);\n // Bind methods to the real Headers instance so private slot access works\n if (typeof value === 'function') {\n return value.bind(target);\n }\n return value;\n },\n });\n}\n\n/**\n * The form state of the no-JS action this render answers, or `null`. Read by\n * the SSR renderer only (`rsc-entry/ssr-renderer.ts`), which passes it to\n * Fizz and embeds it for `hydrateRoot`. Framework-internal: not exported\n * from `@timber-js/app/server`.\n */\nexport function getFormStateForSsr(): ReactFormState | null {\n return requestContextAls.getStore()?.formState ?? null;\n}\n\n/**\n * The error of the no-JS action this render answers, or `null`. Read by the\n * route element builder, which renders it in place of the page, and by the\n * Flight `onError`, which gives it the ID the action logged it with.\n * Framework-internal: not exported from `@timber-js/app/server`.\n */\nexport function getActionErrorForRender(): ActionErrorForRender | null {\n return requestContextAls.getStore()?.actionError ?? null;\n}\n","/**\n * Cookie parsing and serialization helpers — pure string ↔ structure\n * functions with no ALS dependency. Split out of `cookie-context.ts`\n * (TIM-853) so the API surface and the wire-format codecs can each be\n * read on their own.\n *\n * The functions in this module are total over arbitrary input. They\n * never throw and never call `assertValid*` (the security validators\n * live in the API surface — `cookie-context.ts` invokes them at every\n * jar entry point so the smuggling-primitive invariant from TIM-868\n * is enforced regardless of which path produced the bytes).\n *\n * Delegates to the `cookie` package (RFC 6265, dependency-free,\n * browser-safe) for wire codecs. Adapts at the boundary to preserve\n * timber's Map-based API and never-throw contract.\n */\n\nimport { parseCookie, parseSetCookie as upstreamParseSetCookie, stringifySetCookie } from 'cookie';\n\nimport type { CookieEntry } from './als-registry.ts';\nimport type { CookieOptions } from './cookie-context.ts';\n\n/**\n * Parse a Cookie header string into a Map of name → value pairs.\n * Follows RFC 6265 §4.2.1: cookies are semicolon-separated key=value pairs.\n *\n * Values are auto-decoded with `decodeURIComponent` so they round-trip\n * losslessly with `getCookies().set()` (which auto-encodes). Malformed\n * `%`-escapes from third-party cookies fall back to the raw byte sequence\n * — the parser must be total over arbitrary inbound headers, including\n * non-conforming values from other servers, browser extensions, etc.\n */\nexport function parseCookieHeader(header: string): Map<string, string> {\n const map = new Map<string, string>();\n if (!header) return map;\n\n // cookie.parseCookie returns a plain object with first-wins semantics\n // and uses safeDecodeURIComponent by default (try/catch around\n // decodeURIComponent, falls back to raw). This matches our contract.\n const parsed = parseCookie(header);\n for (const name in parsed) {\n const value = parsed[name];\n if (value !== undefined) map.set(name, value);\n }\n\n return map;\n}\n\n/**\n * Decode a single cookie value with `decodeURIComponent`, falling back to\n * the raw byte sequence if the input contains a malformed `%`-escape.\n *\n * Used by both `parseCookieHeader` (incoming Cookie: header) and the\n * `setRaw` forwarding path (outgoing Set-Cookie from upstream services).\n * Total — never throws.\n *\n * cookie's internal decode has identical semantics but is not exported,\n * so we keep this standalone helper.\n */\nexport function safeDecodeCookieValue(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\n/**\n * Serialize a CookieEntry into a Set-Cookie header value.\n *\n * Total — never throws. If the cookie package's serializer rejects\n * the input (e.g. non-integer maxAge, forbidden chars in name/value),\n * falls back to a minimal hand-rolled serialization so the response\n * path is never interrupted by a codec error.\n */\nexport function serializeCookieEntry(entry: CookieEntry): string {\n try {\n return stringifySetCookie(\n {\n name: entry.name,\n value: entry.value,\n domain: entry.options.domain,\n path: entry.options.path,\n expires: entry.options.expires,\n maxAge: entry.options.maxAge,\n httpOnly: entry.options.httpOnly,\n secure: entry.options.secure,\n sameSite: entry.options.sameSite,\n partitioned: entry.options.partitioned,\n },\n // timber pre-encodes values at the API surface (set() calls\n // encodeURIComponent), so pass identity to avoid double-encoding.\n { encode: (v: string) => v }\n );\n } catch {\n // Fallback: hand-roll a minimal Set-Cookie so we never drop the\n // header entirely. The entry-point validators in cookie-context.ts\n // already reject truly dangerous input — this path only fires for\n // edge-case formatting the upstream serializer is strict about.\n return serializeCookieEntryFallback(entry);\n }\n}\n\nfunction serializeCookieEntryFallback(entry: CookieEntry): string {\n const parts = [`${entry.name}=${entry.value}`];\n const opts = entry.options;\n\n if (opts.domain) parts.push(`Domain=${opts.domain}`);\n if (opts.path) parts.push(`Path=${opts.path}`);\n if (opts.expires) parts.push(`Expires=${opts.expires.toUTCString()}`);\n if (opts.maxAge !== undefined) parts.push(`Max-Age=${opts.maxAge}`);\n if (opts.httpOnly) parts.push('HttpOnly');\n if (opts.secure) parts.push('Secure');\n if (opts.sameSite) {\n parts.push(`SameSite=${opts.sameSite.charAt(0).toUpperCase()}${opts.sameSite.slice(1)}`);\n }\n if (opts.partitioned) parts.push('Partitioned');\n\n return parts.join('; ');\n}\n\n/**\n * Parse a raw `Set-Cookie` header string into name, value, and options.\n * Handles all standard attributes: Path, Domain, Max-Age, Expires,\n * SameSite, Secure, HttpOnly, Partitioned.\n *\n * Does NOT apply DEFAULT_COOKIE_OPTIONS — the caller decides whether\n * to merge defaults (e.g. `set()` does, but `setRaw()` should preserve\n * the original header's intent).\n */\nexport function parseSetCookie(\n header: string\n): { name: string; value: string; options: CookieOptions } | null {\n const parsed = upstreamParseSetCookie(header, {\n // Don't decode — setRaw expects the wire-form value so it can\n // re-emit verbatim and validate against cookie-octet.\n decode: (v: string) => v,\n });\n\n // cookie.parseSetCookie always returns a SetCookie object, but\n // with name/value as empty strings when the header has no `=`.\n if (!parsed.name) return null;\n\n const options: CookieOptions = {};\n\n if (parsed.path !== undefined) options.path = parsed.path || '/';\n if (parsed.domain !== undefined) options.domain = parsed.domain;\n if (parsed.maxAge !== undefined && Number.isFinite(parsed.maxAge)) {\n options.maxAge = parsed.maxAge;\n }\n if (parsed.expires !== undefined) options.expires = parsed.expires;\n if (parsed.sameSite !== undefined && parsed.sameSite !== true) {\n const sameSite = (parsed.sameSite as string).toLowerCase();\n if (sameSite === 'strict' || sameSite === 'lax' || sameSite === 'none') {\n options.sameSite = sameSite;\n }\n }\n if (parsed.secure) options.secure = true;\n if (parsed.httpOnly) options.httpOnly = true;\n if (parsed.partitioned) options.partitioned = true;\n\n return { name: parsed.name, value: parsed.value ?? '', options };\n}\n","/**\n * Cookie Context — per-request cookie API and on-the-wire helpers.\n *\n * Split out of `request-context.ts` (TIM-853) so the cookie subsystem\n * — encoding contract, options grammar, parser, serializer, and RYW map\n * — lives in one file. The headers/scope/params APIs\n * stay in `request-context.ts` and call into this module via the\n * exported helpers.\n *\n * See design/29-cookies.md for the encoding contract and read-your-own-\n * writes semantics. See ONGOING_SECURITY.md H-3 (TIM-868) for the\n * smuggling primitive that the encoding contract closes.\n */\n\nimport { assertCookieRead, assertUnscopedRead } from './segment-lifetime/read-rule.ts';\nimport { COOKIE_READ_THROUGH, type CookieReadThrough } from '../shared/cookie-read-through.ts';\nimport { requestContextAls, type RequestContextStore } from './als-registry.ts';\nimport { isDebug } from './debug.ts';\nimport {\n ANY_COOKIE,\n noteCookieReadForReactCache,\n warnIfCachedCookieIsWritten,\n} from './react-cache-scope.ts';\nimport {\n assertValidCookieName,\n assertValidCookieValue,\n assertValidCookieOptions,\n} from '../cookies/validation.ts';\nimport {\n parseCookieHeader,\n parseSetCookie,\n safeDecodeCookieValue,\n serializeCookieEntry,\n} from './cookie-parsing.ts';\n\n// Re-export the validators so framework-internal consumers and tests can\n// import the canonical implementation from the same module that hosts\n// `getCookies()`. The pure shared module lives in `cookies/validation.ts`\n// so the client `useCookie` hook can use the same checks without pulling\n// in the server ALS code.\nexport { assertValidCookieName, assertValidCookieValue, assertValidCookieOptions };\n\n// ─── Public API ───────────────────────────────────────────────────────────\n\n/**\n * Returns a cookie accessor for the current request.\n *\n * Available in middleware, access checks, server components, and server actions.\n * Throws if called outside a request context (security principle #2: no global fallback).\n *\n * Read methods (.get, .has, .getAll) are always available and reflect\n * read-your-own-writes from .set() calls in the same request.\n *\n * Mutation methods (.set, .delete, .clear) are only available in mutable\n * contexts (middleware.ts, server actions, route.ts handlers). Calling them\n * in read-only contexts (access.ts, server components) throws.\n *\n * This is the escape hatch for direct cookie jar operations. For typed\n * cookie access, use `defineCookie()` instead.\n *\n * See design/29-cookies.md\n */\nexport function getCookieJar(): RequestCookies {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error(\n '[timber] getCookieJar() called outside of a request context. ' +\n 'It can only be used in middleware, access checks, server components, and server actions.'\n );\n }\n\n // Parse cookies lazily on first access\n if (!store.parsedCookies) {\n store.parsedCookies = parseCookieHeader(store.cookieHeader);\n }\n\n const map = store.parsedCookies;\n return {\n // Reads are noted (dev only) so a later write of the same cookie can\n // warn if React.cache may have memoized the old value (TIM-1529 D3).\n // Inside a 'document' segment, only the cookies in its key (design/53).\n get(name: string): string | undefined {\n assertCookieRead(name);\n noteCookieReadForReactCache(name);\n return map.get(name);\n },\n // A typed definition's read: allowed for a keyed cookie read through the\n // key's own definition (shared/cookie-read-through.ts).\n [COOKIE_READ_THROUGH](name: string, codec: unknown): string | undefined {\n assertCookieRead(name, codec);\n noteCookieReadForReactCache(name);\n return map.get(name);\n },\n has(name: string): boolean {\n assertCookieRead(name);\n noteCookieReadForReactCache(name);\n return map.has(name);\n },\n getAll(): Array<{ name: string; value: string }> {\n assertUnscopedRead('every cookie');\n noteCookieReadForReactCache(ANY_COOKIE);\n return Array.from(map.entries()).map(([name, value]) => ({ name, value }));\n },\n get size(): number {\n assertUnscopedRead('the number of cookies');\n noteCookieReadForReactCache(ANY_COOKIE);\n return map.size;\n },\n\n set(name: string, value: string, options?: SetCookieOptions): void {\n assertMutable(store, 'set');\n // Validate the name first — names cannot be URL-encoded (RFC 7230\n // token grammar is strict), so a bad name is always a bug.\n assertValidCookieName(name);\n // Type guard with a guiding error. The single most common mistake\n // is passing a non-string (object, number, Date) and expecting the\n // framework to JSON-encode. Point developers at jsonCookieCodec.\n if (typeof value !== 'string') {\n throw new Error(\n `[timber] getCookieJar().set(${JSON.stringify(name)}, …): value must be a string, got ${typeof value}.\\n` +\n ` To store a JSON-serializable value, use defineCookie + jsonCookieCodec:\\n` +\n `\\n` +\n ` import { defineCookie, jsonCookieCodec } from '@timber-js/app/cookies';\\n` +\n `\\n` +\n ` export const ${name}Cookie = defineCookie(${JSON.stringify(name)}, {\\n` +\n ` codec: jsonCookieCodec(),\\n` +\n ` });\\n` +\n `\\n` +\n ` ${name}Cookie.set(value);\\n` +\n `\\n` +\n ` See design/29-cookies.md §\"Typed Cookies with Schema Validation\".`\n );\n }\n // Encode the value so the on-the-wire bytes always satisfy\n // RFC 6265 §4.1.1 cookie-octet. encodeURIComponent's output is a\n // strict subset of cookie-octet (only `A-Z a-z 0-9 ! ' ( ) * - . _\n // ~ %`), so the encoded form can never carry the H-3 smuggling\n // primitive — `;` becomes `%3B`, CR/LF become `%0D`/`%0A`, etc.\n // The round-trip is lossless: parseCookieHeader auto-decodes on\n // read, so `cookies().get(name)` returns exactly `value`. See\n // ONGOING_SECURITY.md H-3 (TIM-868) and design/29-cookies.md\n // §\"Encoding Contract\".\n //\n // The `{ raw: true }` opt-out skips the encoder for callers who\n // need exact byte control (e.g. forwarding pre-encoded cookies\n // from an upstream service). The opt-out goes through the strict\n // cookie-octet validator instead — the smuggling primitive cannot\n // sneak in via the escape hatch.\n const raw = options?.raw === true;\n const wireValue = raw ? value : encodeURIComponent(value);\n if (raw) {\n assertValidCookieValue(name, wireValue);\n }\n if (store.flushed) {\n if (isDebug()) {\n console.warn(\n `[timber] warn: getCookieJar().set('${name}') called after response headers were committed.\\n` +\n ` The cookie will NOT be sent. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n }\n return;\n }\n // Strip the framework-only `raw` flag before persisting — it is\n // not an HTTP cookie attribute and must not leak into the jar.\n const { raw: _raw, ...attributeOptions } = options ?? {};\n void _raw;\n const opts = { ...DEFAULT_COOKIE_OPTIONS, ...attributeOptions };\n assertValidCookieOptions(opts);\n store.cookieJar.set(name, { name, value: wireValue, options: opts });\n // Read-your-own-writes: store the DECODED logical value so that\n // subsequent `cookies().get(name)` in the same request returns\n // exactly what the developer wrote — never the encoded form.\n // For `{ raw: true }`, the wire form IS the logical form.\n map.set(name, raw ? wireValue : value);\n warnIfCachedCookieIsWritten(name);\n },\n\n setFromHeaders(headers: Headers): void {\n assertMutable(store, 'setFromHeaders');\n if (store.flushed) {\n console.warn(\n `[timber] warn: getCookieJar().setFromHeaders() called after response headers were committed.\\n` +\n ` The cookies will NOT be sent. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n return;\n }\n // Headers.getSetCookie() returns individual Set-Cookie strings,\n // avoiding the fragile comma-splitting that raw .get() requires.\n for (const raw of headers.getSetCookie()) {\n const parsed = parseSetCookie(raw);\n if (parsed) {\n // Use setRaw to preserve the original header's attributes without\n // merging DEFAULT_COOKIE_OPTIONS (parseSetCookie intentionally\n // does not apply defaults — see its doc comment).\n setRaw(store, map, parsed.name, parsed.value, parsed.options);\n }\n }\n },\n\n delete(name: string, options?: CookieDeleteOptions): void {\n assertMutable(store, 'delete');\n // Validate the name even though delete writes an empty value — a\n // smuggled name (`;` or CR/LF) would corrupt the Set-Cookie header\n // we emit. See ONGOING_SECURITY.md H-3 (TIM-868).\n assertValidCookieName(name);\n if (store.flushed) {\n if (isDebug()) {\n console.warn(\n `[timber] warn: getCookieJar().delete('${name}') called after response headers were committed.\\n` +\n ` The cookie will NOT be deleted. Move cookie mutations to middleware.ts, a server action,\\n` +\n ` or a route.ts handler.`\n );\n }\n return;\n }\n const opts: CookieOptions = {\n ...DEFAULT_COOKIE_OPTIONS,\n ...options,\n maxAge: 0,\n expires: new Date(0),\n };\n // delete() is a jar entry point like set() — caller-supplied\n // attributes are serialized verbatim into the Set-Cookie header,\n // so they must pass the same attribute-injection guard. See\n // design/29-cookies.md §\"Cookie Attribute Validation\" (TIM-1026).\n assertValidCookieOptions(opts);\n store.cookieJar.set(name, { name, value: '', options: opts });\n // Remove from read view\n map.delete(name);\n warnIfCachedCookieIsWritten(name);\n },\n\n clear(): void {\n assertMutable(store, 'clear');\n if (store.flushed) return;\n // Delete every incoming cookie\n for (const name of Array.from(map.keys())) {\n store.cookieJar.set(name, {\n name,\n value: '',\n options: { ...DEFAULT_COOKIE_OPTIONS, maxAge: 0, expires: new Date(0) },\n });\n }\n map.clear();\n warnIfCachedCookieIsWritten(ANY_COOKIE);\n },\n\n toString(): string {\n assertUnscopedRead('every cookie');\n noteCookieReadForReactCache(ANY_COOKIE);\n // Re-encode values when serializing as a Cookie header — the\n // RYW map holds decoded logical values, but a Cookie header has\n // to satisfy `cookie-octet`. Mirror the auto-encode contract on\n // `set()` so toString() round-trips losslessly with parseCookieHeader.\n return Array.from(map.entries())\n .map(([name, value]) => `${name}=${encodeURIComponent(value)}`)\n .join('; ');\n },\n };\n}\n\n/**\n * Returns the value of a single cookie, or undefined if absent.\n *\n * @internal — not part of the public API. Use `defineCookie().get()` or `getCookieJar().get()` instead.\n */\nexport function getCookie(name: string): string | undefined {\n const jar = getCookieJar();\n return jar.get(name);\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\n/**\n * Per-call options for `getCookies().set()`. Extends the persistent\n * `CookieOptions` (HTTP cookie attributes) with framework-only flags\n * that are NOT serialized into the Set-Cookie header.\n *\n * The `raw` flag is the escape hatch for the auto-encoding contract.\n * See design/29-cookies.md §\"Encoding Contract\".\n */\nexport interface SetCookieOptions extends CookieOptions {\n /**\n * Skip the framework's `encodeURIComponent` pass and store the value\n * verbatim. The value is then validated against the strict RFC 6265\n * §4.1.1 `cookie-octet` grammar — the H-3 smuggling primitive cannot\n * sneak in via this opt-out.\n *\n * Use this when forwarding a cookie value that is already in its\n * intended on-the-wire form (e.g. mirroring an upstream service's\n * Set-Cookie). Default: `false` (auto-encode).\n */\n raw?: boolean;\n}\n\n/** Options for setting a cookie. See design/29-cookies.md. */\nexport interface CookieOptions {\n /** Domain scope. Default: omitted (current domain only). */\n domain?: string;\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Expiration date. Mutually exclusive with maxAge. */\n expires?: Date;\n /** Max age in seconds. Mutually exclusive with expires. */\n maxAge?: number;\n /** Prevent client-side JS access. Default: true. */\n httpOnly?: boolean;\n /** Only send over HTTPS. Default: true. */\n secure?: boolean;\n /** Cross-site request policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Partitioned (CHIPS) — isolate cookie per top-level site. Default: false. */\n partitioned?: boolean;\n}\n\n/**\n * Options for deleting a cookie: every attribute but the lifetime, which\n * delete() forces to the past. Pass the attributes the cookie was set with —\n * a partitioned cookie is only removed by a deletion that is also\n * `Partitioned`, since browsers keep it in a separate jar (TIM-1606).\n */\nexport type CookieDeleteOptions = Omit<CookieOptions, 'maxAge' | 'expires'>;\n\n/**\n * Cookie accessor returned by `getCookies()`.\n *\n * Read methods are always available. Mutation methods throw in read-only\n * contexts (access.ts, server components).\n */\nexport interface RequestCookies {\n /** Get a cookie value by name. Returns undefined if not present. */\n get(name: string): string | undefined;\n /** @internal A typed definition's read (`defineCookie().get()`). */\n [COOKIE_READ_THROUGH]?: CookieReadThrough;\n /** Check if a cookie exists. */\n has(name: string): boolean;\n /** Get all cookies as an array of { name, value } pairs. */\n getAll(): Array<{ name: string; value: string }>;\n /** Number of cookies. */\n readonly size: number;\n /**\n * Set a cookie. Only available in mutable contexts (middleware, actions,\n * route handlers).\n *\n * The value is auto-encoded with `encodeURIComponent` so the on-the-wire\n * bytes always satisfy RFC 6265 §4.1.1 cookie-octet — `cookies().get()`\n * returns the same logical value the developer wrote. Pass `{ raw: true }`\n * to skip the encoder; the raw path validates against the strict\n * cookie-octet grammar instead. See design/29-cookies.md §\"Encoding\n * Contract\" and ONGOING_SECURITY.md H-3 (TIM-868).\n */\n set(name: string, value: string, options?: SetCookieOptions): void;\n /**\n * Copy all `Set-Cookie` headers from a `Headers` object.\n * Parses each header and forwards name, value, and all attributes\n * (path, domain, max-age, expires, sameSite, secure, httpOnly, partitioned).\n *\n * Useful when forwarding cookies from an internal `fetch()` or auth handler:\n * ```ts\n * const response = await auth.handler(req);\n * getCookies().then(c => c.setFromHeaders(response.headers));\n * ```\n */\n setFromHeaders(headers: Headers): void;\n /** Delete a cookie. Only available in mutable contexts. */\n delete(name: string, options?: CookieDeleteOptions): void;\n /** Delete all cookies. Only available in mutable contexts. */\n clear(): void;\n /** Serialize cookies as a Cookie header string. */\n toString(): string;\n}\n\nconst DEFAULT_COOKIE_OPTIONS: CookieOptions = {\n path: '/',\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n};\n\n// ─── Framework-Internal Helpers ───────────────────────────────────────────\n\n/**\n * Build a Map of cookie name → value reflecting the current request's\n * read-your-own-writes state. Includes incoming cookies plus any\n * mutations from getCookies().set() / getCookies().delete() in the same request.\n *\n * Used by SSR renderers to populate NavContext.cookies so that\n * useCookie()'s server snapshot matches the actual response state.\n *\n * See design/29-cookies.md §\"Read-Your-Own-Writes\"\n * See design/triage/TIM-441-cookie-api-triage.md §4\n */\nexport function getCookiesForSsr(): Map<string, string> {\n const store = requestContextAls.getStore();\n if (!store) {\n throw new Error('[timber] getCookiesForSsr() called outside of a request context.');\n }\n\n // Trigger lazy parsing if not yet done\n if (!store.parsedCookies) {\n store.parsedCookies = parseCookieHeader(store.cookieHeader);\n }\n\n // The parsedCookies map already reflects read-your-own-writes:\n // - getCookies().set() updates the map via map.set(name, value)\n // - getCookies().delete() removes from the map via map.delete(name)\n // Return a copy so callers can't mutate the internal map.\n return new Map(store.parsedCookies);\n}\n\n/**\n * Collect all Set-Cookie headers from the cookie jar.\n * Called by the framework at flush time to apply cookies to the response.\n *\n * Returns an array of serialized Set-Cookie header values.\n */\nexport function getSetCookieHeaders(): string[] {\n const store = requestContextAls.getStore();\n if (!store) return [];\n return Array.from(store.cookieJar.values()).map(serializeCookieEntry);\n}\n\n// ─── Cookie Helpers ───────────────────────────────────────────────────────\n\n/** Throw if cookie mutation is attempted in a read-only context. */\nfunction assertMutable(store: RequestContextStore, method: string): void {\n if (!store.mutableContext) {\n throw new Error(\n `[timber] getCookieJar().${method}() cannot be called in this context.\\n` +\n ` Set cookies in middleware.ts, server actions, or route.ts handlers.`\n );\n }\n}\n\n/**\n * Write a cookie to the jar WITHOUT merging DEFAULT_COOKIE_OPTIONS.\n * Used by setFromHeaders to preserve the original header's attributes exactly.\n *\n * For deletion cookies (maxAge=0), the jar entry is still created so the\n * Set-Cookie header is emitted, but the cookie is NOT added to the read map\n * (it would be misleading — the cookie is being deleted).\n */\nfunction setRaw(\n store: RequestContextStore,\n readMap: Map<string, string>,\n name: string,\n value: string,\n options: CookieOptions\n): void {\n // setRaw is the forwarding path for upstream Set-Cookie headers\n // (`getCookies().setFromHeaders(response.headers)`). The value comes\n // out of `parseSetCookie` in its on-the-wire form — already encoded\n // by whoever produced it — so we re-emit it verbatim into our jar.\n // We DO validate against the strict cookie-octet grammar, both as\n // defense-in-depth against a malicious upstream and to keep the\n // ONGOING_SECURITY.md H-3 invariant intact at every entry point into\n // the cookie jar / RYW map.\n assertValidCookieName(name);\n assertValidCookieValue(name, value);\n // Options get the same entry-point guard as set()/delete(). For the\n // setFromHeaders path this can only fire on attributes parseSetCookie\n // cannot produce (it splits on `;` and normalizes Max-Age/SameSite),\n // but setRaw is the jar entry point — the invariant lives here, not in\n // the caller. See design/29-cookies.md §\"Cookie Attribute Validation\".\n assertValidCookieOptions(options);\n store.cookieJar.set(name, { name, value, options });\n warnIfCachedCookieIsWritten(name);\n // Deletion cookies (Max-Age=0) should not appear in the read map.\n if (options.maxAge === 0) {\n readMap.delete(name);\n } else {\n // Decode for the RYW map so consumers see the same logical bytes\n // they would see if the upstream cookie had arrived on the next\n // request. Mirrors `parseCookieHeader`'s auto-decode.\n readMap.set(name, safeDecodeCookieValue(value));\n }\n}\n","// Server-side primitives: deny, redirect, redirectExternal, waitUntil\n//\n// These are the core runtime signals that components, middleware, and access gates\n// use to control request flow. See design/10-error-handling.md.\n\nimport type { JsonSerializable } from './types.ts';\nimport { getWaitUntil as _getWaitUntil } from './waituntil-bridge.ts';\nimport { isDebug } from './debug.ts';\nimport { getRequestSearchString } from './request-context.ts';\nimport { mergePreservedSearchParams } from '../shared/merge-search-params.ts';\nimport { DENY_BRAND, REDIRECT_BRAND } from './signal-identity.ts';\nimport {\n assertRelativeRedirectPath,\n validateExternalRedirectUrl,\n} from '../shared/href-validation.ts';\n\n// ─── Dev-mode validation ────────────────────────────────────────────────────\n\n/**\n * Check if a value is JSON-serializable without data loss.\n * Returns a description of the first non-serializable value found, or null if OK.\n *\n * @internal Exported for testing only.\n */\nexport function findNonSerializable(value: unknown, path = 'data'): string | null {\n if (value === null || value === undefined) return null;\n\n switch (typeof value) {\n case 'string':\n case 'number':\n case 'boolean':\n return null;\n case 'bigint':\n return `${path} contains a BigInt — BigInt throws in JSON.stringify`;\n case 'function':\n return `${path} is a function — functions are not JSON-serializable`;\n case 'symbol':\n return `${path} is a symbol — symbols are not JSON-serializable`;\n case 'object':\n break;\n default:\n return `${path} has unsupported type \"${typeof value}\"`;\n }\n\n if (value instanceof Date) {\n return `${path} is a Date — Dates silently coerce to strings in JSON.stringify`;\n }\n if (value instanceof Map) {\n return `${path} is a Map — Maps serialize as {} in JSON.stringify (data loss)`;\n }\n if (value instanceof Set) {\n return `${path} is a Set — Sets serialize as {} in JSON.stringify (data loss)`;\n }\n if (value instanceof RegExp) {\n return `${path} is a RegExp — RegExps serialize as {} in JSON.stringify`;\n }\n if (value instanceof Error) {\n return `${path} is an Error — Errors serialize as {} in JSON.stringify`;\n }\n\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) {\n const result = findNonSerializable(value[i], `${path}[${i}]`);\n if (result) return result;\n }\n return null;\n }\n\n // Plain object — only Object.prototype is safe. Null-prototype objects\n // (Object.create(null)) survive JSON.stringify but React Flight rejects\n // them with \"Classes or null prototypes are not supported\", so the\n // pre-flush deny path (renderDenyPage → renderToReadableStream) would throw.\n const proto = Object.getPrototypeOf(value);\n if (proto === null) {\n return `${path} is a null-prototype object — React Flight rejects null prototypes`;\n }\n if (proto !== Object.prototype) {\n const name = (value as object).constructor?.name ?? 'unknown';\n return `${path} is a ${name} instance — class instances may lose data in JSON.stringify`;\n }\n\n for (const key of Object.keys(value as Record<string, unknown>)) {\n const result = findNonSerializable((value as Record<string, unknown>)[key], `${path}.${key}`);\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Emit a dev-mode warning if data is not JSON-serializable.\n * No-op in production.\n */\nfunction warnIfNotSerializable(data: unknown, callerName: string): void {\n if (!isDebug()) return;\n if (data === undefined) return;\n\n const issue = findNonSerializable(data);\n if (issue) {\n console.warn(\n `[timber] ${callerName}: ${issue}. ` +\n 'Data passed to deny() must be JSON-serializable because ' +\n 'the post-flush path uses JSON.stringify, not React Flight.'\n );\n }\n}\n\n// ─── DenySignal ─────────────────────────────────────────────────────────────\n\n/**\n * Render-phase signal thrown by `deny()`. Caught by the framework to produce\n * the correct HTTP status code (segment context) or graceful degradation (slot context).\n *\n * Detect with `isDenySignal()`, never `instanceof` — see \"Signal branding\" in signal-identity.ts.\n */\nexport class DenySignal extends Error {\n readonly [DENY_BRAND] = true;\n readonly status: number;\n readonly data: JsonSerializable | undefined;\n\n /**\n * Ordered list of segment keys that own matching deny pages for this\n * signal, best match first. Present = addressed (a boundary should\n * render it); absent = unplaced (the re-render fallback serves it).\n *\n * In-tree hoists stamp a single-element list (`[entry.ownerKey]`) —\n * identical to the pre-TIM-1450 `ownerKey`. Late addressing (TIM-1450)\n * stamps the full candidate list so the client can find the first\n * *reachable* owner via its ancestry context, eliminating the\n * owner-below-throw-site escape.\n *\n * See design/04-authorization.md §\"Where a Deny Page Renders\", TIM-1356.\n */\n owners?: string[];\n\n /**\n * When true, the pipeline must respond with `rscErrorEnvelope` so the\n * client hard-navigates instead of attempting to render a deny page\n * from the RSC payload. Set by AccessGate when a skipped segment\n * denies — rendering the deny page in-tree would appear inside the\n * client's cached layout chrome (TIM-1074). See TIM-1363.\n */\n _hardNavigate?: boolean;\n\n /**\n * When true, no boundary in the tree that threw this may place it: the\n * denying gate guards a segment of the URL's own route that the rendered\n * tree does not contain, so none of its deny pages, nor their layouts, are\n * here. Set by the gate an intercepted navigation renders for each such\n * segment (TIM-1607), together with `_hardNavigate`.\n *\n * Flight's `onError` does not late-address it, and its row carries\n * `leaveSpa`, which every client boundary declines but the terminal, which\n * leaves the SPA — so the document request for the URL renders the URL's\n * own deny page with its real status, wherever the deny lands in time.\n */\n _leaveSpa?: boolean;\n\n constructor(status: number, data?: JsonSerializable) {\n super(`Access denied with status ${status}`);\n this.name = 'DenySignal';\n this.status = status;\n this.data = data;\n }\n\n /**\n * Extract the file that called deny() from the stack trace.\n * Returns a short path (e.g. \"app/auth/access.ts\") or undefined if\n * the stack can't be parsed. Dev-only — used for dev log output.\n */\n get sourceFile(): string | undefined {\n if (!this.stack) return undefined;\n const frames = this.stack.split('\\n');\n // Skip the Error line and the deny() frame — the caller is the 3rd line.\n // Stack format: \" at FnName (file:line:col)\" or \" at file:line:col\"\n for (let i = 2; i < frames.length; i++) {\n const frame = frames[i];\n if (!frame) continue;\n // Skip framework internals\n if (frame.includes('primitives.ts') || frame.includes('node_modules')) continue;\n // Extract file path from the frame\n const match =\n frame.match(/\\(([^)]+?)(?::\\d+:\\d+)\\)/) ?? frame.match(/at\\s+([^\\s]+?)(?::\\d+:\\d+)/);\n if (match?.[1]) {\n // Shorten to app-relative path\n const full = match[1];\n const appIdx = full.indexOf('/app/');\n return appIdx >= 0 ? full.slice(appIdx + 1) : full;\n }\n }\n return undefined;\n }\n}\n\n/** Options for deny(). */\nexport interface DenyOptions {\n /** Human-readable message (logged server-side, not sent to client). */\n message?: string;\n /**\n * JSON-serializable data forwarded as the `data` prop to status-code files\n * and `denied.tsx`. Named `dangerouslyPassData` because this data crosses\n * the RSC → client serialization boundary — do not pass sensitive server\n * state (tokens, internal IDs, database rows).\n */\n dangerouslyPassData?: JsonSerializable;\n}\n\n/**\n * Universal denial/error primitive. Throws a `DenySignal` that the framework catches.\n *\n * - In segment context (outside Suspense): produces HTTP status code\n * - In slot context: graceful degradation → denied.tsx → default.tsx → null\n * - Inside Suspense (hold window): promoted to pre-flush behavior\n * - Inside Suspense (after flush): error boundary + noindex meta\n *\n * ```ts\n * deny() // 403 (default)\n * deny(404) // 404\n * deny(503, { message: 'Maintenance' }) // server-only log message\n * deny(404, { dangerouslyPassData: { resourceId: params.id } }) // explicit client opt-in\n * ```\n *\n * Accepts any 4xx or 5xx status code — it is also how a page renders a 5xx\n * status file with data. An unplanned throw needs no primitive: it renders\n * the error page with a 500.\n *\n * @param status - HTTP status code (4xx or 5xx). Default: 403.\n * @param options - Optional message and/or data to pass to the client.\n */\nexport function deny(status?: number, options?: DenyOptions): never {\n const resolvedStatus = status ?? 403;\n const resolvedData = options?.dangerouslyPassData;\n\n if (resolvedStatus < 400 || resolvedStatus > 599) {\n throw new Error(`deny() requires a 4xx or 5xx status code, got ${resolvedStatus}.`);\n }\n warnIfNotSerializable(resolvedData, 'deny()');\n throw new DenySignal(resolvedStatus, resolvedData);\n}\n\n// Single source of truth shared with the client next/navigation shim —\n// see shared/redirect-type.ts.\nexport { RedirectType } from '../shared/redirect-type.ts';\n\n// ─── RedirectSignal ─────────────────────────────────────────────────────────\n\n/**\n * Render-phase signal thrown by `redirect()` and `redirectExternal()`.\n * Caught by the framework to produce a 3xx response or client-side navigation.\n *\n * Detect with `isRedirectSignal()`, never `instanceof` — see \"Signal branding\" in signal-identity.ts.\n */\nexport class RedirectSignal extends Error {\n readonly [REDIRECT_BRAND] = true;\n readonly location: string;\n readonly status: number;\n\n constructor(location: string, status: number) {\n super(`Redirect to ${location}`);\n this.name = 'RedirectSignal';\n this.location = location;\n this.status = status;\n }\n}\n\n// ─── Signal Detection ───────────────────────────────────────────────────────\n\n/**\n * Options for redirect() — alternative to passing a bare status code.\n */\nexport interface RedirectOptions {\n /** HTTP redirect status code (3xx). Defaults to 302 (or 308 when `permanent: true`). */\n status?: number;\n /**\n * When true, defaults the status to 308 (Permanent Redirect, preserves HTTP method).\n * If `status` is also provided, `status` takes precedence.\n *\n * @example\n * redirect('/new-path', { permanent: true }); // 308\n * redirect('/new-path', { permanent: true, status: 301 }); // 301\n */\n permanent?: boolean;\n /**\n * Preserve search params from the current request URL on the redirect target.\n *\n * - `true` — preserve ALL current search params (target params take precedence)\n * - `string[]` — preserve only the named params (e.g. `['private', 'token']`)\n *\n * Target path's own query params always take precedence over preserved ones.\n */\n preserveSearchParams?: true | string[];\n}\n\n/**\n * Redirect to a relative path. Rejects absolute and protocol-relative URLs.\n * Use `redirectExternal()` for external redirects with an allow-list.\n *\n * @param path - Relative path (e.g. '/login', 'settings', '/login?returnTo=/dash')\n * @param statusOrOptions - HTTP status code (3xx, default 302) or options object.\n *\n * @example\n * // Simple redirect\n * redirect('/login');\n *\n * // With status code\n * redirect('/login', 301);\n *\n * // With preserved search params\n * redirect(`/docs/${version}/${slug}`, { preserveSearchParams: ['foo'] });\n */\nexport function redirect(path: string, statusOrOptions?: number | RedirectOptions): never {\n let status: number;\n let preserveSearchParams: true | string[] | undefined;\n\n if (typeof statusOrOptions === 'number') {\n status = statusOrOptions;\n } else if (statusOrOptions) {\n // Explicit status wins. Otherwise permanent: true → 308, default → 302.\n status = statusOrOptions.status ?? (statusOrOptions.permanent ? 308 : 302);\n preserveSearchParams = statusOrOptions.preserveSearchParams;\n } else {\n status = 302;\n }\n\n if (status < 300 || status > 399) {\n throw new Error(`redirect() requires a 3xx status code, got ${status}.`);\n }\n // Relative-only validation shared with the client next/navigation shim —\n // strips C0 controls and normalizes backslashes before the scheme check.\n assertRelativeRedirectPath(path);\n\n let resolvedPath = path;\n if (preserveSearchParams) {\n const currentSearch = getRequestSearchString();\n resolvedPath = mergePreservedSearchParams(path, currentSearch, preserveSearchParams);\n }\n\n throw new RedirectSignal(resolvedPath, status);\n}\n\n/**\n * Redirect to an external URL. The origin must be in the provided allow-list.\n *\n * Only http: and https: schemes are permitted. The allow-list is matched\n * against full origins (scheme + host + port), not bare hostnames.\n *\n * @param url - Absolute URL to redirect to.\n * @param allowList - Array of allowed origins (e.g. ['https://example.com', 'https://auth.example.com']).\n * @param status - HTTP redirect status code (3xx). Defaults to 302.\n */\nexport function redirectExternal(url: string, allowList: string[], status: number = 302): never {\n if (status < 300 || status > 399) {\n throw new Error(`redirectExternal() requires a 3xx status code, got ${status}.`);\n }\n\n const canonicalUrl = validateExternalRedirectUrl(url, allowList);\n throw new RedirectSignal(canonicalUrl, status);\n}\n\n// ─── waitUntil ──────────────────────────────────────────────────────────────\n\n// Intentional per-app singleton — warn-once flag that persists for the\n// lifetime of the process/isolate. Not per-request; do not migrate to ALS.\nlet _waitUntilWarned = false;\n\n/**\n * Register a promise to be kept alive after the response is sent.\n * Maps to `ctx.waitUntil()` on Cloudflare Workers and similar platforms.\n *\n * The platform adapter installs a per-request waitUntil function via ALS\n * (see waituntil-bridge.ts). If no ALS handler is available, a warning\n * is logged once and the promise is left to resolve (or reject) without\n * being tracked.\n *\n * @param promise - The background work to keep alive.\n */\nexport function waitUntil(promise: Promise<unknown>): void {\n const alsFn = _getWaitUntil();\n if (alsFn) {\n alsFn(promise);\n return;\n }\n\n if (!_waitUntilWarned) {\n _waitUntilWarned = true;\n console.warn(\n '[timber] waitUntil() is not supported by the current adapter. ' +\n 'Background work will not be tracked. This warning is shown once.'\n );\n }\n}\n\n/**\n * Reset the waitUntil warning state. Exported for testing only.\n * @internal\n */\nexport function _resetWaitUntilWarning(): void {\n _waitUntilWarned = false;\n}\n","/**\n * FormData preprocessing — schema-agnostic conversion of FormData to typed objects.\n *\n * FormData is all strings. Schema validation expects typed values. This module\n * bridges the gap with intelligent coercion that runs *before* schema validation.\n *\n * Inspired by zod-form-data, but schema-agnostic — works with any Standard Schema\n * library (Zod, Valibot, ArkType).\n *\n * See design/08-forms-and-actions.md §\"parseFormData() and coerce helpers\"\n */\n\n// ─── parseFormData ───────────────────────────────────────────────────────\n\n/**\n * Convert FormData into a plain object with intelligent coercion.\n *\n * Handles:\n * - **Duplicate keys → arrays**: `tags=js&tags=ts` → `{ tags: [\"js\", \"ts\"] }`\n * - **Nested dot-paths**: `user.name=Alice` → `{ user: { name: \"Alice\" } }`\n * - **Indexed lists → arrays**: `rows.0.name=A&rows.1.name=B` →\n * `{ rows: [{ name: \"A\" }, { name: \"B\" }] }`, when the indexes are exactly\n * `0..n-1`. A list with a gap stays an object keyed by index.\n * - **Empty strings stay `\"\"`**: a blank text input is `\"\"`, so\n * `z.string().min(1, 'Required')` reports its own message. Use\n * `coerce.text` to make a blank optional field `undefined`\n * - **Empty Files → undefined**: File inputs with no selection become `undefined`\n * - **Strips `$ACTION_*` fields**: React's internal hidden fields are excluded\n * - **Drops `__proto__` paths and names deeper than 32 segments**\n *\n * A field's shape follows its count: a name sent once is a scalar, several\n * times an array, never at all absent. A `createActionClient` action with a\n * schema then gives every field the schema declares as a list one shape\n * (`normalizeListFields` in `schema-introspection.ts`). A raw call, and a raw\n * `'use server'` action that calls this itself, keep the count-dependent\n * shape.\n */\nexport function parseFormData(formData: FormData): Record<string, unknown> {\n const flat: Record<string, unknown> = {};\n\n for (const key of new Set(formData.keys())) {\n // Skip React internal fields\n if (key.startsWith('$ACTION_')) continue;\n\n // Skip prototype-pollution keys at the top level — assigning to\n // `flat['__proto__']` invokes the prototype setter and can splice\n // attacker-controlled data into `flat`'s prototype chain.\n // The dot-path case is filtered separately in `expandDotPaths`.\n if (DANGEROUS_KEYS.has(key)) continue;\n\n const values = formData.getAll(key);\n const processed = values.map(normalizeValue);\n\n if (processed.length === 1) {\n flat[key] = processed[0];\n } else {\n // Filter out undefined (empty Files) and empty strings from multi-value fields.\n // Multi-value fields (e.g. tags=js&tags=&tags=ts) should not include blanks.\n flat[key] = processed.filter((v) => v !== undefined && v !== '');\n }\n }\n\n // Expand dot-notation paths into nested objects\n return expandDotPaths(flat);\n}\n\n/**\n * Normalize a single FormData entry value.\n * - Empty File objects (no selection) → undefined\n * - Strings pass through as-is (empty strings stay as empty strings so\n * schema validators like `z.string().min(1, 'Required')` can produce\n * their custom error messages instead of a generic type mismatch)\n * - Everything else passes through as-is\n */\nfunction normalizeValue(value: FormDataEntryValue): unknown {\n // File input with no selection: browsers submit a File with name=\"\" and size=0\n if (value instanceof File && value.size === 0 && value.name === '') {\n return undefined;\n }\n\n return value;\n}\n\n/**\n * Expand dot-notation keys into nested objects.\n * `{ \"user.name\": \"Alice\", \"user.age\": \"30\" }` → `{ user: { name: \"Alice\", age: \"30\" } }`\n *\n * Keys without dots are left as-is. Bracket notation (e.g. `items[0]`) is NOT\n * supported — use dot notation (`items.0`) instead.\n */\nfunction expandDotPaths(flat: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n let hasDotPaths = false;\n\n // First pass: check if any keys have dots\n for (const key of Object.keys(flat)) {\n if (key.includes('.')) {\n hasDotPaths = true;\n break;\n }\n }\n\n // Fast path: no dot-notation keys, return as-is.\n // Top-level dangerous keys are already filtered in `parseFormData` above.\n if (!hasDotPaths) return flat;\n\n for (const [key, value] of Object.entries(flat)) {\n // Reject any path that contains __proto__ / constructor / prototype.\n // Without this, `__proto__.x=1` writes to Object.prototype because\n // `result['__proto__']` resolves to the prototype object itself.\n const parts = key.split('.');\n if (parts.some((p) => DANGEROUS_KEYS.has(p))) continue;\n // Bound the nesting depth. Every walk over the parsed value recurses\n // once per level (list conversion here, then file and sensitive-field\n // stripping and schema validation), and a 10 KB key of 5,000 segments\n // fits well inside the body limits. No form nests this deep.\n if (parts.length > MAX_PATH_DEPTH) continue;\n\n if (parts.length === 1) {\n result[parts[0]] = value;\n continue;\n }\n\n let current: Record<string, unknown> = result;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n // Step only into an object this walk built. Anything else under the\n // name — a string, a File, or an array from a duplicate key\n // (`rows=x&rows=y`) — is replaced: the dot-path takes precedence.\n // Stepping into an array would let `rows.4294967294` set its length\n // to 2^32 - 1, and every later walk (file and sensitive-field\n // stripping) maps over that length (TIM-1573).\n if (!isPlainObject(current[part])) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]] = value;\n }\n\n // The top level is always an object: it is the form, not a list.\n for (const [key, value] of Object.entries(result)) {\n if (isPlainObject(value)) result[key] = indexedListsToArrays(value);\n }\n return result;\n}\n\n/**\n * `node`, with every nested object whose keys are exactly `\"0\"..\"n-1\"`\n * turned into an array, depth first. Only a dense, canonical index set\n * converts: `{ \"0\", \"2\" }` (a gap), `{ \"01\" }` and `{ \"0\", \"name\" }` stay\n * objects. So a forged `rows.99999` stays one key instead of allocating a\n * sparse array, and the array's length is bounded by the field count limit.\n *\n * Object.keys lists integer-like keys first, in ascending order, so a dense\n * set reads as `0, 1, … n-1` and `Object.values` is already in index order.\n */\nfunction indexedListsToArrays(node: Record<string, unknown>): Record<string, unknown> | unknown[] {\n for (const [key, value] of Object.entries(node)) {\n if (isPlainObject(value)) node[key] = indexedListsToArrays(value);\n }\n const keys = Object.keys(node);\n const dense = keys.length > 0 && keys.every((key, i) => key === String(i));\n return dense ? Object.values(node) : node;\n}\n\n/** An object the dot-path walk built — not an array, File or other instance. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\n// `__proto__` is the only key in this parser that escapes the dot-path\n// walk's `typeof !== 'object'` reset: accessing `obj['__proto__']` returns\n// `Object.prototype` (itself an object), so the walk steps into the global\n// prototype and the leaf write mutates it. `constructor` resolves to a\n// function (reset fires) and `prototype` is undefined on fresh objects\n// (reset fires), so neither escapes the walk — they parse as legit nested\n// keys and do not mutate anything global.\nconst DANGEROUS_KEYS = new Set(['__proto__']);\n\n/**\n * The most segments a dot-path field name may have. A deeper name is dropped,\n * like a `__proto__` path, so no walk over the parsed value can exhaust the\n * stack (TIM-1573).\n */\nconst MAX_PATH_DEPTH = 32;\n\n// ─── Coercion Helpers ────────────────────────────────────────────────────\n\n/**\n * Schema-agnostic coercion primitives for common FormData patterns.\n *\n * These are plain transform functions — they compose with any schema library's\n * `transform`/`preprocess` pipeline. In Zod, use `z.preprocess`: it runs on an\n * absent key (an unchecked checkbox), where `z.unknown().transform()` fails\n * with \"expected nonoptional\" before the transform runs.\n *\n * ```ts\n * // Zod\n * z.preprocess(coerce.number, z.number())\n * // Valibot\n * v.pipe(v.unknown(), v.transform(coerce.number), v.number())\n * ```\n */\nexport const coerce = {\n /**\n * Coerce an empty string to undefined for optional text fields.\n * Use with `.optional()` schemas where an empty input means \"not provided\".\n *\n * ```ts\n * // Zod — preprocess, not `z.unknown().transform(…)`: Zod 4 rejects an\n * // absent key before a transform runs (\"expected nonoptional\")\n * z.preprocess(coerce.text, z.string().optional())\n * // Valibot\n * v.pipe(v.unknown(), v.transform(coerce.text), v.optional(v.string()))\n * ```\n */\n text(value: unknown): string | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value === 'string') return value;\n return undefined;\n },\n\n /**\n * Coerce a string to a number.\n * - `\"42\"` → `42`\n * - `\"3.14\"` → `3.14`\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Non-numeric strings → `undefined` (schema validation will catch this)\n */\n number(value: unknown): number | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value === 'number') return value;\n if (typeof value !== 'string') return undefined;\n const num = Number(value);\n if (Number.isNaN(num)) return undefined;\n return num;\n },\n\n /**\n * Coerce a checkbox value to a boolean.\n * HTML checkboxes submit \"on\" when checked and are absent when unchecked.\n * - `\"on\"` / any truthy string → `true`\n * - `undefined` / `null` / `\"\"` → `false`\n */\n checkbox(value: unknown): boolean {\n if (value === undefined || value === null || value === '') return false;\n if (typeof value === 'boolean') return value;\n // Any non-empty string (typically \"on\") is true\n return typeof value === 'string' && value.length > 0;\n },\n\n /**\n * Parse a JSON string into an object.\n * - Valid JSON string → parsed object\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Invalid JSON → `undefined` (schema validation will catch this)\n */\n json(value: unknown): unknown {\n if (value === undefined || value === null || value === '') return undefined;\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n },\n\n /**\n * Coerce a date string to a Date object.\n * Handles `<input type=\"date\">` (`\"2024-01-15\"`), `<input type=\"datetime-local\">`\n * (`\"2024-01-15T10:30\"`), and full ISO 8601 strings.\n * - Valid date string → `Date`\n * - `\"\"` / `undefined` / `null` → `undefined`\n * - Invalid date strings → `undefined` (schema validation will catch this)\n * - Impossible dates that `new Date()` silently normalizes (e.g. Feb 31) → `undefined`\n */\n date(value: unknown): Date | undefined {\n if (value === undefined || value === null || value === '') return undefined;\n if (value instanceof Date) return value;\n if (typeof value !== 'string') return undefined;\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return undefined;\n\n // Overflow detection: extract Y/M/D from the input string and verify\n // they match the parsed Date components. new Date('2024-02-31') silently\n // normalizes to March 2nd — we reject such inputs.\n const ymdMatch = value.match(/^(\\d{4})-(\\d{2})-(\\d{2})/);\n if (ymdMatch) {\n const inputYear = Number(ymdMatch[1]);\n const inputMonth = Number(ymdMatch[2]);\n const inputDay = Number(ymdMatch[3]);\n\n // Use UTC methods for date-only and Z-suffixed strings to avoid\n // timezone offset shifting the day. For datetime-local (no Z suffix),\n // the Date constructor parses in local time, so use local methods.\n const isUTC = value.length === 10 || value.endsWith('Z');\n const parsedYear = isUTC ? date.getUTCFullYear() : date.getFullYear();\n const parsedMonth = isUTC ? date.getUTCMonth() + 1 : date.getMonth() + 1;\n const parsedDay = isUTC ? date.getUTCDate() : date.getDate();\n\n if (inputYear !== parsedYear || inputMonth !== parsedMonth || inputDay !== parsedDay) {\n return undefined;\n }\n }\n\n return date;\n },\n\n /**\n * Create a File coercion function with optional size and mime type validation.\n * Returns the File if valid, `undefined` otherwise.\n *\n * ```ts\n * // Basic — just checks it's a real File\n * z.preprocess(coerce.file(), z.instanceof(File))\n *\n * // With constraints\n * z.preprocess(\n * coerce.file({ maxSize: 5 * 1024 * 1024, accept: ['image/png', 'image/jpeg'] }),\n * z.instanceof(File)\n * )\n * ```\n */\n file(options?: { maxSize?: number; accept?: string[] }): (value: unknown) => File | undefined {\n return (value: unknown): File | undefined => {\n if (value === undefined || value === null || value === '') return undefined;\n if (!(value instanceof File)) return undefined;\n\n // Empty file input (no selection): browsers submit File with name=\"\" and size=0\n if (value.size === 0 && value.name === '') return undefined;\n\n if (options?.maxSize !== undefined && value.size > options.maxSize) {\n return undefined;\n }\n\n if (options?.accept !== undefined && !options.accept.includes(value.type)) {\n return undefined;\n }\n\n return value;\n };\n },\n};\n","/**\n * Server action primitives: revalidatePath, revalidateTag, and the action handler.\n *\n * - revalidatePath(path) re-renders the route at that path and returns the RSC\n * flight payload for inline reconciliation. Server actions only.\n * - revalidateTag(tag) invalidates timber.cache entries by tag. Callable from\n * any server code: deferred to the end of the action inside one, immediate\n * anywhere else.\n *\n * The action handler processes incoming action requests, validates CSRF,\n * enforces body limits, executes the action, and returns the response\n * (with piggybacked RSC payload if revalidatePath was called).\n *\n * See design/08-forms-and-actions.md\n */\n\nimport { cache } from '../cache/cache-api.ts';\nimport { canonicalize } from './canonicalize.ts';\nimport { isDenySignal, isRedirectSignal } from './signal-identity.ts';\nimport { withSpan } from './tracing.ts';\nimport { revalidationAls, type RevalidationState } from './als-registry.ts';\nimport type { ReactCacheScope } from './react-cache-scope.ts';\n// ─── Types ───────────────────────────────────────────────────────────────\n\n/** Result of rendering a revalidation — payload root before RSC serialization. */\nexport interface RevalidationResult {\n /**\n * The payload root — tree plus the params it rendered with, exactly as an\n * ordinary route payload. The client splits it in `applyActionResult`.\n */\n payload: unknown;\n /**\n * The `React.cache` scope the target route's middleware ran in. The\n * revalidated tree renders in it, so middleware, access.ts and components\n * share one scope — fresh, never the action body's (TIM-1529).\n */\n reactCacheScope: ReactCacheScope;\n}\n\n/** Renderer function that builds a React element tree for a given path. */\nexport type RevalidateRenderer = (path: string) => Promise<RevalidationResult>;\n\n/**\n * Thrown by a `RevalidateRenderer` that decided not to render: the path\n * was rejected, its params failed coercion, or its middleware answered\n * with a `Response` that cannot become an element tree. `executeAction`\n * drops the revalidation — the action result is still delivered, with no\n * `_tree` piggybacked — and, because the drop was a decision, does not\n * return it as an error to report. Identified by `instanceof`, so the\n * message text never reaches clients.\n */\nexport class RevalidationDropped extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'RevalidationDropped';\n }\n}\n\n// Re-export the type from the registry for public API consumers.\nexport type { RevalidationState } from './als-registry.ts';\n\n/** Options for creating the action handler. */\nexport interface ActionHandlerConfig {\n /** Renderer for producing RSC payloads during revalidation. */\n renderer?: RevalidateRenderer;\n /**\n * Pathname of the page the action was submitted from. When set,\n * revalidatePath renders are skipped for non-matching paths — the\n * server cache is already invalidated, so the next navigation fetches\n * fresh data. See TIM-1454.\n */\n requestPathname?: string;\n /** Search string of the action request URL (e.g. `?page=1`). */\n requestSearch?: string;\n}\n\n/** Result of handling a server action request. */\nexport interface ActionHandlerResult {\n /** The action's return value (serialized). */\n actionResult: unknown;\n /** Revalidation result if revalidatePath was called (element tree, not yet serialized). */\n revalidation?: RevalidationResult;\n /**\n * True when `revalidatePath()` was called only for pages other than the\n * current one (TIM-1454). The client then evicts its caches and skips the\n * refresh — nothing on screen was named. Whenever the current page was\n * named this is false, even if other pages were named too: its re-render,\n * or the refresh that replaces a dropped one, re-renders every layout it\n * shares with them. Which paths were named is not reported: the client\n * evicts every cached payload after any revalidation (TIM-1476), so a path\n * list would carry nothing it acts on (TIM-1461).\n */\n onlyOtherPagesNamed: boolean;\n /** Redirect location if a RedirectSignal was thrown during revalidation. */\n redirectTo?: string;\n /** Redirect status code. */\n redirectStatus?: number;\n /**\n * Errors the action survived after its body returned: a `revalidateTag`\n * invalidation that rejected, or a `revalidatePath` render that threw.\n * Each is already logged. They are returned rather than reported here\n * because reporting needs the request, which the caller owns; the caller\n * passes each to `onRequestError` once.\n */\n revalidationErrors: unknown[];\n}\n\n// ─── Revalidation State ──────────────────────────────────────────────────\n\n// Per-request revalidation state stored in AsyncLocalStorage (from als-registry.ts).\n// This ensures concurrent requests never share or overwrite each other's state\n// (the previous module-level global was vulnerable to cross-request pollution).\n\n/**\n * Run `fn` inside a revalidation ALS scope.\n * @internal — for tests that call revalidatePath/Tag directly without executeAction().\n */\nexport function _runWithRevalidationState<T>(state: RevalidationState, fn: () => T): T {\n return revalidationAls.run(state, fn);\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────\n\n/**\n * Re-render the route at `path` and include the RSC flight payload in the\n * action response. The client reconciles inline — no separate fetch needed.\n *\n * Only callable inside a server action: it attaches a render to the action\n * response, and nothing else has one. To refresh cached data from a\n * `route.ts` handler, a webhook, or a job, use `revalidateTag()` or\n * `cache.invalidate()`.\n *\n * @param path - The path to re-render (e.g. '/dashboard', '/todos').\n */\nexport function revalidatePath(path: string): void {\n const state = revalidationAls.getStore();\n if (!state || state.closed) {\n throw new Error(\n 'revalidatePath() can only be called inside a server action: it re-renders ' +\n 'the route into the action response, and there is no action response here. ' +\n 'To refresh cached data from a route handler or other server code, call ' +\n 'revalidateTag() or cache.invalidate() for the tags the route reads.'\n );\n }\n if (!state.paths.includes(path)) {\n state.paths.push(path);\n }\n}\n\n/**\n * Invalidate all timber.cache entries tagged with `tag`, and tombstone the\n * pre-rendered component seeds that carry it.\n * Does not return a payload — the next request for an invalidated entry re-executes.\n *\n * Callable from any server code. Inside a server action the invalidation is\n * deferred until the action body returns, so a `revalidatePath()` render in\n * the same action reads fresh data; the returned promise resolves at once.\n * Anywhere else — a `route.ts` webhook, a job, or background work an action\n * started that runs after the action body returned — it is\n * `cache.invalidate({ tag })`, and the promise settles when the invalidation\n * has. Await it before responding.\n *\n * @param tag - The cache tag to invalidate (e.g. 'products', 'user:123').\n */\nexport function revalidateTag(tag: string): Promise<void> {\n const state = revalidationAls.getStore();\n if (!state || state.closed) return cache.invalidate({ tag });\n if (!state.tags.includes(tag)) {\n state.tags.push(tag);\n }\n return Promise.resolve();\n}\n\n// ─── Action Handler ──────────────────────────────────────────────────────\n\n/**\n * Execute a server action and process revalidation.\n *\n * 1. Sets up revalidation state\n * 2. Calls the action function\n * 3. Processes revalidateTag calls (invalidates cache entries)\n * 4. Processes revalidatePath calls (re-renders and captures RSC payload)\n * 5. Returns the action result + optional RSC payload\n *\n * @param actionFn - The server action function to execute.\n * @param args - Arguments to pass to the action.\n * @param config - Handler configuration (cache handler, renderer).\n */\nexport async function executeAction(\n actionFn: (...args: unknown[]) => Promise<unknown>,\n args: unknown[],\n config: ActionHandlerConfig = {},\n spanMeta?: { actionFile?: string; actionName?: string }\n): Promise<ActionHandlerResult> {\n const state: RevalidationState = { paths: [], tags: [] };\n const revalidationErrors: unknown[] = [];\n let actionResult: unknown;\n let redirectTo: string | undefined;\n let redirectStatus: number | undefined;\n\n // Run the action inside ALS scope so revalidatePath/Tag resolve to this\n // request's state object — concurrent requests each get their own scope.\n await revalidationAls.run(state, async () => {\n try {\n actionResult = await withSpan(\n 'timber.action',\n {\n ...(spanMeta?.actionFile ? { 'timber.action_file': spanMeta.actionFile } : {}),\n ...(spanMeta?.actionName ? { 'timber.action_name': spanMeta.actionName } : {}),\n },\n () => actionFn(...args)\n );\n } catch (error) {\n if (isRedirectSignal(error)) {\n redirectTo = error.location;\n redirectStatus = error.status;\n } else {\n throw error;\n }\n } finally {\n // From here `paths` and `tags` are snapshotted below (or abandoned on\n // a throw); later calls from un-awaited work must not queue into them.\n state.closed = true;\n }\n });\n\n // Process tag invalidation through cache.invalidate so it records the\n // invalidation epoch — an in-flight cached fn must not re-store data this\n // mutation just invalidated (TIM-1028). cache.invalidate resolves the\n // module-level handler singleton: setCacheHandler() is called at boot from\n // rsc-entry when timber.config.ts provides a cacheHandler; otherwise falls\n // back to in-memory LRU (TIM-599).\n if (state.tags.length > 0) {\n // cache.invalidate handles both data-cache clearing AND component-seed\n // tombstone writes (design/45 §ISR mechanics) — no separate tombstone\n // step needed here.\n // Best-effort: the action body already executed and its mutation committed.\n // Use allSettled so all tags settle before proceeding — Promise.all would\n // short-circuit on the first rejection, leaving other invalidations (including\n // component-seed tombstone writes) in-flight during revalidatePath rendering.\n const results = await Promise.allSettled(state.tags.map((tag) => cache.invalidate({ tag })));\n for (const r of results) {\n if (r.status === 'rejected') {\n console.error('[timber] revalidateTag invalidation failed:', r.reason);\n revalidationErrors.push(r.reason);\n }\n }\n }\n\n // Process path revalidation — build element tree (not yet serialized).\n //\n // TIM-1454: Only a path that matches the current page is rendered. When\n // every call names another page, `onlyOtherPagesNamed` tells the client to\n // evict its caches instead. The matching path is looked for across every\n // call, not just the first: an action that calls revalidatePath('/other')\n // and then revalidatePath('/current') must still re-render the current\n // page (TIM-1461).\n let revalidation: RevalidationResult | undefined;\n const { requestPathname, requestSearch } = config;\n const isCurrentPage = (path: string) =>\n !requestPathname || revalidationPathMatches(path, requestPathname, requestSearch);\n const path = state.paths.find(isCurrentPage);\n const onlyOtherPagesNamed = state.paths.length > 0 && path === undefined;\n\n if (path !== undefined && config.renderer) {\n try {\n revalidation = await config.renderer(path);\n } catch (renderError) {\n if (isRedirectSignal(renderError)) {\n redirectTo = renderError.location;\n redirectStatus = renderError.status;\n } else if (isDenySignal(renderError)) {\n console.error(\n `[timber] revalidatePath dropped — target middleware denied (status ${renderError.status})`\n );\n } else if (renderError instanceof RevalidationDropped) {\n console.error(`[timber] ${renderError.message}`);\n } else {\n console.error('[timber] revalidatePath render failed:', renderError);\n revalidationErrors.push(renderError);\n }\n }\n }\n\n return {\n actionResult,\n revalidation,\n onlyOtherPagesNamed,\n revalidationErrors,\n ...(redirectTo ? { redirectTo, redirectStatus } : {}),\n };\n}\n\n/**\n * Check if a `revalidatePath(path)` argument matches the request pathname.\n * Canonicalizes the revalidated path the same way the renderer does so\n * equivalent paths compare equal. Returns true when the paths match or\n * when comparison is inconclusive (validation failure → render to be safe).\n */\nfunction revalidationPathMatches(\n revalidatedPath: string,\n requestPathname: string,\n requestSearch?: string\n): boolean {\n const hashIdx = revalidatedPath.indexOf('#');\n const noFragment = hashIdx >= 0 ? revalidatedPath.slice(0, hashIdx) : revalidatedPath;\n const queryIdx = noFragment.indexOf('?');\n const pathnameOnly = queryIdx >= 0 ? noFragment.slice(0, queryIdx) : noFragment;\n const search = queryIdx >= 0 ? noFragment.slice(queryIdx) : '';\n const canonical = canonicalize(pathnameOnly, true);\n if (!canonical.ok) return true;\n if (canonical.pathname !== requestPathname) return false;\n // revalidatePath('/dashboard') (no search) matches any query variant.\n // revalidatePath('/dashboard?tab=x') only matches that exact search.\n if (search && search !== (requestSearch ?? '')) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,SAAgB,wBAAyC;CACvD,uBAAO,IAAI,IAAI;AACjB;;;;;;;;;;;AAYA,SAAgB,uBACd,IACA,QAAyB,sBAAsB,GAC5C;CACH,OAAO,mBAAmB,IAAI,OAAO,EAAE;AACzC;;;;;;;;;;;AAYA,SAAgB,0BAA6B,IAAgB;CAC3D,OAAO,mBAAmB,KAAK,EAAE;AACnC;AAgBA,IAAM,8BAAc,IAAI,QAAsC;AAC9D,IAAM,+BAAe,IAAI,QAAyB;;;;;;AAOlD,SAAgB,4BAA4B,MAAoB;C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M,OAAO,SAAS,IAAI;CAC3C,SAAS,aAAa;EACpB,IAAI,iBAAiB,WAAW,GAAG;GACjC,aAAa,YAAY;GACzB,iBAAiB,YAAY;EAC/B,OAAO,IAAI,aAAa,WAAW,GACjC,QAAQ,MACN,sEAAsE,YAAY,OAAO,EAC3F;OACK,IAAI,uBAAuB,qBAChC,QAAQ,MAAM,YAAY,YAAY,SAAS;OAC1C;GACL,QAAQ,MAAM,0CAA0C,WAAW;GACnE,mBAAmB,KAAK,WAAW;EACrC;CACF;CAGF,OAAO;EACL;EACA;EACA;EACA;EACA,GAAI,aAAa;GAAE;GAAY;EAAe,IAAI,CAAC;CACrD;AACF;;;;;;;AAQA,SAAS,wBACP,iBACA,iBACA,eACS;CACT,MAAM,UAAU,gBAAgB,QAAQ,GAAG;CAC3C,MAAM,aAAa,WAAW,IAAI,gBAAgB,MAAM,GAAG,OAAO,IAAI;CACtE,MAAM,WAAW,WAAW,QAAQ,GAAG;CACvC,MAAM,eAAe,YAAY,IAAI,WAAW,MAAM,GAAG,QAAQ,IAAI;CACrE,MAAM,SAAS,YAAY,IAAI,WAAW,MAAM,QAAQ,IAAI;CAC5D,MAAM,YAAY,aAAa,cAAc,IAAI;CACjD,IAAI,CAAC,UAAU,IAAI,OAAO;CAC1B,IAAI,UAAU,aAAa,iBAAiB,OAAO;CAGnD,IAAI,UAAU,YAAY,iBAAiB,KAAK,OAAO;CACvD,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as formatChains } from "./chains-IswOWMnq.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"convention-lint-BfC_dAhZ.js","names":[],"sources":["../../src/routing/segment-codegen.ts","../../src/routing/codegen-write.ts","../../src/shared/route-options-export.ts","../../src/routing/route-options.ts","../../src/routing/route-options-lint.ts","../../src/routing/convention-lint.ts"],"sourcesContent":["/**\n * $segment type generation and directory-to-route mapping.\n *\n * Generates per-route $segment.d.ts files in .timber/types/ that mirror\n * the app/ directory structure. TypeScript's rootDirs feature makes these\n * importable as './$segment' from route files.\n *\n * Design doc: design/41-global-params.md §The $segment Module\n */\n\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree, SegmentNode } from './types.ts';\n\n/** Info carried per directory for type generation. */\nexport interface SegmentInfo {\n /** The URL route pattern (groups and slots stripped). e.g. '/[artistSlug]/[year]' */\n route: string;\n /** The full tree path including groups and slots — uniquely identifies a segment.\n * e.g. '/(browse)/[artistSlug]/@shows/[year]' */\n segmentPath: string;\n}\n\n/**\n * Build a map of absolute filesystem directory → segment info.\n * Used by resolveId to map a $segment import's importer to the correct route,\n * and by writeSegmentTypes to generate per-route $segment.d.ts files.\n *\n * Walks every segment (not just leaves) so layouts and middleware\n * at any depth can import $segment.\n */\nexport function buildDirToRouteMap(tree: RouteTree, appDir: string): Map<string, SegmentInfo> {\n const map = new Map<string, SegmentInfo>();\n\n function walk(node: SegmentNode, fsPath: string, treePath: string): void {\n map.set(fsPath, {\n route: node.urlPath || '/',\n segmentPath: treePath || '/',\n });\n\n for (const child of node.children) {\n const childDir = join(fsPath, child.segmentName);\n const childTreePath = `${treePath}/${child.segmentName}`;\n walk(child, childDir, childTreePath);\n }\n for (const [slotName, slotNode] of Object.entries(node.slots)) {\n const slotDir = join(fsPath, `@${slotName}`);\n const slotTreePath = `${treePath}/@${slotName}`;\n walk(slotNode, slotDir, slotTreePath);\n }\n }\n\n walk(tree.root, appDir, '');\n return map;\n}\n\n/**\n * Generate the full $segment.d.ts content for a segment.\n */\nexport function generateSegmentDts(info: SegmentInfo): string {\n return [\n `export const ROUTE: '${info.route}';`,\n `export const SEGMENT_PATH: '${info.segmentPath}';`,\n '',\n ].join('\\n');\n}\n\n/**\n * Generate per-route $segment.d.ts files in .timber/types/ mirroring\n * the app/ directory structure. These files are importable via TypeScript's\n * rootDirs feature.\n */\nexport async function writeSegmentTypes(\n routeTree: RouteTree,\n appDir: string,\n root: string\n): Promise<void> {\n // Compute the relative prefix from project root to appDir.\n // e.g. if appDir is /project/src/app, relative is 'src/app'\n const relative = appDir.slice(root.length + 1);\n const typesBase = join(root, '.timber', 'types', relative);\n const map = buildDirToRouteMap(routeTree, appDir);\n\n const writes: Promise<void>[] = [];\n for (const [fsDir, info] of map) {\n // Mirror the app/ structure under .timber/types/\n const relDir = fsDir.slice(appDir.length); // e.g. '/[artistSlug]/[year]'\n const segmentDir = join(typesBase, relDir);\n const segmentFile = join(segmentDir, '$segment.d.ts');\n const content = generateSegmentDts(info);\n\n writes.push(\n mkdir(segmentDir, { recursive: true }).then(() => writeFileAtomic(segmentFile, content))\n );\n }\n\n await Promise.all(writes);\n}\n","/**\n * Route-map codegen writer.\n *\n * Materializes the generated route types on disk: `.timber/timber-routes.d.ts`,\n * `.timber/segment-types.d.ts` (via `writeSegmentTypes`), and the root\n * `timber-env.d.ts` that references them.\n *\n * Lives outside `plugins/routing.ts` because it has two callers with two\n * different failure policies: the dev/build plugin starts the write off the hot\n * path and logs failures, while `timber check` awaits it and treats a failure as\n * fatal — a type check run against absent or stale route types reports errors\n * about code that is fine. One implementation, two policies, so the bytes on\n * disk cannot drift between the two commands.\n *\n * Design docs: 09-typescript.md §\"Typed Routes\", 18-build-system.md\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { generateRouteMap } from './codegen.ts';\nimport { writeSegmentTypes } from './segment-codegen.ts';\nimport { writeFileAtomic } from '../utils/write-file-atomic.ts';\nimport type { RouteTree } from './types.ts';\n\n/**\n * Path (relative to the project root) of the generated route map declaration\n * file, and the name of the root file that `/// <reference>`s it.\n *\n * Exported because `timber check` has to answer whether the user's tsconfig\n * pulls these into the program — a question about these exact paths. It derives\n * them from here rather than restating them, so a rename cannot leave the check\n * looking for a file nothing writes.\n */\nexport const CODEGEN_OUTPUT = '.timber/timber-routes.d.ts';\n\n/** Root-level file that references the generated declarations. */\nexport const ENV_DTS_FILENAME = 'timber-env.d.ts';\n\n/**\n * Content of the timber-env.d.ts file written to the project root.\n *\n * Uses a triple-slash reference so TypeScript auto-discovers the generated\n * route map without the user needing to edit tsconfig.json — same pattern\n * as Next.js's next-env.d.ts.\n *\n * Also references `vite/client` so side-effect imports like\n * `import './globals.css'` type-check without ts(2882), and so\n * `import.meta.env`, `import.meta.hot`, `import.meta.glob`, asset\n * imports (`*.png`, `*.svg`, …), CSS modules, and `?url`/`?raw`/\n * `?inline` query variants all resolve without the user editing\n * tsconfig.json themselves. Next.js's next-env.d.ts plays the same\n * role via `next/types/global`.\n *\n * `vite` is a peer dep of `@timber-js/app`, so the reference always\n * resolves in a correctly-installed project.\n */\nconst TIMBER_ENV_DTS = [\n '// This file is auto-generated by timber.js. Do not edit.',\n '// It ensures TypeScript picks up the generated route types and',\n '// Vite-provided ambient types (CSS, assets, import.meta.env, HMR).',\n '/* eslint-disable @typescript-eslint/triple-slash-reference */',\n '/// <reference path=\".timber/timber-routes.d.ts\" />',\n '/// <reference types=\"vite/client\" />',\n '/// <reference types=\"react/canary\" />',\n '/// <reference types=\"react-dom/canary\" />',\n '',\n].join('\\n');\n\n/**\n * Codegen writes that have been started but have not yet landed on disk.\n *\n * `writeRouteCodegen` is deliberately unawaited on the dev/build hot path,\n * which leaves that caller no way to know the files exist yet. Anything that\n * tears down the project root — a build process exiting, a test removing its\n * temp root — then races the writes: `rmSync` empties a directory that a\n * pending `mkdir` immediately recreates, and the removal fails with ENOTEMPTY.\n *\n * Every started write registers here and deregisters when it settles, so\n * `flushCodegenWrites()` can await them instead of guessing at a delay.\n */\nconst pendingCodegenWrites = new Set<Promise<void>>();\n\n/**\n * Resolve once every codegen write started so far has landed on disk.\n *\n * Safe to call at any time and from anywhere — writes are tracked per process,\n * not per plugin instance, so a caller does not need a handle on the plugin\n * that started them. Never rejects: the tracked copy of each write has its\n * rejection swallowed, so a failing write cannot turn a teardown barrier into\n * an unhandled rejection. Callers that care about failure await the promise\n * `writeRouteCodegen` returned instead.\n */\nexport async function flushCodegenWrites(): Promise<void> {\n // Loop rather than a single Promise.all: a write started while we were\n // awaiting would otherwise be missed, and the set would still be non-empty\n // on return.\n //\n // Each round drops what it awaited rather than trusting the per-write\n // `finally` to have run, so the two removal paths are independent — a\n // deregistration that stopped firing would leak memory in dev, but it can\n // never turn this into a spin.\n while (pendingCodegenWrites.size > 0) {\n const inFlight = [...pendingCodegenWrites];\n await Promise.all(inFlight);\n for (const write of inFlight) pendingCodegenWrites.delete(write);\n }\n}\n\n/**\n * Write the generated route map, segment types, and the timber-env.d.ts\n * reference file for `tree`.\n *\n * Returns a promise that **rejects** if any write fails. The dev/build plugin\n * does not await it (types are a developer convenience there, not a runtime\n * dependency) and logs instead; `timber check` awaits it and fails the command.\n * Either way the write is registered with `flushCodegenWrites()`.\n */\n/**\n * Write `timber-env.d.ts` only when its content differs.\n *\n * Its content is constant per timber version, so almost every call is a no-op\n * — and a file that is not rewritten cannot be read half-written. It is not\n * replaced atomically because it lives in the user's project root, often\n * committed: a rename would turn a symlink into a regular file, reset its\n * permissions, and a process killed mid-write would leave a temp file next to\n * their source. The in-place write happens only on first run or a timber\n * upgrade.\n */\nasync function writeEnvDts(envPath: string): Promise<void> {\n const existing = await readFile(envPath, 'utf-8').catch(() => null);\n if (existing !== TIMBER_ENV_DTS) await writeFile(envPath, TIMBER_ENV_DTS, 'utf-8');\n}\n\nexport function writeRouteCodegen(tree: RouteTree, appDir: string, root: string): Promise<void> {\n const timberDir = join(root, '.timber');\n const content = generateRouteMap(tree, { appDir, outputDir: timberDir });\n const routesPath = join(root, CODEGEN_OUTPUT);\n const envPath = join(root, ENV_DTS_FILENAME);\n\n const done = mkdir(timberDir, { recursive: true })\n .then(() =>\n // The type checker can read these while they are being rewritten — an\n // editor's TS server during `timber dev`, a `tsgo` run during `vite\n // build`. A truncating write shows it an empty route map for the length\n // of the write, and every typed route degrades to `any` (TIM-1562).\n // The generated files under `.timber/` are replaced atomically.\n Promise.all([\n writeFileAtomic(routesPath, content),\n writeEnvDts(envPath),\n writeSegmentTypes(tree, appDir, root),\n ])\n )\n .then(() => undefined);\n\n // The tracked copy swallows rejection so `flushCodegenWrites` — a teardown\n // barrier — never rejects and never leaves an unhandled rejection behind.\n // The returned promise keeps its rejection for callers that want it.\n const tracked = done.catch(() => undefined);\n pendingCodegenWrites.add(tracked);\n void tracked.finally(() => pendingCodegenWrites.delete(tracked));\n\n return done;\n}\n","/**\n * The export a layout or page declares its options under (design/53\n * §\"Route-module options\"). One table for both readers: the build-time source\n * reader (`routing/route-options.ts`) and the runtime module loader\n * (`server/route-module-loader.ts`), which cannot import the source reader\n * because it pulls in `node:fs` and Vite's parser.\n */\n\nexport type RouteOptionsKind = 'layout' | 'page';\n\nexport const ROUTE_OPTIONS_EXPORT = {\n layout: 'layoutOptions',\n page: 'pageOptions',\n} as const satisfies Record<RouteOptionsKind, string>;\n","/**\n * Route-module options: `export const layoutOptions = { … }` in a layout and\n * `export const pageOptions = { … }` in a page, read from source.\n *\n * Design doc: design/53-segment-lifetime.md §\"Route-module options\".\n *\n * `prerender` is read here at build time, before any route module loads:\n * `plugins/prerender-sugar.ts` decides from it which pages to wrap in\n * `cache.component(...)`. Every other option is validated here and read at\n * runtime from the loaded module (`deferSuspenseFor`, in\n * `server/route-module-loader.ts`; `lifetime` and `key`, in\n * `server/segment-lifetime/segment-key.ts`). A key's `searchParams` and\n * `cookies` name definitions, so they are the one place a non-literal value is\n * accepted; `segmentParams` is checked against the segment's path by\n * `routing/route-options-lint.ts`. The whole object follows one rule so that\n * every key is checkable: this reader accepts one spelling —\n * `export const xOptions = { … }` of literal values, optionally behind\n * `satisfies` / `as` — and reports the others it can see as problems.\n * `routing/convention-lint.ts` turns problems into build errors:\n *\n * - a spread, a computed key, a getter or method, or a non-literal value\n * - an unknown key (a misspelled `prerendr`)\n * - `pageOptions` in a layout or `layoutOptions` in a page\n * - options in a `'use client'` file, whose exports the server never sees\n * - the removed floating exports, `export const prerender` and\n * `export const deferSuspenseFor`\n * - `let`, a destructured binding, a specifier or a named re-export\n * (`export { pageOptions } from`, `export * as pageOptions from`)\n *\n * What it cannot see is not reported: `export * from` is not followed, a\n * file that does not parse reads as having no options (the compiler reports\n * it), and MDX pages are not read at all, so `prerender` in an MDX page does\n * nothing and its `deferSuspenseFor` is unvalidated.\n */\n\nimport { existsSync } from 'node:fs';\nimport type {\n LayoutOptions,\n PageOptions,\n RoutePrerender,\n SegmentKey,\n SegmentLifetime,\n} from '../server/types.ts';\nimport { patternBinds, TRANSPARENT_WRAPPERS, tryParse } from './export-detect.ts';\nimport { readFileCached } from './file-cache.ts';\nimport { ROUTE_OPTIONS_EXPORT, type RouteOptionsKind } from '../shared/route-options-export.ts';\n\nconst OPTIONS_TYPE = { layout: 'LayoutOptions', page: 'PageOptions' } as const;\n\n/** Floating exports the options objects replaced (design/53). */\nconst REMOVED_EXPORTS = ['prerender', 'deferSuspenseFor'] as const;\n\nexport interface RouteOptionsRead {\n /**\n * The declared options. Undefined when the file declares none or when any\n * problem was found — a half-read object is never acted on.\n */\n options: LayoutOptions | PageOptions | undefined;\n /** One line per problem, each naming what to write instead. */\n problems: string[];\n}\n\n// ─── AST access ────────────────────────────────────────────────────────────\n\n/** An ESTree node as oxc's `parseAst` produces it, read field by field. */\ntype Node = { readonly type: string; readonly [field: string]: unknown };\n\nfunction isNode(value: unknown): value is Node {\n return (\n typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'\n );\n}\n\nfunction child(node: Node, field: string): Node | undefined {\n const value = node[field];\n return isNode(value) ? value : undefined;\n}\n\nfunction list(node: Node, field: string): unknown[] {\n const value = node[field];\n return Array.isArray(value) ? value : [];\n}\n\n/** Strip `satisfies T`, `as T`, `(x)` and friends, which compile away. */\nfunction unwrap(node: Node): Node {\n let current = node;\n while (TRANSPARENT_WRAPPERS.has(current.type)) {\n const inner = child(current, 'expression');\n if (!inner) break;\n current = inner;\n }\n return current;\n}\n\n/** An identifier's name or a string literal's value (`export { x as \"y\" }`). */\nfunction nameOf(node: Node | undefined): string | undefined {\n if (!node) return undefined;\n if (typeof node.value === 'string') return node.value;\n return typeof node.name === 'string' ? node.name : undefined;\n}\n\n/** A literal's value; a template literal with no `${}` counts as a string. */\nfunction literal(node: Node): unknown {\n const n = unwrap(node);\n if (n.type === 'Literal') return n.value;\n if (n.type !== 'TemplateLiteral' || list(n, 'expressions').length > 0) return undefined;\n const [quasi] = list(n, 'quasis');\n // A TemplateElement's `value` is `{ raw, cooked }`, not a node.\n const parts = isNode(quasi) ? quasi.value : undefined;\n const value =\n typeof parts === 'object' && parts !== null && 'cooked' in parts ? parts.cooked : undefined;\n return typeof value === 'string' ? value : undefined;\n}\n\n/** `key: undefined` — the same as leaving the key out, as the types allow. */\nfunction isUndefined(node: Node): boolean {\n const n = unwrap(node);\n return n.type === 'Identifier' && n.name === 'undefined';\n}\n\n// ─── Value readers, one per option ────────────────────────────────────────\n\ntype Read<T> = { value: T } | { problem: string };\n\n/** A numeric literal is never negative (`-1` is a unary expression), so finite is enough. */\nfunction readNonNegativeNumber(node: Node, label: string): Read<number> {\n const value = literal(node);\n if (typeof value === 'number' && Number.isFinite(value)) return { value };\n return { problem: `${label} must be a non-negative number literal.` };\n}\n\nfunction readPrerender(node: Node): Read<RoutePrerender> {\n const value = literal(node);\n if (typeof value === 'boolean') return { value };\n const n = unwrap(node);\n if (n.type !== 'ObjectExpression') {\n return {\n problem: 'prerender must be `true`, `false`, or an object literal `{ ttl?, tags? }`.',\n };\n }\n const result: { ttl?: number; tags?: string[] } = {};\n for (const entry of readProperties(n, 'prerender')) {\n if ('problem' in entry) return entry;\n if (entry.key === 'ttl') {\n const ttl = readNonNegativeNumber(entry.value, 'prerender.ttl');\n if ('problem' in ttl) return ttl;\n result.ttl = ttl.value;\n } else if (entry.key === 'tags') {\n const tags = readStringArray(entry.value);\n if (!tags) return { problem: 'prerender.tags must be an array of string literals.' };\n result.tags = tags;\n } else {\n return { problem: `Unknown key \"${entry.key}\" in prerender. Allowed: ttl, tags.` };\n }\n }\n return { value: result };\n}\n\nfunction readStringArray(node: Node): string[] | undefined {\n const n = unwrap(node);\n if (n.type !== 'ArrayExpression') return undefined;\n const result: string[] = [];\n for (const element of list(n, 'elements')) {\n const value = isNode(element) ? literal(element) : undefined;\n if (typeof value !== 'string') return undefined;\n result.push(value);\n }\n return result;\n}\n\n/**\n * One reader per option key. Typed against the public option types, so an\n * option added to `PageOptions` / `LayoutOptions` without a reader here (or a\n * reader without the option) fails typecheck — the two lists cannot drift.\n */\ntype Readers<T> = {\n [K in keyof Required<T>]: (\n node: Node\n ) => Read<NonNullable<T[K]> extends SegmentKey ? BuildTimeKey : NonNullable<T[K]>>;\n};\n\nconst deferSuspenseFor = (node: Node) => readNonNegativeNumber(node, 'deferSuspenseFor');\n\nconst LIFETIMES: readonly SegmentLifetime[] = ['request', 'document'];\n\nfunction readLifetime(node: Node): Read<SegmentLifetime> {\n const value = literal(node);\n const lifetime = LIFETIMES.find((l) => l === value);\n if (lifetime) return { value: lifetime };\n return { problem: \"lifetime must be 'request' or 'document'.\" };\n}\n\n/**\n * What the build can read of a segment key: the param names. `searchParams`\n * and `cookies` name definitions — code the build cannot evaluate — so only\n * their shape is checked here; their values take effect from the loaded\n * module (`server/segment-lifetime/`). The route-options lint checks the\n * param names against the segment's path.\n */\ntype BuildTimeKey = Pick<SegmentKey, 'segmentParams'>;\n\n/** A value written in place, which cannot be a definition imported or declared elsewhere. */\nfunction isInlineValue(node: Node): boolean {\n const type = unwrap(node).type;\n return (\n literal(node) !== undefined ||\n type === 'ObjectExpression' ||\n type === 'ArrayExpression' ||\n type === 'Literal' ||\n type === 'TemplateLiteral'\n );\n}\n\nfunction readKey(node: Node): Read<BuildTimeKey> {\n const n = unwrap(node);\n if (n.type !== 'ObjectExpression') {\n return {\n problem: 'key must be an object literal `{ segmentParams?, searchParams?, cookies? }`.',\n };\n }\n const result: BuildTimeKey = {};\n for (const entry of readProperties(n, 'key')) {\n if ('problem' in entry) return entry;\n if (entry.key === 'segmentParams') {\n const names = readStringArray(entry.value);\n if (!names) return { problem: 'key.segmentParams must be an array of string literals.' };\n result.segmentParams = names;\n } else if (entry.key === 'searchParams') {\n if (isInlineValue(entry.value)) {\n return {\n problem:\n 'key.searchParams must name a search-params definition (`defineSearchParams`, or a `.pick()` of one).',\n };\n }\n } else if (entry.key === 'cookies') {\n const array = unwrap(entry.value);\n const elements = list(array, 'elements');\n const definitions = elements.every(\n (e) => isNode(e) && e.type !== 'SpreadElement' && !isInlineValue(e)\n );\n if (array.type !== 'ArrayExpression' || !definitions) {\n return {\n problem: 'key.cookies must be an array literal of cookie definitions (`defineCookie`).',\n };\n }\n } else {\n return {\n problem: `Unknown key \"${entry.key}\" in key. Allowed: segmentParams, searchParams, cookies.`,\n };\n }\n }\n return { value: result };\n}\n\nconst READERS = {\n layout: {\n lifetime: readLifetime,\n key: readKey,\n prerender: readPrerender,\n deferSuspenseFor,\n } satisfies Readers<LayoutOptions>,\n page: {\n lifetime: readLifetime,\n key: readKey,\n prerender: readPrerender,\n deferSuspenseFor,\n } satisfies Readers<PageOptions>,\n};\n\n// ─── Object literal ───────────────────────────────────────────────────────\n\ntype Entry = { key: string; value: Node } | { problem: string };\n\n/**\n * The `key: value` entries of an object literal, or a problem per entry that\n * has none. `key: undefined` entries are dropped: they mean \"not set\".\n */\nfunction readProperties(object: Node, label: string): Entry[] {\n return list(object, 'properties').flatMap((prop): Entry[] => {\n if (!isNode(prop) || prop.type === 'SpreadElement') {\n return [{ problem: `${label} cannot use a spread; write every key in the literal.` }];\n }\n if (prop.computed === true) {\n return [{ problem: `${label} cannot use a computed key; write the key name.` }];\n }\n const value = child(prop, 'value');\n const key = nameOf(child(prop, 'key'));\n if (prop.kind !== 'init' || prop.method === true || !value || key === undefined) {\n return [{ problem: `${label} entries must be plain \\`key: value\\` pairs.` }];\n }\n return isUndefined(value) ? [] : [{ key, value }];\n });\n}\n\nfunction readOptionsObject(init: Node, kind: RouteOptionsKind, problems: string[]) {\n const name = ROUTE_OPTIONS_EXPORT[kind];\n const object = unwrap(init);\n if (object.type !== 'ObjectExpression') {\n problems.push(`${name} must be an object literal: \\`export const ${name} = { … }\\`.`);\n return undefined;\n }\n const readers: Record<string, (node: Node) => Read<unknown>> = READERS[kind];\n const options: Record<string, unknown> = {};\n for (const entry of readProperties(object, name)) {\n if ('problem' in entry) {\n problems.push(entry.problem);\n continue;\n }\n const reader = Object.hasOwn(readers, entry.key) ? readers[entry.key] : undefined;\n if (!reader) {\n problems.push(\n `Unknown key \"${entry.key}\" in ${name}. Allowed: ${Object.keys(readers).join(', ')}.`\n );\n continue;\n }\n const read = reader(entry.value);\n if ('problem' in read) problems.push(read.problem);\n else options[entry.key] = read.value;\n }\n return options;\n}\n\n// ─── File ─────────────────────────────────────────────────────────────────\n\nconst NONE: RouteOptionsRead = Object.freeze({ options: undefined, problems: [] });\n\n/** Every name the reader reacts to; a file containing none of them is not parsed. */\nconst MENTIONS = /Options|prerender|deferSuspenseFor/;\n\n/**\n * Read a layout's `layoutOptions` or a page's `pageOptions` from source.\n *\n * A missing or unparseable file reads as no options and no problems: the\n * compiler reports syntax errors, and guessing at a half-written file would\n * misreport it. `.ts` files are parsed as TypeScript, not TSX, so an\n * angle-bracket cast does not hide a file from this check.\n */\nexport function readRouteOptions(filePath: string, kind: RouteOptionsKind): RouteOptionsRead {\n if (!existsSync(filePath)) return NONE;\n const source = readFileCached(filePath);\n // Runs on every page and layout on each rescan; most declare nothing.\n if (!MENTIONS.test(source)) return NONE;\n const program = tryParse(source, /\\.[mc]?ts$/.test(filePath) ? 'ts' : 'tsx');\n if (!program) return NONE;\n\n const own = ROUTE_OPTIONS_EXPORT[kind];\n const otherKind: RouteOptionsKind = kind === 'page' ? 'layout' : 'page';\n const other = ROUTE_OPTIONS_EXPORT[otherKind];\n const problems: string[] = [];\n let init: Node | undefined;\n\n /** An export of a watched name in a form the build cannot read. */\n const report = (name: string | undefined) => {\n if (name === own) {\n problems.push(\n `${own} must be declared in this file as \\`export const ${own} = { … } satisfies ${OPTIONS_TYPE[kind]}\\`. ` +\n '`let`, destructuring, `export { … }` and re-exports cannot be read at build time.'\n );\n } else if (name === other) {\n problems.push(\n `${other} configures a ${otherKind}; this file is a ${kind}. Use \\`export const ${own}\\`.`\n );\n } else if (name && (REMOVED_EXPORTS as readonly string[]).includes(name)) {\n problems.push(\n `\\`export const ${name}\\` was removed. Move it into the options object: ` +\n `\\`export const ${own} = { ${name}: … } satisfies ${OPTIONS_TYPE[kind]}\\`.`\n );\n }\n };\n const watched = [own, other, ...REMOVED_EXPORTS];\n\n for (const stmt of program.body) {\n if (!isNode(stmt) || stmt.exportKind === 'type') continue;\n // `export * as pageOptions from` names an export; bare `export * from` does not.\n if (stmt.type === 'ExportAllDeclaration') report(nameOf(child(stmt, 'exported')));\n if (stmt.type !== 'ExportNamedDeclaration') continue;\n for (const spec of list(stmt, 'specifiers')) {\n if (isNode(spec) && spec.exportKind !== 'type') report(nameOf(child(spec, 'exported')));\n }\n const decl = child(stmt, 'declaration');\n if (!decl) continue;\n if (decl.type !== 'VariableDeclaration') {\n report(nameOf(child(decl, 'id'))); // function or class\n continue;\n }\n for (const declarator of list(decl, 'declarations')) {\n if (!isNode(declarator)) continue;\n const id = child(declarator, 'id');\n const value = child(declarator, 'init');\n if (id?.type !== 'Identifier') {\n for (const name of watched) if (patternBinds(id, name)) report(name);\n } else if (id.name === own && decl.kind === 'const' && value) {\n init = value;\n } else {\n report(nameOf(id));\n }\n }\n }\n\n if (init && isClientModule(program.body)) {\n problems.push(\n `A 'use client' ${kind} cannot declare ${own}: the server sees a client reference, ` +\n `not the object. Move ${own} to a server ${kind} that renders the client component.`\n );\n }\n const options = init ? readOptionsObject(init, kind, problems) : undefined;\n return { options: problems.length === 0 ? options : undefined, problems };\n}\n\n/** Whether the module starts with a 'use client' directive. */\nfunction isClientModule(body: readonly unknown[]): boolean {\n for (const stmt of body) {\n if (\n !isNode(stmt) ||\n stmt.type !== 'ExpressionStatement' ||\n typeof stmt.directive !== 'string'\n ) {\n return false;\n }\n if (stmt.directive === 'use client') return true;\n }\n return false;\n}\n","/**\n * Convention-lint check for route-module options (design/53 §\"Route-module\n * options\"): `layoutOptions` / `pageOptions` the build cannot read, and\n * options declared where nothing reads them. Called from\n * `lintConventions` in `convention-lint.ts`.\n */\n\nimport type { ConventionWarning } from './convention-lint.ts';\nimport { fileHasAnyExport, isScriptExtension } from './export-detect.ts';\nimport { readRouteOptions } from './route-options.ts';\nimport type { RouteFile, SegmentNode } from './types.ts';\nimport type { LayoutOptions, PageOptions, SegmentLifetime } from '../server/types.ts';\nimport { ROUTE_OPTIONS_EXPORT, type RouteOptionsKind } from '../shared/route-options-export.ts';\n\n/**\n * Fail the build on a `layoutOptions` / `pageOptions` the build cannot read.\n *\n * Proven from source and fatal in the sense the error level requires: the\n * developer declared an option that would otherwise silently do nothing — a\n * misspelled key, a value the build cannot read, an options object in the\n * wrong file kind, or a floating `export const prerender` that no longer\n * prerenders. See `routing/route-options.ts` for what is accepted.\n */\nexport function checkRouteOptions(\n node: SegmentNode,\n warnings: ConventionWarning[],\n position: RoutePosition,\n /** The app's `defaultLayoutLifetime` (design/53 §\"App-wide default\"). */\n defaultLayoutLifetime: SegmentLifetime,\n /** The params named on the path above this segment. */\n ancestorParams: readonly string[] = []\n): void {\n const here: RoutePosition = node.segmentType === 'intercepting' ? 'intercepting' : position;\n const pathParams = node.paramName ? [...ancestorParams, node.paramName] : ancestorParams;\n const files: Array<[RouteOptionsKind, RouteFile | undefined]> = [\n ['layout', node.layout],\n ['page', node.page],\n ];\n for (const [kind, file] of files) {\n if (!file || !isScriptExtension(file.extension)) continue;\n const { options, problems } = readRouteOptions(file.filePath, kind);\n problems.push(\n ...inertOptions(options, here),\n ...paramsOffPath(options, pathParams),\n ...keyWithoutDocument(options, kind === 'layout' ? defaultLayoutLifetime : 'request')\n );\n if (problems.length === 0) continue;\n warnings.push({\n id: `ROUTE_OPTIONS_INVALID:${file.filePath}`,\n summary: `${kind}.${file.extension} has invalid ${ROUTE_OPTIONS_EXPORT[kind]}: ${file.filePath}`,\n details:\n ` File: ${file.filePath}\\n\\n` +\n problems.map((problem) => ` - ${problem}\\n`).join('') +\n '\\n Options are read from source at build time, so they must be one object\\n' +\n ' literal of literal values.\\n',\n level: 'error',\n });\n }\n if (node.default && isScriptExtension(node.default.extension)) {\n const declared = fileHasAnyExport(node.default.filePath, OPTION_EXPORT_NAMES);\n if (declared.size > 0) {\n warnings.push({\n id: `ROUTE_OPTIONS_INVALID:${node.default.filePath}`,\n summary: `default.${node.default.extension} takes no route options: ${node.default.filePath}`,\n details:\n ` File: ${node.default.filePath}\\n\\n` +\n ` default.tsx exports ${[...declared].join(', ')}, which nothing reads.\\n` +\n ' To fix: remove the export; declare options on the slot page or layout.\\n',\n level: 'error',\n });\n }\n }\n for (const child of node.children) {\n checkRouteOptions(child, warnings, here, defaultLayoutLifetime, pathParams);\n }\n for (const slot of Object.values(node.slots)) {\n const slotPosition = here === 'intercepting' ? here : 'slot';\n checkRouteOptions(slot, warnings, slotPosition, defaultLayoutLifetime, pathParams);\n }\n}\n\n/**\n * A `key` applies only to a `'document'` segment; on any other it would\n * silently do nothing. A layout that declares no lifetime takes the app's\n * `defaultLayoutLifetime`, so under a `'document'` default it may declare a\n * key alone. A page always defaults to `'request'`.\n */\nfunction keyWithoutDocument(\n options: LayoutOptions | PageOptions | undefined,\n defaultLifetime: SegmentLifetime\n): string[] {\n if (options?.key === undefined || (options.lifetime ?? defaultLifetime) === 'document') return [];\n return [\n \"key applies only to lifetime: 'document'. Declare `lifetime: 'document'` or remove key.\",\n ];\n}\n\n/**\n * A key's `segmentParams` must name params on the segment's path — the\n * segment's own and every ancestor's, slots included. Anything else could\n * never change, so the key would silently ignore what the author meant\n * (design/53 §\"Segment keys\").\n */\nfunction paramsOffPath(\n options: LayoutOptions | PageOptions | undefined,\n pathParams: readonly string[]\n): string[] {\n const declared = options?.key?.segmentParams ?? [];\n return declared\n .filter((name) => !pathParams.includes(name))\n .map(\n (name) =>\n `key.segmentParams names \"${name}\", which is not a param on this segment's path. ` +\n (pathParams.length > 0\n ? `Params on the path: ${pathParams.join(', ')}.`\n : 'This path has no params.')\n );\n}\n\n/**\n * Where a segment sits decides which options take effect there.\n * - `main`: the matched route chain. Every option applies.\n * - `slot`: a parallel slot. `prerender` applies to slot pages (the sugar\n * walks slots); `deferSuspenseFor` does not — the hold is read from the\n * main chain's modules only (`server/route-module-loader.ts`).\n * - `intercepting`: an intercepting route and everything under it. It renders\n * only on a soft navigation, through the slot resolver, and the sugar skips\n * it, so no option applies.\n */\ntype RoutePosition = 'main' | 'slot' | 'intercepting';\n\nconst OPTION_EXPORT_NAMES = [\n ...Object.values(ROUTE_OPTIONS_EXPORT),\n 'prerender',\n 'deferSuspenseFor',\n] as const;\n\nfunction inertOptions(\n options: LayoutOptions | PageOptions | undefined,\n position: RoutePosition\n): string[] {\n if (!options || position === 'main') return [];\n const inert = Object.keys(options).filter(\n (key) => position === 'intercepting' || key === 'deferSuspenseFor'\n );\n return inert.map((key) =>\n position === 'intercepting'\n ? `${key} has no effect on an intercepting route: it renders only on a soft navigation, ` +\n 'through the slot that intercepts it. Declare it on the route being intercepted.'\n : `${key} has no effect in a parallel slot: the hold is read from the main route's ` +\n 'layouts and page. Declare it there.'\n );\n}\n","/**\n * Convention linter — validates common misconfigurations in the route tree.\n *\n * Runs at scan time (build and dev startup). Each check produces a warning\n * with the file path, what's wrong, and what to do about it.\n *\n * Most checks are warnings — they don't block the build. The goal is to catch\n * issues that would otherwise produce cryptic runtime behavior (silent 404s,\n * empty pages, confusing React errors).\n *\n * A check emits `level: 'error'` only when the misconfiguration is *proven*\n * (never inferred from an absence the analysis cannot see through) and either\n * fatal to rendering or a declaration that provably does nothing — a CSRF\n * exemption the gate never reads, a route option the build cannot read, a\n * middleware.ts in a slot. The developer believes the declaration is in\n * effect, so silence would ship the wrong behavior. `plugins/routing.ts` turns those into a thrown build error,\n * so a false positive there refuses a working app — see\n * `classifyClientBoundaryFile` for how that bar is met.\n *\n * Design doc: 07-routing.md, 10-error-handling.md\n */\n\nimport { existsSync } from 'node:fs';\nimport type { RouteFile, RouteTree, SegmentNode } from './types.ts';\nimport { swallow } from '../server/logger.ts';\nimport { HTTP_METHODS } from '../server/route-methods.ts';\nimport {\n fileDefaultExportIsLocalValue,\n fileHasAnyExport,\n fileHasDefaultExport,\n fileHasDirective,\n fileHasStarExport,\n getCsrfExport,\n isScriptExtension,\n} from './export-detect.ts';\nimport { checkRouteOptions } from './route-options-lint.ts';\nimport type { SegmentLifetime } from '../server/types.ts';\n\n// ─── Types ──────────────────────────────────────────────────────────────────\n\nexport interface ConventionWarning {\n /** Warning ID for deduplication and filtering. */\n id: string;\n /** Human-readable single-line summary. */\n summary: string;\n /** Multi-line details with file path and fix suggestion. */\n details: string;\n /** Severity: 'warn' for potential issues, 'error' for definite misconfigurations. */\n level: 'warn' | 'error';\n}\n\n// ─── Lint Rules ─────────────────────────────────────────────────────────────\n\n/**\n * Run all convention lint checks on a route tree.\n *\n * Returns an array of warnings. Empty array means everything looks good.\n */\nexport function lintConventions(\n tree: RouteTree,\n appDir: string,\n /** The config the checks depend on, as the build resolved it. */\n config: { defaultLayoutLifetime: SegmentLifetime | undefined }\n): ConventionWarning[] {\n const warnings: ConventionWarning[] = [];\n\n // Check 1: app/ directory exists (caller should check before scanning,\n // but we validate the root has at least one routable file)\n checkEmptyApp(tree.root, appDir, warnings);\n\n // Check 2: route.ts without recognized HTTP method exports\n checkRouteExports(tree.root, warnings);\n\n // Check 3: Segments with layout but no page/route anywhere in subtree\n // (not a misconfiguration per se — layouts without pages are valid for\n // route groups. Skip this check.)\n\n // Check 4: Root segment has no layout.tsx (no HTML shell)\n checkRootLayout(tree.root, warnings);\n\n // Check 5: page.tsx / layout.tsx without default export\n checkDefaultExports(tree.root, warnings);\n\n // Check 6: Client layouts cannot suppress server children before Flight\n // serializes them. They remain valid UI boundaries, but not authorization\n // or data-hiding boundaries.\n checkClientLayouts(tree.root, warnings);\n\n // Check 7: error.tsx / 404.tsx / 4xx.tsx / … without 'use client' directive\n checkClientBoundaryFiles(tree.root, warnings);\n if (tree.globalError) {\n checkFileUseClientDirective(tree.globalError, 'global-error', warnings);\n }\n\n // Check 8: middleware.ts inside a parallel slot subtree (silently dead)\n checkSlotMiddleware(tree.root, warnings);\n\n // Check 9: `export const csrf` anywhere but route.ts, or in a form the\n // scanner cannot read (TIM-1543)\n checkCsrfExports(tree.root, warnings);\n if (tree.proxy) checkCsrfExport(tree.proxy, 'proxy.ts', warnings);\n if (tree.globalError) checkCsrfExport(tree.globalError, 'global-error', warnings);\n\n // Check 10: layoutOptions / pageOptions the build cannot read, unknown\n // keys, and the removed floating exports (design/53)\n checkRouteOptions(tree.root, warnings, 'main', config.defaultLayoutLifetime ?? 'request');\n\n return warnings;\n}\n\nfunction checkClientLayouts(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.layout && isScriptExtension(node.layout.extension)) {\n try {\n const isClient = fileHasDirective(node.layout.filePath, 'use client');\n const isProvablyServer = fileDefaultExportIsLocalValue(node.layout.filePath);\n if (isClient || !isProvablyServer) {\n const certainty = isClient\n ? `This layout is a client component.`\n : `Timber cannot prove this layout is a server component because its default export comes from another module or an opaque expression.`;\n warnings.push({\n id: `CLIENT_LAYOUT_NOT_AUTH_BOUNDARY:${node.layout.filePath}`,\n summary: isClient\n ? `Client layout cannot securely suppress server children: ${node.layout.filePath}`\n : `Layout may resolve to a client component and cannot be trusted as an auth boundary: ${node.layout.filePath}`,\n details:\n ` File: ${node.layout.filePath}\\n\\n` +\n ` ${certainty}\\n` +\n ` React Flight resolves server content passed to a client layout before the layout runs in the browser.\\n` +\n ` Conditionally omitting children here does not prevent descendant server components from executing or being serialized.\\n\\n` +\n ` To fix: Put authorization in access.ts or a provably server layout with a locally defined default component, and keep client components inside that boundary.\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable layout file ${node.layout.filePath}`);\n }\n }\n for (const child of node.children) checkClientLayouts(child, warnings);\n for (const slot of Object.values(node.slots)) checkClientLayouts(slot, warnings);\n}\n\n// ─── Check: CSRF Exemption Export ──────────────────────────────────────────\n\n/** Single-file segment conventions other than route.ts. */\nconst NON_ROUTE_FILE_KEYS = [\n 'page',\n 'layout',\n 'middleware',\n 'access',\n 'error',\n 'default',\n 'denied',\n] as const satisfies readonly (keyof SegmentNode)[];\n\n/**\n * Fail the build on a `csrf` export the CSRF gate would not honor.\n *\n * Both findings are proven from source, and both are fatal in the sense\n * the error level requires: the developer wrote an exemption that silently\n * does nothing, so a legitimate cross-site POST they meant to accept gets\n * a 403 in production, or they believe a page or action is exempt when\n * the gate still protects it. The exemption exists only on route.ts —\n * server actions always get the check (design/08 §\"Per-route exemption\").\n * A `'use server'` module cannot export it at all: plugin-rsc rejects every\n * non-async-function export there.\n */\nfunction checkCsrfExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) checkCsrfExport(node.route, 'route.ts', warnings);\n for (const key of NON_ROUTE_FILE_KEYS) {\n const file = node[key];\n if (file) checkCsrfExport(file, key, warnings);\n }\n // Status files and metadata routes (sitemap.ts, opengraph-image.tsx, …).\n // JSON status files are skipped by the script-extension check.\n for (const [name, file] of Object.entries(node.statusFiles ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const [name, file] of Object.entries(node.metadataRoutes ?? {})) {\n checkCsrfExport(file, name, warnings);\n }\n for (const child of node.children) checkCsrfExports(child, warnings);\n for (const slot of Object.values(node.slots)) checkCsrfExports(slot, warnings);\n}\n\nfunction checkCsrfExport(file: RouteFile, convention: string, warnings: ConventionWarning[]): void {\n if (!isScriptExtension(file.extension)) return;\n const found = getCsrfExport(file.filePath);\n if (found === 'absent') return;\n const isRoute = convention === 'route.ts';\n if (isRoute && found === 'exempt') return;\n warnings.push({\n id: `CSRF_EXPORT_INVALID:${file.filePath}`,\n summary: isRoute\n ? `route.ts csrf export must be exactly \\`export const csrf = false\\`: ${file.filePath}`\n : `\\`csrf\\` can only be exported from route.ts, not ${convention}: ${file.filePath}`,\n details:\n ` File: ${file.filePath}\\n\\n` +\n (isRoute\n ? ' The CSRF gate reads this export from source before any module loads, so only\\n' +\n ' the literal form counts. Other values, `let`, and re-exports are not read.\\n\\n' +\n ' To fix: write `export const csrf = false;` in this file, or remove the export.\\n'\n : ' The per-route CSRF exemption applies only to route.ts handlers. Pages, layouts\\n' +\n ' and server actions always get the CSRF check.\\n\\n' +\n ' To fix: remove the export. To accept a cross-site POST, handle it in a route.ts\\n' +\n ' that exports `const csrf = false`.\\n'),\n level: 'error',\n });\n}\n\n// ─── Check: Empty App ───────────────────────────────────────────────────────\n\n/**\n * Warn when the app/ directory has no routable files at all.\n *\n * This catches the \"I created app/ but didn't add any pages\" case where\n * every request silently 404s with no guidance.\n */\nfunction checkEmptyApp(root: SegmentNode, appDir: string, warnings: ConventionWarning[]): void {\n if (hasAnyRoutable(root)) return;\n\n warnings.push({\n id: 'EMPTY_APP',\n summary: 'No pages or route handlers found in app/',\n details:\n ` Directory: ${appDir}\\n\\n` +\n ' Your app/ directory has no page.tsx or route.ts files.\\n' +\n ' Every request will return 404.\\n\\n' +\n ' To fix: Create app/page.tsx with a default export:\\n\\n' +\n ' export default function Home() {\\n return <h1>Hello</h1>;\\n }\\n',\n level: 'warn',\n });\n}\n\n/**\n * Check if a segment tree has any routable files (page or route) anywhere.\n */\nfunction hasAnyRoutable(node: SegmentNode): boolean {\n if (node.page || node.route) return true;\n for (const child of node.children) {\n if (hasAnyRoutable(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyRoutable(slot)) return true;\n }\n return false;\n}\n\n/**\n * Check if a segment tree has any page files (not just route handlers).\n * Used by checkRootLayout to avoid false positives for API-only apps (TIM-794).\n * API-only apps (just route.ts handlers) don't need a root layout.\n */\nfunction hasAnyPage(node: SegmentNode): boolean {\n if (node.page) return true;\n for (const child of node.children) {\n if (hasAnyPage(child)) return true;\n }\n for (const slot of Object.values(node.slots)) {\n if (hasAnyPage(slot)) return true;\n }\n return false;\n}\n\n// ─── Check: Route Exports ───────────────────────────────────────────────────\n\n/**\n * Warn when a route.ts file doesn't appear to export any recognized HTTP methods.\n *\n * Uses AST-based detection via parseAst for precise matching.\n * Falls back silently when the file can't be parsed (syntax errors produce\n * no spurious warning — the TS compiler will catch those).\n */\nfunction checkRouteExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.route) {\n const filePath = node.route.filePath;\n try {\n const methods = fileHasAnyExport(filePath, HTTP_METHODS);\n if (methods.size === 0 && !fileHasStarExport(filePath)) {\n const hasDefault = fileHasDefaultExport(filePath);\n const hint = hasDefault\n ? ' It looks like you have a default export. route.ts uses named exports\\n' +\n ' for HTTP methods (GET, POST, etc.), not a default export.\\n'\n : '';\n\n warnings.push({\n id: 'ROUTE_NO_METHODS',\n summary: `route.ts has no HTTP method exports: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ' route.ts files must export named HTTP method handlers.\\n' +\n ' Without them, the route matches but returns 405 Method Not Allowed.\\n\\n' +\n hint +\n ' Example:\\n\\n' +\n ' export function GET(ctx: RouteContext) {\\n' +\n \" return Response.json({ hello: 'world' });\\n\" +\n ' }\\n',\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable route.ts ${filePath}`);\n }\n }\n\n // Recurse\n for (const child of node.children) {\n checkRouteExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkRouteExports(slot, warnings);\n }\n}\n\n// ─── Check: Root Layout ─────────────────────────────────────────────────────\n\n/**\n * Warn when the root segment has no layout.tsx.\n *\n * Without a root layout, there's no HTML shell (<html>, <body>).\n * The page will render but may have hydration issues or no proper document structure.\n */\nfunction checkRootLayout(root: SegmentNode, warnings: ConventionWarning[]): void {\n if (root.layout) return;\n\n // Only warn if there are pages — API-only apps (just route.ts handlers)\n // don't need a root layout (TIM-794).\n if (!hasAnyPage(root)) return;\n\n warnings.push({\n id: 'NO_ROOT_LAYOUT',\n summary: 'No root layout.tsx found',\n details:\n ' Your app has pages but no root layout.\\n' +\n ' Without app/layout.tsx, pages have no <html> or <body> wrapper.\\n\\n' +\n ' To fix: Create app/layout.tsx:\\n\\n' +\n ' export default function RootLayout({ children }: { children: React.ReactNode }) {\\n' +\n ' return (\\n' +\n ' <html lang=\"en\">\\n' +\n ' <body>{children}</body>\\n' +\n ' </html>\\n' +\n ' );\\n' +\n ' }\\n',\n level: 'warn',\n });\n}\n\n// ─── Check: Default Exports ───────────────────────────────────────────\n\n/**\n * Warn when page.tsx or layout.tsx files don't have a default export.\n *\n * Without a default export:\n * - page.tsx: the page renders nothing (empty content)\n * - layout.tsx: the layout module loads but has no component to render\n *\n * Uses AST-based detection via parseAst for precise matching. Falls back\n * silently when the file can't be parsed (no spurious warning on syntax errors).\n */\nfunction checkDefaultExports(node: SegmentNode, warnings: ConventionWarning[]): void {\n // Check page files (tsx/ts/jsx/js only — not mdx, which is default-exported by the mdx compiler)\n if (node.page && isScriptExtension(node.page.extension)) {\n checkFileDefaultExport(node.page.filePath, 'page', warnings);\n }\n\n // Check layout files\n if (node.layout && isScriptExtension(node.layout.extension)) {\n checkFileDefaultExport(node.layout.filePath, 'layout', warnings);\n }\n\n // Recurse\n for (const child of node.children) {\n checkDefaultExports(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkDefaultExports(slot, warnings);\n }\n}\n\nfunction checkFileDefaultExport(\n filePath: string,\n fileType: string,\n warnings: ConventionWarning[]\n): void {\n try {\n if (!fileHasDefaultExport(filePath)) {\n warnings.push({\n id: `NO_DEFAULT_EXPORT:${filePath}`,\n summary: `${fileType}.tsx has no default export: ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${fileType}.tsx files must export a default React component.\\n` +\n ` Without a default export, the ${fileType === 'page' ? 'page renders nothing' : 'layout has no component to wrap children'}.\\n\\n` +\n ` To fix: Add a default export:\\n\\n` +\n ` export default function My${fileType === 'page' ? 'Page' : 'Layout'}(${fileType === 'layout' ? '{ children }' : ''}) {\\n` +\n ` return ${fileType === 'layout' ? '<div>{children}</div>' : '<h1>Hello</h1>'};\\n` +\n ` }\\n`,\n level: 'warn',\n });\n }\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${fileType} file ${filePath}`);\n }\n}\n\n// ─── Check: Client Boundary Directive ───────────────────────────────────────\n\n/**\n * Check every file the renderer hands to `TimberErrorBoundary` as a component\n * prop: `error.tsx`, `global-error.tsx`, and the status-code family\n * (`404.tsx`, `4xx.tsx`, `503.tsx`, …).\n *\n * `TimberErrorBoundary` is a client component, so a server component passed as\n * `fallbackComponent` is a function crossing the RSC → client boundary. React\n * Flight refuses to serialize it, and because the boundary wraps the segment's\n * *children*, the failure hits every page under that segment — not just the\n * error path. The raw message (\"Functions cannot be passed directly to Client\n * Components\") names neither the file nor the fix (TIM-1329).\n *\n * `.json` status files never reach React at all, and are not in `statusFiles`.\n */\nfunction checkClientBoundaryFiles(node: SegmentNode, warnings: ConventionWarning[]): void {\n if (node.error) {\n checkFileUseClientDirective(node.error, 'error', warnings);\n }\n\n for (const [key, file] of Object.entries(node.statusFiles ?? {})) {\n checkFileUseClientDirective(file, key, warnings);\n }\n\n for (const child of node.children) {\n checkClientBoundaryFiles(child, warnings);\n }\n for (const slot of Object.values(node.slots)) {\n checkClientBoundaryFiles(slot, warnings);\n }\n}\n\n/**\n * `'client'` — carries the directive.\n * `'server'` — proven server component: no directive, and the default export is\n * a function or class built by this very module, so no other file's directive\n * can be governing it.\n * `'unknown'` — no directive, but the exported value may come from elsewhere\n * (`export { default } from './client-thing'`), or the file could not be\n * read or parsed. Never escalated to a build error.\n */\ntype ClientBoundaryVerdict = 'client' | 'server' | 'unknown';\n\nfunction classifyClientBoundaryFile(filePath: string): ClientBoundaryVerdict {\n if (fileHasDirective(filePath, 'use client')) return 'client';\n if (fileDefaultExportIsLocalValue(filePath)) return 'server';\n return 'unknown';\n}\n\n/** Example component name for the fix snippet, keyed by convention name. */\nfunction exampleComponentName(convention: string): string {\n if (convention === 'global-error') return 'GlobalError';\n if (convention === 'error') return 'ErrorBoundary';\n if (convention === '404') return 'NotFound';\n return 'StatusPage';\n}\n\n/**\n * @param file the route file (its extension decides whether the check applies)\n * @param convention the convention name — `error`, `global-error`, `404`, `4xx`, …\n */\nfunction checkFileUseClientDirective(\n file: RouteFile,\n convention: string,\n warnings: ConventionWarning[]\n): void {\n // Only script extensions need the 'use client' check — .json status files\n // never reach React at all, and are not in `statusFiles`.\n if (!isScriptExtension(file.extension)) return;\n\n const filePath = file.filePath;\n const label = `${convention}.${file.extension}`;\n let verdict: ClientBoundaryVerdict;\n try {\n verdict = classifyClientBoundaryFile(filePath);\n } catch (err) {\n swallow(err, `convention-lint: unreadable ${label} file ${filePath}`);\n return;\n }\n if (verdict === 'client') return;\n\n const isError = verdict === 'server';\n const name = exampleComponentName(convention);\n const props =\n convention === 'error' || convention === 'global-error' ? '{ error, reset }' : '{ status }';\n\n warnings.push({\n id: `NEEDS_USE_CLIENT:${filePath}`,\n summary: isError\n ? `${label} is a server component and must be a client component: ${filePath}`\n : `${label} may be missing 'use client': ${filePath}`,\n details:\n ` File: ${filePath}\\n\\n` +\n ` ${label} is handed to timber's error boundary — a client\\n` +\n ' component — as a prop. A server component cannot cross that boundary:\\n' +\n ' React fails with \"Functions cannot be passed directly to Client\\n' +\n ' Components\", and every page under this segment fails to render.\\n\\n' +\n (isError\n ? \" To fix: Add 'use client' as the first line of the file:\\n\\n\" +\n \" 'use client';\\n\\n\" +\n ` export default function ${name}(${props}) {\\n` +\n ' return <h1>…</h1>;\\n' +\n ' }\\n'\n : // The default export comes from somewhere this analysis cannot follow\n // — a re-export, an imported binding, a wrapper call. It may well\n // already be a client component, so say what was checked rather than\n // assert a break.\n \" This file has no 'use client' directive, and its default export\\n\" +\n ' comes from elsewhere, so timber cannot tell which it is. If the\\n' +\n \" module it re-exports starts with 'use client', nothing is wrong\\n\" +\n ' and you can ignore this. Otherwise add the directive there.\\n'),\n level: isError ? 'error' : 'warn',\n });\n}\n\n// ─── Check: Slot Middleware ─────────────────────────────────────────────────\n\n/**\n * Error when middleware.ts appears inside a parallel slot subtree.\n *\n * Middleware is collected from the main matched segment chain only\n * (route-matcher.ts `collectMiddlewareChain`). The slot resolver never\n * walks `middleware` on its matched chain, so a middleware.ts under any\n * `@slot/` directory silently never executes. `access.ts` in slot chains\n * DOES run (via SlotAccessGate), making the asymmetry invisible unless\n * you know to look.\n *\n * This is a build error rather than a warning: the file provably cannot\n * run and its presence misleads the author into thinking the slot is\n * middleware-protected.\n *\n * See design/07-routing.md §\"Parallel Routes\"\n */\nfunction checkSlotMiddleware(node: SegmentNode, warnings: ConventionWarning[]): void {\n for (const [slotName, slotRoot] of Object.entries(node.slots)) {\n collectSlotMiddleware(slotRoot, slotName, warnings);\n }\n for (const child of node.children) {\n checkSlotMiddleware(child, warnings);\n }\n}\n\n/**\n * Walk a slot subtree and report every middleware.ts found.\n */\nfunction collectSlotMiddleware(\n node: SegmentNode,\n slotName: string,\n warnings: ConventionWarning[]\n): void {\n if (node.middleware) {\n warnings.push({\n id: `SLOT_MIDDLEWARE:${node.middleware.filePath}`,\n summary: `middleware.ts inside slot @${slotName} never executes: ${node.middleware.filePath}`,\n details:\n ` File: ${node.middleware.filePath}\\n\\n` +\n ` Middleware is collected from the main route chain only.\\n` +\n ` The slot resolver does not run middleware — this file is silently dead.\\n` +\n ` (access.ts in slots does run via SlotAccessGate; middleware.ts does not.)\\n\\n` +\n ` To fix: Move the middleware logic into access.ts for slot-scoped auth,\\n` +\n ` or into a middleware.ts on the main route chain outside the slot.\\n`,\n level: 'error',\n });\n }\n for (const child of node.children) {\n collectSlotMiddleware(child, slotName, warnings);\n }\n for (const [nestedSlotName, nestedSlot] of Object.entries(node.slots)) {\n collectSlotMiddleware(nestedSlot, nestedSlotName, warnings);\n }\n}\n\n// ─── Check: App Directory Exists ────────────────────────────────────────────\n\n/**\n * Check if the app/ directory exists. Called before scanning.\n * Returns a warning if missing, or null if the directory exists.\n */\nexport function checkAppDirExists(appDir: string): ConventionWarning | null {\n if (existsSync(appDir)) return null;\n\n return {\n id: 'NO_APP_DIR',\n summary: 'No app/ directory found',\n details:\n ` Expected: ${appDir}\\n\\n` +\n ' timber.js requires an app/ directory for file-system routing.\\n' +\n ' Every request will return 404 until you create it.\\n\\n' +\n ' To fix: Create the app/ directory with a page:\\n\\n' +\n ' mkdir -p app\\n' +\n ' # Create app/layout.tsx and app/page.tsx\\n',\n level: 'error',\n };\n}\n\n// ─── Formatting ─────────────────────────────────────────────────────────────\n\nimport type { InspectColor } from 'node:util';\nimport { styleText } from 'node:util';\n\ntype Format = InspectColor | readonly InspectColor[];\nconst noValidate = { validateStream: false } as const;\n\nexport interface FormatOptions {\n /**\n * Emit ANSI escapes. Off when the text becomes an `Error` message —\n * whoever prints it decides its formatting, and colored escapes inside\n * an exception leak into logs and stack traces.\n */\n color?: boolean;\n}\n\n/**\n * Format warnings for terminal output.\n *\n * Groups by severity, uses colors, and includes fix suggestions.\n */\nexport function formatConventionWarnings(\n warnings: ConventionWarning[],\n options: FormatOptions = {}\n): string {\n const { color = true } = options;\n const style = (fmt: Format, text: string) => (color ? styleText(fmt, text, noValidate) : text);\n if (warnings.length === 0) return '';\n\n const errors = warnings.filter((w) => w.level === 'error');\n const warns = warnings.filter((w) => w.level === 'warn');\n\n const lines: string[] = [];\n\n if (errors.length > 0) {\n lines.push(\n `${style(['red', 'bold'], '[timber]')} ${style('red', `${errors.length} configuration error${errors.length !== 1 ? 's' : ''}:`)}`\n );\n for (const e of errors) {\n lines.push('');\n lines.push(` ${style('red', '✗')} ${e.summary}`);\n lines.push(style('dim', e.details));\n }\n }\n\n if (warns.length > 0) {\n if (errors.length > 0) lines.push('');\n lines.push(\n `${style(['yellow', 'bold'], '[timber]')} ${style('yellow', `${warns.length} configuration warning${warns.length !== 1 ? 's' : ''}:`)}`\n );\n for (const w of warns) {\n lines.push('');\n lines.push(` ${style('yellow', '⚠')} ${w.summary}`);\n lines.push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