@timber-js/app 0.2.0-alpha.196 → 0.2.0-alpha.198
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-CWYtq6ii.js → actions-BS-m5SLv.js} +3 -3
- package/dist/_chunks/{actions-CWYtq6ii.js.map → actions-BS-m5SLv.js.map} +1 -1
- package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -1
- package/dist/_chunks/{build-manifest-DWppEdLB.js → build-manifest-DTmSGLRz.js} +51 -2
- package/dist/_chunks/build-manifest-DTmSGLRz.js.map +1 -0
- package/dist/_chunks/{cache-api-CQeYzA5g.js → cache-api-DqzgTEqk.js} +4 -49
- package/dist/_chunks/cache-api-DqzgTEqk.js.map +1 -0
- package/dist/_chunks/{chains-h7EO-u3n.js → chains-CZG7E5zg.js} +2 -2
- package/dist/_chunks/{chains-h7EO-u3n.js.map → chains-CZG7E5zg.js.map} +1 -1
- package/dist/_chunks/{cli-check-BVthpfLS.js → cli-check-dVDi1GQz.js} +3 -3
- package/dist/_chunks/{cli-check-BVthpfLS.js.map → cli-check-dVDi1GQz.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js → cli-schema-sync-DTy_-Msq.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-3Wutm8pH.js.map → cli-schema-sync-DTy_-Msq.js.map} +1 -1
- package/dist/_chunks/{cloudflare-BKJC3SC_.js → cloudflare-BFb__LYG.js} +2 -2
- package/dist/_chunks/{cloudflare-BKJC3SC_.js.map → cloudflare-BFb__LYG.js.map} +1 -1
- package/dist/_chunks/{convention-lint-DO10_pVl.js → convention-lint-Ph6luW4c.js} +4 -2
- package/dist/_chunks/convention-lint-Ph6luW4c.js.map +1 -0
- package/dist/_chunks/{error-boundary-D-lkwyaD.js → error-boundary-BvRCCmbN.js} +3 -3
- package/dist/_chunks/{error-boundary-D-lkwyaD.js.map → error-boundary-BvRCCmbN.js.map} +1 -1
- package/dist/_chunks/{href-validation-CMc5JRls.js → href-validation-BIrxavIy.js} +74 -2
- package/dist/_chunks/href-validation-BIrxavIy.js.map +1 -0
- package/dist/_chunks/{live-graph-Bx4HodF1.js → live-graph-BXDsdzBv.js} +3 -3
- package/dist/_chunks/{live-graph-Bx4HodF1.js.map → live-graph-BXDsdzBv.js.map} +1 -1
- package/dist/_chunks/{logger-pumCm3Il.js → logger-DDirEsn7.js} +3 -4
- package/dist/_chunks/{logger-pumCm3Il.js.map → logger-DDirEsn7.js.map} +1 -1
- package/dist/_chunks/navigation-root-B00jjGd5.js +233 -0
- package/dist/_chunks/navigation-root-B00jjGd5.js.map +1 -0
- package/dist/_chunks/{segment-context-CjOlyB8Y.js → param-value-C8TNYchQ.js} +2 -33
- package/dist/_chunks/param-value-C8TNYchQ.js.map +1 -0
- package/dist/_chunks/{poison-scan-BAxfTT5L.js → poison-scan-BoDLgbix.js} +2 -2
- package/dist/_chunks/{poison-scan-BAxfTT5L.js.map → poison-scan-BoDLgbix.js.map} +1 -1
- package/dist/_chunks/{router-ref-BzqbPwYC.js → router-ref-8gr8qsxN.js} +2 -2
- package/dist/_chunks/{router-ref-BzqbPwYC.js.map → router-ref-8gr8qsxN.js.map} +1 -1
- package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js → rsc-cache-key-ClUiXQnK.js} +2 -2
- package/dist/_chunks/{rsc-cache-key-DD0fl_-s.js.map → rsc-cache-key-ClUiXQnK.js.map} +1 -1
- package/dist/_chunks/{scanner-BRIOmHE2.js → scanner-tdFPvDYi.js} +174 -7
- package/dist/_chunks/scanner-tdFPvDYi.js.map +1 -0
- package/dist/_chunks/segment-context-D9_89u34.js +34 -0
- package/dist/_chunks/segment-context-D9_89u34.js.map +1 -0
- package/dist/_chunks/singleflight-2lUWfcAk.js +54 -0
- package/dist/_chunks/singleflight-2lUWfcAk.js.map +1 -0
- package/dist/_chunks/{ssr-data-Ya2HJPFp.js → ssr-data-BQGhTPAK.js} +2 -17
- package/dist/_chunks/ssr-data-BQGhTPAK.js.map +1 -0
- package/dist/_chunks/{walkers-BU6z9xRV.js → walkers-DNX05dC0.js} +2 -2
- package/dist/_chunks/{walkers-BU6z9xRV.js.map → walkers-DNX05dC0.js.map} +1 -1
- package/dist/adapters/cloudflare-dev.js +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/adapters/cloudflare.js +1 -1
- package/dist/adapters/nitro.d.ts +1 -1
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/crawl-entry.js +2 -2
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/index.js +1 -1
- package/dist/cache/singleflight.d.ts +2 -0
- package/dist/cache/singleflight.d.ts.map +1 -1
- package/dist/cli.js +2 -2
- package/dist/client/browser-entry/hydrate.d.ts +21 -15
- package/dist/client/browser-entry/hydrate.d.ts.map +1 -1
- package/dist/client/browser-entry/index.d.ts +4 -3
- package/dist/client/browser-entry/index.d.ts.map +1 -1
- package/dist/client/browser-entry/post-hydration.d.ts.map +1 -1
- package/dist/client/browser-entry/router-init.d.ts +17 -1
- package/dist/client/browser-entry/router-init.d.ts.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/global-context.d.ts +15 -0
- package/dist/client/global-context.d.ts.map +1 -0
- package/dist/client/index.js +138 -35
- package/dist/client/index.js.map +1 -1
- package/dist/client/internal.d.ts +0 -1
- package/dist/client/internal.d.ts.map +1 -1
- package/dist/client/internal.js +206 -55
- package/dist/client/internal.js.map +1 -1
- package/dist/client/link.d.ts.map +1 -1
- package/dist/client/location-search.d.ts +12 -0
- package/dist/client/location-search.d.ts.map +1 -0
- package/dist/client/navigation-api.d.ts.map +1 -1
- package/dist/client/navigation-commit.d.ts +18 -0
- package/dist/client/navigation-commit.d.ts.map +1 -1
- package/dist/client/navigation-context.d.ts +13 -11
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/navigation-root.d.ts +47 -108
- package/dist/client/navigation-root.d.ts.map +1 -1
- package/dist/client/navigation-transition.d.ts +136 -0
- package/dist/client/navigation-transition.d.ts.map +1 -0
- package/dist/client/nuqs-adapter.d.ts.map +1 -1
- package/dist/client/params-context.d.ts +4 -5
- package/dist/client/params-context.d.ts.map +1 -1
- package/dist/client/react-root.d.ts +44 -0
- package/dist/client/react-root.d.ts.map +1 -0
- package/dist/client/router-pipeline.d.ts +2 -2
- package/dist/client/router-pipeline.d.ts.map +1 -1
- package/dist/client/router-types.d.ts +12 -2
- 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 +39 -0
- package/dist/client/segment-cache.d.ts.map +1 -1
- package/dist/client/segment-context.d.ts.map +1 -1
- package/dist/client/segment-outlet.d.ts +25 -14
- package/dist/client/segment-outlet.d.ts.map +1 -1
- package/dist/client/segment-update-context.d.ts +3 -9
- package/dist/client/segment-update-context.d.ts.map +1 -1
- package/dist/client/slot-content-cache-context.d.ts +35 -0
- package/dist/client/slot-content-cache-context.d.ts.map +1 -0
- package/dist/client/ssr-data.d.ts +8 -2
- package/dist/client/ssr-data.d.ts.map +1 -1
- package/dist/client/state.d.ts +0 -15
- package/dist/client/state.d.ts.map +1 -1
- package/dist/client/use-pathname.d.ts +13 -11
- package/dist/client/use-pathname.d.ts.map +1 -1
- package/dist/client/use-search-params.d.ts +13 -13
- package/dist/client/use-search-params.d.ts.map +1 -1
- package/dist/client/use-segment-params.d.ts +18 -68
- package/dist/client/use-segment-params.d.ts.map +1 -1
- package/dist/config-types.d.ts +17 -0
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/cookies/index.js +1 -1
- package/dist/dev-tools/holding-server.d.ts +15 -10
- package/dist/dev-tools/holding-server.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -43
- package/dist/index.js.map +1 -1
- package/dist/plugins/dev-server.d.ts.map +1 -1
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/shims.d.ts.map +1 -1
- package/dist/plugins/static-build.d.ts +2 -2
- package/dist/plugins/static-build.d.ts.map +1 -1
- package/dist/routing/codegen-write.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/routing/interception-overlap.d.ts +35 -0
- package/dist/routing/interception-overlap.d.ts.map +1 -0
- package/dist/routing/interception.d.ts.map +1 -1
- package/dist/rsc-runtime/ssr.d.ts +3 -1
- package/dist/rsc-runtime/ssr.d.ts.map +1 -1
- package/dist/server/als-registry.d.ts +6 -0
- package/dist/server/als-registry.d.ts.map +1 -1
- package/dist/server/csp-nonce.d.ts +45 -0
- package/dist/server/csp-nonce.d.ts.map +1 -0
- package/dist/server/default-status-page.d.ts.map +1 -1
- package/dist/server/deny-renderer.d.ts.map +1 -1
- package/dist/server/flight-scripts.d.ts +5 -2
- package/dist/server/flight-scripts.d.ts.map +1 -1
- package/dist/server/html-injector-core.d.ts +17 -2
- package/dist/server/html-injector-core.d.ts.map +1 -1
- package/dist/server/html-injectors.d.ts +3 -2
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +86 -37
- package/dist/server/internal.js.map +1 -1
- package/dist/server/metadata-render.d.ts.map +1 -1
- package/dist/server/node-stream-transforms.d.ts +3 -17
- package/dist/server/node-stream-transforms.d.ts.map +1 -1
- package/dist/server/nuqs-ssr-provider.d.ts +7 -3
- package/dist/server/nuqs-ssr-provider.d.ts.map +1 -1
- package/dist/server/pipeline-phases.d.ts.map +1 -1
- package/dist/server/prebuilt/key-discipline.d.ts +32 -3
- package/dist/server/prebuilt/key-discipline.d.ts.map +1 -1
- package/dist/server/primitives.d.ts.map +1 -1
- package/dist/server/render-utils.d.ts +4 -3
- package/dist/server/render-utils.d.ts.map +1 -1
- package/dist/server/rsc-entry/action-middleware-runner.d.ts.map +1 -1
- package/dist/server/rsc-entry/error-renderer.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
- package/dist/server/ssr-bridge-types.d.ts +22 -2
- package/dist/server/ssr-bridge-types.d.ts.map +1 -1
- package/dist/server/ssr-entry.d.ts.map +1 -1
- package/dist/server/ssr-render.d.ts +5 -1
- package/dist/server/ssr-render.d.ts.map +1 -1
- package/dist/server/ssr-wrappers.d.ts +59 -27
- package/dist/server/ssr-wrappers.d.ts.map +1 -1
- package/dist/server/types.d.ts +10 -0
- package/dist/server/types.d.ts.map +1 -1
- package/dist/shims/navigation-rsc.d.ts +21 -0
- package/dist/shims/navigation-rsc.d.ts.map +1 -0
- package/docs/api/30-api-server.mdx +1 -0
- package/docs/api/35-api-typescript.mdx +4 -83
- package/docs/learn/03-fetching-data.mdx +1 -1
- package/docs/learn/{03b-access-control.mdx → 04-access-control.mdx} +2 -17
- package/docs/learn/05-the-flush-point.mdx +175 -0
- package/docs/learn/{05-typed-params.mdx → 06-typed-params.mdx} +1 -1
- package/docs/learn/07-typed-routes.mdx +25 -49
- package/docs/learn/{08-streaming.mdx → 09-streaming.mdx} +1 -7
- package/docs/learn/{10-middleware.mdx → 11-middleware.mdx} +1 -0
- package/package.json +3 -3
- package/src/adapters/nitro.ts +7 -7
- package/src/cache/singleflight.ts +5 -0
- package/src/client/browser-entry/hydrate.ts +54 -104
- package/src/client/browser-entry/index.ts +16 -6
- package/src/client/browser-entry/post-hydration.ts +3 -2
- package/src/client/browser-entry/router-init.ts +84 -33
- package/src/client/global-context.ts +31 -0
- package/src/client/internal.ts +1 -2
- package/src/client/link.tsx +18 -18
- package/src/client/location-search.ts +15 -0
- package/src/client/navigation-api.ts +4 -2
- package/src/client/navigation-commit.ts +48 -2
- package/src/client/navigation-context.ts +25 -37
- package/src/client/navigation-root.tsx +55 -411
- package/src/client/navigation-transition.ts +278 -0
- package/src/client/nuqs-adapter.tsx +4 -5
- package/src/client/params-context.ts +13 -18
- package/src/client/react-root.ts +72 -0
- package/src/client/router-lifecycle.ts +1 -1
- package/src/client/router-pipeline.ts +96 -22
- package/src/client/router-types.ts +12 -2
- package/src/client/router.ts +48 -36
- package/src/client/segment-cache.ts +70 -2
- package/src/client/segment-context.ts +7 -4
- package/src/client/segment-outlet.tsx +41 -86
- package/src/client/segment-update-context.ts +7 -26
- package/src/client/slot-content-cache-context.ts +43 -0
- package/src/client/ssr-data.ts +8 -2
- package/src/client/state.ts +0 -26
- package/src/client/use-pathname.ts +21 -31
- package/src/client/use-search-params.ts +31 -29
- package/src/client/use-segment-params.ts +27 -126
- package/src/config-types.ts +17 -0
- package/src/config-validation.ts +17 -0
- package/src/dev-tools/holding-server.ts +23 -12
- package/src/index.ts +26 -11
- package/src/plugins/dev-server.ts +9 -12
- package/src/plugins/entries.ts +3 -0
- package/src/plugins/shims.ts +8 -7
- package/src/plugins/static-build.ts +9 -5
- package/src/react-canary.d.ts +2 -0
- package/src/routing/codegen-write.ts +2 -0
- package/src/routing/interception-overlap.ts +141 -0
- package/src/routing/interception.ts +118 -5
- package/src/rsc-runtime/ssr.ts +3 -2
- package/src/server/als-registry.ts +6 -0
- package/src/server/csp-nonce.ts +70 -0
- package/src/server/default-status-page.ts +1 -0
- package/src/server/deny-renderer.ts +7 -3
- package/src/server/flight-scripts.ts +9 -4
- package/src/server/html-injector-core.ts +26 -9
- package/src/server/html-injectors.ts +8 -8
- package/src/server/metadata-render.ts +26 -4
- package/src/server/node-stream-transforms.ts +7 -20
- package/src/server/nuqs-ssr-provider.tsx +8 -7
- package/src/server/pipeline-phases.ts +5 -0
- package/src/server/prebuilt/key-discipline.ts +82 -13
- package/src/server/prebuilt-runtime.ts +2 -2
- package/src/server/primitives.ts +4 -4
- package/src/server/render-utils.ts +8 -4
- package/src/server/rsc-entry/action-middleware-runner.ts +7 -0
- package/src/server/rsc-entry/error-renderer.ts +5 -2
- package/src/server/rsc-entry/index.ts +8 -0
- package/src/server/rsc-entry/ssr-renderer.ts +11 -4
- package/src/server/ssr-bridge-types.ts +22 -2
- package/src/server/ssr-entry.ts +35 -28
- package/src/server/ssr-render.ts +13 -4
- package/src/server/ssr-wrappers.tsx +81 -61
- package/src/server/types.ts +10 -0
- package/src/shared/slot-params.ts +3 -4
- package/src/shims/navigation-rsc.ts +47 -0
- package/dist/_chunks/build-manifest-DWppEdLB.js.map +0 -1
- package/dist/_chunks/cache-api-CQeYzA5g.js.map +0 -1
- package/dist/_chunks/convention-lint-DO10_pVl.js.map +0 -1
- package/dist/_chunks/href-validation-CMc5JRls.js.map +0 -1
- package/dist/_chunks/scanner-BRIOmHE2.js.map +0 -1
- package/dist/_chunks/segment-context-CjOlyB8Y.js.map +0 -1
- package/dist/_chunks/slot-params-BCTmZkQB.js +0 -76
- package/dist/_chunks/slot-params-BCTmZkQB.js.map +0 -1
- package/dist/_chunks/ssr-data-Ya2HJPFp.js.map +0 -1
- package/dist/_chunks/use-segment-params-DzTBpkvj.js +0 -398
- package/dist/_chunks/use-segment-params-DzTBpkvj.js.map +0 -1
- package/docs/learn/04-loading-states.mdx +0 -67
- package/docs/learn/04b-the-flush-point.mdx +0 -115
- package/docs/learn/12-client-navigation.mdx +0 -176
- package/docs/learn/13-configuration.mdx +0 -166
- package/docs/more/01-advanced-routing.mdx +0 -344
- package/docs/more/02-advanced-forms.mdx +0 -137
- package/docs/more/03-coming-from-nextjs.mdx +0 -186
- package/docs/more/04-metadata-and-fonts.mdx +0 -193
- package/docs/more/04b-mdx.mdx +0 -229
- package/docs/more/05-content-collections.mdx +0 -90
- package/docs/more/06-instrumentation.mdx +0 -214
- package/docs/more/07-security.mdx +0 -129
- package/docs/more/08-developer-experience.mdx +0 -134
- package/docs/more/40-why-timber.mdx +0 -50
- package/docs/more/41-timber-vs-nextjs.mdx +0 -81
- package/docs/more/42-timber-vs-others.mdx +0 -68
- package/docs/more/50-ai-agent-instructions.mdx +0 -171
- /package/docs/learn/{06-forms-and-actions.mdx → 08-forms-and-actions.mdx} +0 -0
- /package/docs/learn/{09-caching.mdx → 10-caching.mdx} +0 -0
- /package/docs/learn/{11-error-handling.mdx → 12-error-handling.mdx} +0 -0
- /package/docs/learn/{14-deploying.mdx → 13-deploying.mdx} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as revalidationAls } from "./als-registry-C6kcfprT.js";
|
|
2
|
-
import { J as withSpan, _ as RedirectSignal, g as DenySignal } from "./logger-
|
|
3
|
-
import { t as cache } from "./cache-api-
|
|
2
|
+
import { J as withSpan, _ as RedirectSignal, g as DenySignal } from "./logger-DDirEsn7.js";
|
|
3
|
+
import { t as cache } from "./cache-api-DqzgTEqk.js";
|
|
4
4
|
//#region src/server/form-data.ts
|
|
5
5
|
/**
|
|
6
6
|
* FormData preprocessing — schema-agnostic conversion of FormData to typed objects.
|
|
@@ -315,4 +315,4 @@ async function executeAction(actionFn, args, config = {}, spanMeta) {
|
|
|
315
315
|
//#endregion
|
|
316
316
|
export { parseFormData as a, coerce as i, revalidatePath as n, revalidateTag as r, executeAction as t };
|
|
317
317
|
|
|
318
|
-
//# sourceMappingURL=actions-
|
|
318
|
+
//# sourceMappingURL=actions-BS-m5SLv.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actions-CWYtq6ii.js","names":[],"sources":["../../src/server/form-data.ts","../../src/server/actions.ts"],"sourcesContent":["/**\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 * - **Empty strings → undefined**: Enables `.optional()` semantics in schemas\n * - **Empty Files → undefined**: File inputs with no selection become `undefined`\n * - **Strips `$ACTION_*` fields**: React's internal hidden fields are excluded\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\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 if (current[part] === undefined || current[part] === null) {\n current[part] = {};\n }\n // If current[part] is not an object (e.g., a string from a non-dotted key),\n // the dot-path takes precedence\n if (typeof current[part] !== 'object' || current[part] instanceof File) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]] = value;\n }\n\n return result;\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// ─── 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:\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\n * z.unknown().transform(coerce.text).pipe(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.\n * - revalidateTag(tag) invalidates timber.cache entries by tag.\n *\n * Both are callable from anywhere on the server — actions, API routes, handlers.\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 { DenySignal, RedirectSignal } from './primitives.ts';\nimport { withSpan } from './tracing.ts';\nimport { revalidationAls, type RevalidationState } from './als-registry.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 `applyRevalidation`.\n */\n payload: unknown;\n}\n\n/** Renderer function that builds a React element tree for a given path. */\nexport type RevalidateRenderer = (path: string) => Promise<RevalidationResult>;\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\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 /** Redirect location if a RedirectSignal was thrown during revalidation. */\n redirectTo?: string;\n /** Redirect status code. */\n redirectStatus?: number;\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/**\n * Get the current revalidation state. Throws if called outside an action context.\n * @internal\n */\nfunction getRevalidationState(): RevalidationState {\n const state = revalidationAls.getStore();\n if (!state) {\n throw new Error(\n 'revalidatePath/revalidateTag called outside of a server action context. ' +\n 'These functions can only be called during action execution.'\n );\n }\n return state;\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 * Can be called from server actions, API routes, or any server-side context.\n *\n * @param path - The path to re-render (e.g. '/dashboard', '/todos').\n */\nexport function revalidatePath(path: string): void {\n const state = getRevalidationState();\n if (!state.paths.includes(path)) {\n state.paths.push(path);\n }\n}\n\n/**\n * Invalidate all timber.cache entries tagged with `tag`.\n * Does not return a payload — the next request for an invalidated entry re-executes.\n *\n * @param tag - The cache tag to invalidate (e.g. 'products', 'user:123').\n */\nexport function revalidateTag(tag: string): void {\n const state = getRevalidationState();\n if (!state.tags.includes(tag)) {\n state.tags.push(tag);\n }\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 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 (error instanceof RedirectSignal) {\n redirectTo = error.location;\n redirectStatus = error.status;\n } else {\n throw error;\n }\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 }\n }\n }\n\n // Process path revalidation — build element tree (not yet serialized)\n let revalidation: RevalidationResult | undefined;\n if (state.paths.length > 0 && config.renderer) {\n // For now, render the first revalidated path.\n // Multiple paths could be supported via multipart streaming in the future.\n const path = state.paths[0];\n try {\n revalidation = await config.renderer(path);\n } catch (renderError) {\n if (renderError instanceof RedirectSignal) {\n // Revalidation triggered a redirect (e.g., session expired,\n // middleware on the target path called `redirect()`).\n redirectTo = renderError.location;\n redirectStatus = renderError.status;\n } else if (renderError instanceof DenySignal) {\n // Target path's middleware/access denied this user.\n //\n // Dropping the revalidation here is the security boundary added\n // in TIM-996: without this branch, a DenySignal would fall into\n // the `console.error` path AND the element tree would have\n // already been built and serialized — leaking a privileged RSC\n // payload to the action submitter. By the time the signal\n // surfaces, the renderer has thrown BEFORE building the tree,\n // so we simply drop `revalidation` and ship the action result\n // alone. The action itself still succeeded.\n console.error(\n `[timber] revalidatePath dropped — target middleware denied (status ${renderError.status})`\n );\n } else {\n // Log but don't fail the action — revalidation is best-effort.\n // Includes input-validation rejections from the renderer\n // (e.g., revalidatePath('//evil.com/admin')).\n console.error('[timber] revalidatePath render failed:', renderError);\n }\n }\n }\n\n return {\n actionResult,\n revalidation,\n ...(redirectTo ? { redirectTo, redirectStatus } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,cAAc,UAA6C;CACzE,MAAM,OAAgC,CAAC;CAEvC,KAAK,MAAM,OAAO,IAAI,IAAI,SAAS,KAAK,CAAC,GAAG;EAE1C,IAAI,IAAI,WAAW,UAAU,GAAG;EAMhC,IAAI,eAAe,IAAI,GAAG,GAAG;EAG7B,MAAM,YADS,SAAS,OAAO,GACb,CAAA,CAAO,IAAI,cAAc;EAE3C,IAAI,UAAU,WAAW,GACvB,KAAK,OAAO,UAAU;OAItB,KAAK,OAAO,UAAU,QAAQ,MAAM,MAAM,KAAA,KAAa,MAAM,EAAE;CAEnE;CAGA,OAAO,eAAe,IAAI;AAC5B;;;;;;;;;AAUA,SAAS,eAAe,OAAoC;CAE1D,IAAI,iBAAiB,QAAQ,MAAM,SAAS,KAAK,MAAM,SAAS,IAC9D;CAGF,OAAO;AACT;;;;;;;;AASA,SAAS,eAAe,MAAwD;CAC9E,MAAM,SAAkC,CAAC;CACzC,IAAI,cAAc;CAGlB,KAAK,MAAM,OAAO,OAAO,KAAK,IAAI,GAChC,IAAI,IAAI,SAAS,GAAG,GAAG;EACrB,cAAc;EACd;CACF;CAKF,IAAI,CAAC,aAAa,OAAO;CAEzB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAI/C,MAAM,QAAQ,IAAI,MAAM,GAAG;EAC3B,IAAI,MAAM,MAAM,MAAM,eAAe,IAAI,CAAC,CAAC,GAAG;EAE9C,IAAI,MAAM,WAAW,GAAG;GACtB,OAAO,MAAM,MAAM;GACnB;EACF;EAEA,IAAI,UAAmC;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aAAa;GACpB,IAAI,uBAAuB,gBAAgB;IAGzC,aAAa,YAAY;IACzB,iBAAiB,YAAY;GAC/B,OAAO,IAAI,uBAAuB,YAWhC,QAAQ,MACN,sEAAsE,YAAY,OAAO,EAC3F;QAKA,QAAQ,MAAM,0CAA0C,WAAW;EAEvE;CACF;CAEA,OAAO;EACL;EACA;EACA,GAAI,aAAa;GAAE;GAAY;EAAe,IAAI,CAAC;CACrD;AACF"}
|
|
1
|
+
{"version":3,"file":"actions-BS-m5SLv.js","names":[],"sources":["../../src/server/form-data.ts","../../src/server/actions.ts"],"sourcesContent":["/**\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 * - **Empty strings → undefined**: Enables `.optional()` semantics in schemas\n * - **Empty Files → undefined**: File inputs with no selection become `undefined`\n * - **Strips `$ACTION_*` fields**: React's internal hidden fields are excluded\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\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 if (current[part] === undefined || current[part] === null) {\n current[part] = {};\n }\n // If current[part] is not an object (e.g., a string from a non-dotted key),\n // the dot-path takes precedence\n if (typeof current[part] !== 'object' || current[part] instanceof File) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n\n current[parts[parts.length - 1]] = value;\n }\n\n return result;\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// ─── 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:\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\n * z.unknown().transform(coerce.text).pipe(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.\n * - revalidateTag(tag) invalidates timber.cache entries by tag.\n *\n * Both are callable from anywhere on the server — actions, API routes, handlers.\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 { DenySignal, RedirectSignal } from './primitives.ts';\nimport { withSpan } from './tracing.ts';\nimport { revalidationAls, type RevalidationState } from './als-registry.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 `applyRevalidation`.\n */\n payload: unknown;\n}\n\n/** Renderer function that builds a React element tree for a given path. */\nexport type RevalidateRenderer = (path: string) => Promise<RevalidationResult>;\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\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 /** Redirect location if a RedirectSignal was thrown during revalidation. */\n redirectTo?: string;\n /** Redirect status code. */\n redirectStatus?: number;\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/**\n * Get the current revalidation state. Throws if called outside an action context.\n * @internal\n */\nfunction getRevalidationState(): RevalidationState {\n const state = revalidationAls.getStore();\n if (!state) {\n throw new Error(\n 'revalidatePath/revalidateTag called outside of a server action context. ' +\n 'These functions can only be called during action execution.'\n );\n }\n return state;\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 * Can be called from server actions, API routes, or any server-side context.\n *\n * @param path - The path to re-render (e.g. '/dashboard', '/todos').\n */\nexport function revalidatePath(path: string): void {\n const state = getRevalidationState();\n if (!state.paths.includes(path)) {\n state.paths.push(path);\n }\n}\n\n/**\n * Invalidate all timber.cache entries tagged with `tag`.\n * Does not return a payload — the next request for an invalidated entry re-executes.\n *\n * @param tag - The cache tag to invalidate (e.g. 'products', 'user:123').\n */\nexport function revalidateTag(tag: string): void {\n const state = getRevalidationState();\n if (!state.tags.includes(tag)) {\n state.tags.push(tag);\n }\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 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 (error instanceof RedirectSignal) {\n redirectTo = error.location;\n redirectStatus = error.status;\n } else {\n throw error;\n }\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 }\n }\n }\n\n // Process path revalidation — build element tree (not yet serialized)\n let revalidation: RevalidationResult | undefined;\n if (state.paths.length > 0 && config.renderer) {\n // For now, render the first revalidated path.\n // Multiple paths could be supported via multipart streaming in the future.\n const path = state.paths[0];\n try {\n revalidation = await config.renderer(path);\n } catch (renderError) {\n if (renderError instanceof RedirectSignal) {\n // Revalidation triggered a redirect (e.g., session expired,\n // middleware on the target path called `redirect()`).\n redirectTo = renderError.location;\n redirectStatus = renderError.status;\n } else if (renderError instanceof DenySignal) {\n // Target path's middleware/access denied this user.\n //\n // Dropping the revalidation here is the security boundary added\n // in TIM-996: without this branch, a DenySignal would fall into\n // the `console.error` path AND the element tree would have\n // already been built and serialized — leaking a privileged RSC\n // payload to the action submitter. By the time the signal\n // surfaces, the renderer has thrown BEFORE building the tree,\n // so we simply drop `revalidation` and ship the action result\n // alone. The action itself still succeeded.\n console.error(\n `[timber] revalidatePath dropped — target middleware denied (status ${renderError.status})`\n );\n } else {\n // Log but don't fail the action — revalidation is best-effort.\n // Includes input-validation rejections from the renderer\n // (e.g., revalidatePath('//evil.com/admin')).\n console.error('[timber] revalidatePath render failed:', renderError);\n }\n }\n }\n\n return {\n actionResult,\n revalidation,\n ...(redirectTo ? { redirectTo, redirectStatus } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,cAAc,UAA6C;CACzE,MAAM,OAAgC,CAAC;CAEvC,KAAK,MAAM,OAAO,IAAI,IAAI,SAAS,KAAK,CAAC,GAAG;EAE1C,IAAI,IAAI,WAAW,UAAU,GAAG;EAMhC,IAAI,eAAe,IAA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,MAAM,CAAC;CAAE;CACvD,IAAI;CACJ,IAAI;CACJ,IAAI;CAIJ,MAAM,gBAAgB,IAAI,OAAO,YAAY;EAC3C,IAAI;GACF,eAAe,MAAM,SACnB,iBACA;IACE,GAAI,UAAU,aAAa,EAAE,sBAAsB,SAAS,WAAW,IAAI,CAAC;IAC5E,GAAI,UAAU,aAAa,EAAE,sBAAsB,SAAS,WAAW,IAAI,CAAC;GAC9E,SACM,SAAS,GAAG,IAAI,CACxB;EACF,SAAS,OAAO;GACd,IAAI,iBAAiB,gBAAgB;IACnC,aAAa,MAAM;IACnB,iBAAiB,MAAM;GACzB,OACE,MAAM;EAEV;CACF,CAAC;CAQD,IAAI,MAAM,KAAK,SAAS,GAAG;EAQzB,MAAM,UAAU,MAAM,QAAQ,WAAW,MAAM,KAAK,KAAK,QAAQ,MAAM,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC;EAC3F,KAAK,MAAM,KAAK,SACd,IAAI,EAAE,WAAW,YACf,QAAQ,MAAM,+CAA+C,EAAE,MAAM;CAG3E;CAGA,IAAI;CACJ,IAAI,MAAM,MAAM,SAAS,KAAK,OAAO,UAAU;EAG7C,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI;GACF,eAAe,MAAM,OAAO,SAAS,IAAI;EAC3C,SAAS,aAAa;GACpB,IAAI,uBAAuB,gBAAgB;IAGzC,aAAa,YAAY;IACzB,iBAAiB,YAAY;GAC/B,OAAO,IAAI,uBAAuB,YAWhC,QAAQ,MACN,sEAAsE,YAAY,OAAO,EAC3F;QAKA,QAAQ,MAAM,0CAA0C,WAAW;EAEvE;CACF;CAEA,OAAO;EACL;EACA;EACA,GAAI,aAAa;GAAE;GAAY;EAAe,IAAI,CAAC;CACrD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"als-registry-C6kcfprT.js","names":[],"sources":["../../src/server/als-registry.ts"],"sourcesContent":["/**\n * Centralized AsyncLocalStorage registry for server-side per-request state.\n *\n * ALL ALS instances used by the server framework live here. Individual\n * modules (request-context.ts, tracing.ts, actions.ts, etc.) import from\n * this registry and re-export public accessor functions.\n *\n * Why: ALS instances require singleton semantics — if two copies of the\n * same ALS exist (one from a relative import, one from a barrel import,\n * or the same file re-evaluated by Vite after an HMR invalidation), one\n * module writes to its copy and another reads from an empty copy.\n * Centralizing ALS creation in a single module + anchoring each instance\n * on `globalThis` under a `Symbol.for(...)` key eliminates this class of\n * bug, including the Vite-dev case where module instance split would\n * otherwise hand two copies of this file out of a single evaluation cycle.\n *\n * The `timber-shims` plugin remaps `@timber-js/app/server` to src/ in\n * RSC and SSR environments so import-specifier paths converge here, and\n * the `globalThis[SYMBOL_FOR]` anchor below closes the remaining gap: any\n * second evaluation of this module picks up the ALS the first evaluation\n * already stored rather than instantiating a fresh one. Same pattern the\n * Cloudflare bindings ALS uses in `adapters/cloudflare.ts`.\n *\n * DO NOT create ALS instances outside this file. If you need a new ALS,\n * add it here and import from `./als-registry.js` in the consuming module.\n * Inside this file, always route through `getOrCreateAls(symbol)` — a raw\n * `new AsyncLocalStorage()` reintroduces the instance-split hazard.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\". Regression test:\n * `tests/als-registry-singleton.test.ts`.\n */\n\nimport '#server-only-guard';\nimport type { CoercedParams } from '../shared/param-value.ts';\nimport type { SlotParamsRecord } from '../shared/slot-params.ts';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DebugComponentEntry } from './rsc-entry/helpers.ts';\n\n/**\n * Return a process-wide singleton `AsyncLocalStorage` keyed by `symbol`.\n *\n * `Symbol.for(...)` keys live in the cross-realm symbol registry, and\n * `globalThis` is shared across every module evaluation inside the same\n * Node.js process. Together they give a stable anchor that survives\n * re-evaluation of this file — the second evaluation observes the\n * `globalThis[symbol]` slot already populated by the first and hands\n * back the identical ALS instance.\n */\nfunction getOrCreateAls<T>(symbol: symbol): AsyncLocalStorage<T> {\n const g = globalThis as unknown as Record<symbol, unknown>;\n const existing = g[symbol];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<T>;\n }\n const created = new AsyncLocalStorage<T>();\n g[symbol] = created;\n return created;\n}\n\n// ─── Request Context ──────────────────────────────────────────────────────\n// Used by: request-context.ts (getHeaders(), getCookies(), getSearchParams())\n// Design doc: design/04-authorization.md\n\n/** @internal — import via request-context.ts public API */\nexport const requestContextAls = getOrCreateAls<RequestContextStore>(\n Symbol.for('timber:request-context-als')\n);\n\nexport interface RequestContextStore {\n /** Incoming request headers (read-only view). */\n headers: Headers;\n /** Raw cookie header string, parsed lazily into a Map on first access. */\n cookieHeader: string;\n /** Lazily-parsed cookie map (mutable — reflects write-overlay from set()). */\n parsedCookies?: Map<string, string>;\n /** Original (pre-overlay) frozen headers, kept for overlay merging. */\n originalHeaders: Headers;\n /**\n * Raw URLSearchParams for the current request.\n * To get typed parsed params, import a search params definition and\n * call `.parse(searchParams())`.\n */\n searchParams: URLSearchParams;\n /**\n * Raw search string from the request URL (e.g. \"?foo=bar&baz=1\").\n * Available synchronously for use in `redirect()` with `preserveSearchParams`.\n */\n searchString: string;\n /**\n * Coerced segment params for the current request.\n * Set by the pipeline after route matching and param coercion, before\n * middleware and rendering. Pages and layouts read params via\n * `getSegmentParams()` instead of receiving them as a prop.\n *\n * See design/07-routing.md §\"params.ts — Convention File for Typed Params\"\n */\n segmentParams?: CoercedParams;\n /**\n * The matched segment path (e.g. '/(browse)/[artistSlug]/[year]').\n * Includes route groups and parallel slots — uniquely identifies the\n * segment in the route tree. Set by the pipeline alongside segmentParams.\n * Used by getSegmentParams() for dev-mode validation.\n * See design/41-global-params.md §Runtime Validation\n */\n matchedSegmentPath?: string;\n /**\n * Per-slot coerced segment params, keyed by the slot's full tree path\n * (e.g. '/(browse)/@shows/[artistSlug]/[...year]').\n *\n * Each slot walks its own segment tree and may interpret URL parts\n * differently from the main route (e.g. catch-all vs dynamic). This\n * map stores slot-specific params so getSegmentParams(segmentPath)\n * returns the correct types for slot pages.\n *\n * See design/07-routing.md §\"Parallel Slot Params\"\n */\n slotParams?: SlotParamsRecord;\n /** Outgoing Set-Cookie entries (name → serialized value + options). Last write wins. */\n cookieJar: Map<string, CookieEntry>;\n /** Whether the response has flushed (headers committed). */\n flushed: boolean;\n /** Whether the current context allows cookie mutation. */\n mutableContext: boolean;\n /**\n * Set by AccessGate or PageDenyBoundary when a DenySignal is caught\n * server-side (inside the React tree, before React Flight sees it).\n * The pipeline reads this after render to set the HTTP status code.\n * See TIM-666.\n */\n denyStatus?: number;\n /**\n * Callback fired when setDenyStatus() is called. Used by shellSettled\n * to short-circuit when any component catches a DenySignal in-tree,\n * regardless of which component caught it (AccessGate, TracedLayout,\n * or PageDenyBoundary). See TIM-1208.\n */\n onDenyStatus?: () => void;\n /**\n * Dev-only: getter for the current request's RSC debug components.\n * Set by renderRoute() so onPipelineError can include component tree\n * context for render-phase errors without module-level shared state.\n */\n debugComponentsGetter?: () => DebugComponentEntry[];\n /**\n * Index of the first segment whose AccessGate denied during render.\n * Recorded by AccessGate when it catches a DenySignal so post-render\n * consumers (buildSegmentInfo, X-Timber-Segments header) can bound\n * the segment list without a pre-render access pass. Infinity when\n * no segment denied. See TIM-1363.\n */\n _firstDeniedSegmentIndex?: number;\n /**\n * Metadata entries collected during render by MetadataCollector.\n * Populated per-segment in tree order (root→page) during\n * renderToReadableStream. Entries may contain promises for dynamic\n * metadata (resolved concurrently with page rendering, TIM-1367).\n * MetadataHead awaits all entries before merging.\n * See TIM-1363, TIM-1367, design/16-metadata.md.\n */\n _metadataEntries?: Array<{\n metadata: import('./types.ts').Metadata | Promise<import('./types.ts').Metadata | null>;\n isPage: boolean;\n }>;\n}\n\n/** A single outgoing cookie entry in the cookie jar. */\nexport interface CookieEntry {\n name: string;\n value: string;\n options: import('./cookie-context.ts').CookieOptions;\n}\n\n// ─── Tracing ──────────────────────────────────────────────────────────────\n// Used by: tracing.ts (getTraceId(), getSpanId())\n// Design doc: design/17-logging.md\n\nexport interface TraceStore {\n /** 32-char lowercase hex trace ID (OTEL or UUID fallback). */\n traceId: string;\n /** OTEL span ID if available, undefined otherwise. */\n spanId?: string;\n /**\n * Innermost active native platform span (e.g. Cloudflare's `Span` from\n * tracing.enterSpan()). Tracked so setSpanAttribute() can set attributes\n * after span creation — the platform API has no getActiveSpan() equivalent.\n * Saved/restored by withSpan() around each callback. See TIM-1135.\n */\n platformSpan?: import('./tracing.ts').PlatformSpan;\n}\n\n/** @internal — import via tracing.ts public API */\nexport const traceAls = getOrCreateAls<TraceStore>(Symbol.for('timber:trace-als'));\n\n// ─── Server-Timing ────────────────────────────────────────────────────────\n// Used by: server-timing.ts (recordTiming(), withTiming())\n// Design doc: (dev-only performance instrumentation)\n\nexport interface TimingStore {\n entries: import('./server-timing.ts').TimingEntry[];\n}\n\n/** @internal — import via server-timing.ts public API */\nexport const timingAls = getOrCreateAls<TimingStore>(Symbol.for('timber:timing-als'));\n\n// ─── Revalidation ─────────────────────────────────────────────────────────\n// Used by: actions.ts (revalidatePath(), revalidateTag())\n// Design doc: design/08-forms-and-actions.md\n\nexport interface RevalidationState {\n /** Paths to re-render (populated by revalidatePath calls). */\n paths: string[];\n /** Tags to invalidate (populated by revalidateTag calls). */\n tags: string[];\n}\n\n/** @internal — import via actions.ts public API */\nexport const revalidationAls = getOrCreateAls<RevalidationState>(\n Symbol.for('timber:revalidation-als')\n);\n\n// ─── Form Flash ───────────────────────────────────────────────────────────\n// Used by: form-flash.ts (getFormFlash())\n// Design doc: design/08-forms-and-actions.md §\"No-JS Error Round-Trip\"\n\n/** @internal — import via form-flash.ts public API */\nexport const formFlashAls = getOrCreateAls<import('./form-flash.ts').FormFlashData>(\n Symbol.for('timber:form-flash-als')\n);\n\n// ─── Early Hints Sender ──────────────────────────────────────────────────\n// Used by: early-hints-sender.ts (sendEarlyHints103())\n// Design doc: design/02-rendering-pipeline.md §\"Early Hints (103)\"\n\n/** Function that sends Link header values as a 103 Early Hints response. */\nexport type EarlyHintsSenderFn = (links: string[]) => void;\n\n/** @internal — import via early-hints-sender.ts public API */\nexport const earlyHintsSenderAls = getOrCreateAls<EarlyHintsSenderFn>(\n Symbol.for('timber:early-hints-sender-als')\n);\n\n// ─── waitUntil Bridge ────────────────────────────────────────────────────\n// Used by: waituntil-bridge.ts (waitUntil())\n// Design doc: design/11-platform.md §\"waitUntil()\"\n\n/** Function that extends the request lifecycle with a background promise. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** @internal — import via waituntil-bridge.ts public API */\nexport const waitUntilAls = getOrCreateAls<WaitUntilFn>(Symbol.for('timber:wait-until-als'));\n\n// ─── Workers Cache Purge Bridge ─────────────────────────────────────────\n// Used by: workers-cache-bridge.ts (runWithWorkersCachePurge())\n// Design doc: design/06-caching.md, design/25-production-deployments.md\n\n/** Workers Cache purge function from Cloudflare ExecutionContext.cache. */\nexport interface WorkersCachePurgeCtx {\n purge(opts: { tags: string[] }): Promise<void>;\n}\n\n/** @internal — import via workers-cache-bridge.ts public API */\nexport const workersCachePurgeAls = getOrCreateAls<WorkersCachePurgeCtx>(\n Symbol.for('timber:workers-cache-purge-als')\n);\n"],"mappings":";;;;;;;;;;;;;AAiDA,SAAS,eAAkB,QAAsC;CAC/D,MAAM,IAAI;CACV,MAAM,WAAW,EAAE;CACnB,IAAI,oBAAoB,mBACtB,OAAO;CAET,MAAM,UAAU,IAAI,kBAAqB;CACzC,EAAE,UAAU;CACZ,OAAO;AACT;;AAOA,IAAa,oBAAoB,eAC/B,OAAO,IAAI,4BAA4B,CACzC;;AA6HA,IAAa,WAAW,eAA2B,OAAO,IAAI,kBAAkB,CAAC;;AAWjF,IAAa,YAAY,eAA4B,OAAO,IAAI,mBAAmB,CAAC;;AAcpF,IAAa,kBAAkB,eAC7B,OAAO,IAAI,yBAAyB,CACtC;;AAOA,IAAa,eAAe,eAC1B,OAAO,IAAI,uBAAuB,CACpC;;AAUA,IAAa,sBAAsB,eACjC,OAAO,IAAI,+BAA+B,CAC5C;;AAUA,IAAa,eAAe,eAA4B,OAAO,IAAI,uBAAuB,CAAC;;AAY3F,IAAa,uBAAuB,eAClC,OAAO,IAAI,gCAAgC,CAC7C"}
|
|
1
|
+
{"version":3,"file":"als-registry-C6kcfprT.js","names":[],"sources":["../../src/server/als-registry.ts"],"sourcesContent":["/**\n * Centralized AsyncLocalStorage registry for server-side per-request state.\n *\n * ALL ALS instances used by the server framework live here. Individual\n * modules (request-context.ts, tracing.ts, actions.ts, etc.) import from\n * this registry and re-export public accessor functions.\n *\n * Why: ALS instances require singleton semantics — if two copies of the\n * same ALS exist (one from a relative import, one from a barrel import,\n * or the same file re-evaluated by Vite after an HMR invalidation), one\n * module writes to its copy and another reads from an empty copy.\n * Centralizing ALS creation in a single module + anchoring each instance\n * on `globalThis` under a `Symbol.for(...)` key eliminates this class of\n * bug, including the Vite-dev case where module instance split would\n * otherwise hand two copies of this file out of a single evaluation cycle.\n *\n * The `timber-shims` plugin remaps `@timber-js/app/server` to src/ in\n * RSC and SSR environments so import-specifier paths converge here, and\n * the `globalThis[SYMBOL_FOR]` anchor below closes the remaining gap: any\n * second evaluation of this module picks up the ALS the first evaluation\n * already stored rather than instantiating a fresh one. Same pattern the\n * Cloudflare bindings ALS uses in `adapters/cloudflare.ts`.\n *\n * DO NOT create ALS instances outside this file. If you need a new ALS,\n * add it here and import from `./als-registry.js` in the consuming module.\n * Inside this file, always route through `getOrCreateAls(symbol)` — a raw\n * `new AsyncLocalStorage()` reintroduces the instance-split hazard.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\". Regression test:\n * `tests/als-registry-singleton.test.ts`.\n */\n\nimport '#server-only-guard';\nimport type { CoercedParams } from '../shared/param-value.ts';\nimport type { SlotParamsRecord } from '../shared/slot-params.ts';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DebugComponentEntry } from './rsc-entry/helpers.ts';\n\n/**\n * Return a process-wide singleton `AsyncLocalStorage` keyed by `symbol`.\n *\n * `Symbol.for(...)` keys live in the cross-realm symbol registry, and\n * `globalThis` is shared across every module evaluation inside the same\n * Node.js process. Together they give a stable anchor that survives\n * re-evaluation of this file — the second evaluation observes the\n * `globalThis[symbol]` slot already populated by the first and hands\n * back the identical ALS instance.\n */\nfunction getOrCreateAls<T>(symbol: symbol): AsyncLocalStorage<T> {\n const g = globalThis as unknown as Record<symbol, unknown>;\n const existing = g[symbol];\n if (existing instanceof AsyncLocalStorage) {\n return existing as AsyncLocalStorage<T>;\n }\n const created = new AsyncLocalStorage<T>();\n g[symbol] = created;\n return created;\n}\n\n// ─── Request Context ──────────────────────────────────────────────────────\n// Used by: request-context.ts (getHeaders(), getCookies(), getSearchParams())\n// Design doc: design/04-authorization.md\n\n/** @internal — import via request-context.ts public API */\nexport const requestContextAls = getOrCreateAls<RequestContextStore>(\n Symbol.for('timber:request-context-als')\n);\n\nexport interface RequestContextStore {\n /** Incoming request headers (read-only view). */\n headers: Headers;\n /** Raw cookie header string, parsed lazily into a Map on first access. */\n cookieHeader: string;\n /** Lazily-parsed cookie map (mutable — reflects write-overlay from set()). */\n parsedCookies?: Map<string, string>;\n /** Original (pre-overlay) frozen headers, kept for overlay merging. */\n originalHeaders: Headers;\n /**\n * CSP nonce, created the first time middleware reads `ctx.nonce`. Read by\n * the renderers via `getCspNonce()` and stamped on every inline script.\n * Absent when no middleware asked for one. See server/csp-nonce.ts.\n */\n cspNonce?: string;\n /**\n * Raw URLSearchParams for the current request.\n * To get typed parsed params, import a search params definition and\n * call `.parse(searchParams())`.\n */\n searchParams: URLSearchParams;\n /**\n * Raw search string from the request URL (e.g. \"?foo=bar&baz=1\").\n * Available synchronously for use in `redirect()` with `preserveSearchParams`.\n */\n searchString: string;\n /**\n * Coerced segment params for the current request.\n * Set by the pipeline after route matching and param coercion, before\n * middleware and rendering. Pages and layouts read params via\n * `getSegmentParams()` instead of receiving them as a prop.\n *\n * See design/07-routing.md §\"params.ts — Convention File for Typed Params\"\n */\n segmentParams?: CoercedParams;\n /**\n * The matched segment path (e.g. '/(browse)/[artistSlug]/[year]').\n * Includes route groups and parallel slots — uniquely identifies the\n * segment in the route tree. Set by the pipeline alongside segmentParams.\n * Used by getSegmentParams() for dev-mode validation.\n * See design/41-global-params.md §Runtime Validation\n */\n matchedSegmentPath?: string;\n /**\n * Per-slot coerced segment params, keyed by the slot's full tree path\n * (e.g. '/(browse)/@shows/[artistSlug]/[...year]').\n *\n * Each slot walks its own segment tree and may interpret URL parts\n * differently from the main route (e.g. catch-all vs dynamic). This\n * map stores slot-specific params so getSegmentParams(segmentPath)\n * returns the correct types for slot pages.\n *\n * See design/07-routing.md §\"Parallel Slot Params\"\n */\n slotParams?: SlotParamsRecord;\n /** Outgoing Set-Cookie entries (name → serialized value + options). Last write wins. */\n cookieJar: Map<string, CookieEntry>;\n /** Whether the response has flushed (headers committed). */\n flushed: boolean;\n /** Whether the current context allows cookie mutation. */\n mutableContext: boolean;\n /**\n * Set by AccessGate or PageDenyBoundary when a DenySignal is caught\n * server-side (inside the React tree, before React Flight sees it).\n * The pipeline reads this after render to set the HTTP status code.\n * See TIM-666.\n */\n denyStatus?: number;\n /**\n * Callback fired when setDenyStatus() is called. Used by shellSettled\n * to short-circuit when any component catches a DenySignal in-tree,\n * regardless of which component caught it (AccessGate, TracedLayout,\n * or PageDenyBoundary). See TIM-1208.\n */\n onDenyStatus?: () => void;\n /**\n * Dev-only: getter for the current request's RSC debug components.\n * Set by renderRoute() so onPipelineError can include component tree\n * context for render-phase errors without module-level shared state.\n */\n debugComponentsGetter?: () => DebugComponentEntry[];\n /**\n * Index of the first segment whose AccessGate denied during render.\n * Recorded by AccessGate when it catches a DenySignal so post-render\n * consumers (buildSegmentInfo, X-Timber-Segments header) can bound\n * the segment list without a pre-render access pass. Infinity when\n * no segment denied. See TIM-1363.\n */\n _firstDeniedSegmentIndex?: number;\n /**\n * Metadata entries collected during render by MetadataCollector.\n * Populated per-segment in tree order (root→page) during\n * renderToReadableStream. Entries may contain promises for dynamic\n * metadata (resolved concurrently with page rendering, TIM-1367).\n * MetadataHead awaits all entries before merging.\n * See TIM-1363, TIM-1367, design/16-metadata.md.\n */\n _metadataEntries?: Array<{\n metadata: import('./types.ts').Metadata | Promise<import('./types.ts').Metadata | null>;\n isPage: boolean;\n }>;\n}\n\n/** A single outgoing cookie entry in the cookie jar. */\nexport interface CookieEntry {\n name: string;\n value: string;\n options: import('./cookie-context.ts').CookieOptions;\n}\n\n// ─── Tracing ──────────────────────────────────────────────────────────────\n// Used by: tracing.ts (getTraceId(), getSpanId())\n// Design doc: design/17-logging.md\n\nexport interface TraceStore {\n /** 32-char lowercase hex trace ID (OTEL or UUID fallback). */\n traceId: string;\n /** OTEL span ID if available, undefined otherwise. */\n spanId?: string;\n /**\n * Innermost active native platform span (e.g. Cloudflare's `Span` from\n * tracing.enterSpan()). Tracked so setSpanAttribute() can set attributes\n * after span creation — the platform API has no getActiveSpan() equivalent.\n * Saved/restored by withSpan() around each callback. See TIM-1135.\n */\n platformSpan?: import('./tracing.ts').PlatformSpan;\n}\n\n/** @internal — import via tracing.ts public API */\nexport const traceAls = getOrCreateAls<TraceStore>(Symbol.for('timber:trace-als'));\n\n// ─── Server-Timing ────────────────────────────────────────────────────────\n// Used by: server-timing.ts (recordTiming(), withTiming())\n// Design doc: (dev-only performance instrumentation)\n\nexport interface TimingStore {\n entries: import('./server-timing.ts').TimingEntry[];\n}\n\n/** @internal — import via server-timing.ts public API */\nexport const timingAls = getOrCreateAls<TimingStore>(Symbol.for('timber:timing-als'));\n\n// ─── Revalidation ─────────────────────────────────────────────────────────\n// Used by: actions.ts (revalidatePath(), revalidateTag())\n// Design doc: design/08-forms-and-actions.md\n\nexport interface RevalidationState {\n /** Paths to re-render (populated by revalidatePath calls). */\n paths: string[];\n /** Tags to invalidate (populated by revalidateTag calls). */\n tags: string[];\n}\n\n/** @internal — import via actions.ts public API */\nexport const revalidationAls = getOrCreateAls<RevalidationState>(\n Symbol.for('timber:revalidation-als')\n);\n\n// ─── Form Flash ───────────────────────────────────────────────────────────\n// Used by: form-flash.ts (getFormFlash())\n// Design doc: design/08-forms-and-actions.md §\"No-JS Error Round-Trip\"\n\n/** @internal — import via form-flash.ts public API */\nexport const formFlashAls = getOrCreateAls<import('./form-flash.ts').FormFlashData>(\n Symbol.for('timber:form-flash-als')\n);\n\n// ─── Early Hints Sender ──────────────────────────────────────────────────\n// Used by: early-hints-sender.ts (sendEarlyHints103())\n// Design doc: design/02-rendering-pipeline.md §\"Early Hints (103)\"\n\n/** Function that sends Link header values as a 103 Early Hints response. */\nexport type EarlyHintsSenderFn = (links: string[]) => void;\n\n/** @internal — import via early-hints-sender.ts public API */\nexport const earlyHintsSenderAls = getOrCreateAls<EarlyHintsSenderFn>(\n Symbol.for('timber:early-hints-sender-als')\n);\n\n// ─── waitUntil Bridge ────────────────────────────────────────────────────\n// Used by: waituntil-bridge.ts (waitUntil())\n// Design doc: design/11-platform.md §\"waitUntil()\"\n\n/** Function that extends the request lifecycle with a background promise. */\nexport type WaitUntilFn = (promise: Promise<unknown>) => void;\n\n/** @internal — import via waituntil-bridge.ts public API */\nexport const waitUntilAls = getOrCreateAls<WaitUntilFn>(Symbol.for('timber:wait-until-als'));\n\n// ─── Workers Cache Purge Bridge ─────────────────────────────────────────\n// Used by: workers-cache-bridge.ts (runWithWorkersCachePurge())\n// Design doc: design/06-caching.md, design/25-production-deployments.md\n\n/** Workers Cache purge function from Cloudflare ExecutionContext.cache. */\nexport interface WorkersCachePurgeCtx {\n purge(opts: { tags: string[] }): Promise<void>;\n}\n\n/** @internal — import via workers-cache-bridge.ts public API */\nexport const workersCachePurgeAls = getOrCreateAls<WorkersCachePurgeCtx>(\n Symbol.for('timber:workers-cache-purge-als')\n);\n"],"mappings":";;;;;;;;;;;;;AAiDA,SAAS,eAAkB,QAAsC;CAC/D,MAAM,IAAI;CACV,MAAM,WAAW,EAAE;CACnB,IAAI,oBAAoB,mBACtB,OAAO;CAET,MAAM,UAAU,IAAI,kBAAqB;CACzC,EAAE,UAAU;CACZ,OAAO;AACT;;AAOA,IAAa,oBAAoB,eAC/B,OAAO,IAAI,4BAA4B,CACzC;;AAmIA,IAAa,WAAW,eAA2B,OAAO,IAAI,kBAAkB,CAAC;;AAWjF,IAAa,YAAY,eAA4B,OAAO,IAAI,mBAAmB,CAAC;;AAcpF,IAAa,kBAAkB,eAC7B,OAAO,IAAI,yBAAyB,CACtC;;AAOA,IAAa,eAAe,eAC1B,OAAO,IAAI,uBAAuB,CACpC;;AAUA,IAAa,sBAAsB,eACjC,OAAO,IAAI,+BAA+B,CAC5C;;AAUA,IAAa,eAAe,eAA4B,OAAO,IAAI,uBAAuB,CAAC;;AAY3F,IAAa,uBAAuB,eAClC,OAAO,IAAI,gCAAgC,CAC7C"}
|
|
@@ -1,3 +1,52 @@
|
|
|
1
|
+
import { r as requestContextAls } from "./als-registry-C6kcfprT.js";
|
|
2
|
+
//#region src/server/csp-nonce.ts
|
|
3
|
+
/**
|
|
4
|
+
* CSP nonce — per-request, generated on demand.
|
|
5
|
+
*
|
|
6
|
+
* timber emits several inline `<script>` tags per HTML response — React's
|
|
7
|
+
* bootstrap script and Fizz runtime, the Flight init/chunk scripts, the
|
|
8
|
+
* segment-tree script, and the post-flush noindex script. Under a strict
|
|
9
|
+
* `Content-Security-Policy` (`script-src 'nonce-…' 'strict-dynamic'`) every
|
|
10
|
+
* one of them needs the request's nonce or the browser refuses to run it.
|
|
11
|
+
*
|
|
12
|
+
* The app opts in by reading `ctx.nonce` in `middleware.ts` and putting it
|
|
13
|
+
* in the CSP header it sets through `ctx.headers`. The first read generates
|
|
14
|
+
* the value and stores it on the request context; the render pipeline reads
|
|
15
|
+
* it back with `getCspNonce()` and stamps it on every inline script. A
|
|
16
|
+
* request whose middleware never reads `ctx.nonce` has no nonce, and its
|
|
17
|
+
* markup is byte-identical to a render without this feature. timber does
|
|
18
|
+
* not parse the CSP header — the app owns the policy, timber owns the
|
|
19
|
+
* markup, and `ctx.nonce` is the one value both are built from.
|
|
20
|
+
*
|
|
21
|
+
* `proxy.ts` cannot participate: it only sees the finished response from
|
|
22
|
+
* `next()`, after the markup exists.
|
|
23
|
+
*
|
|
24
|
+
* See design/13-security.md §"Content Security Policy" (TIM-1414).
|
|
25
|
+
*/
|
|
26
|
+
/**
|
|
27
|
+
* Generate a CSP nonce: 128 random bits, base64. Matches CSP's
|
|
28
|
+
* `base64-value` grammar, so it is valid in the header verbatim and safe
|
|
29
|
+
* inside a double-quoted HTML attribute without escaping.
|
|
30
|
+
*/
|
|
31
|
+
function generateNonce() {
|
|
32
|
+
const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
|
|
33
|
+
let binary = "";
|
|
34
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
35
|
+
return btoa(binary);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The request's CSP nonce, creating it on first call. Backs the
|
|
39
|
+
* `ctx.nonce` getter on `MiddlewareContext`. Outside a request context
|
|
40
|
+
* (tests, build-time rendering) a fresh value is returned but not
|
|
41
|
+
* retained, since there is no request for it to belong to.
|
|
42
|
+
*/
|
|
43
|
+
function requestCspNonce() {
|
|
44
|
+
const store = requestContextAls.getStore();
|
|
45
|
+
if (!store) return generateNonce();
|
|
46
|
+
store.cspNonce ??= generateNonce();
|
|
47
|
+
return store.cspNonce;
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
1
50
|
//#region src/server/build-manifest.ts
|
|
2
51
|
/**
|
|
3
52
|
* Empty build manifest used in dev mode, and the single source of truth for
|
|
@@ -81,6 +130,6 @@ function collectRouteModulepreloads(segments, manifest) {
|
|
|
81
130
|
return result;
|
|
82
131
|
}
|
|
83
132
|
//#endregion
|
|
84
|
-
export { collectRouteModulepreloads as i, collectRouteCss as n, collectRouteFonts as r, EMPTY_BUILD_MANIFEST as t };
|
|
133
|
+
export { requestCspNonce as a, collectRouteModulepreloads as i, collectRouteCss as n, collectRouteFonts as r, EMPTY_BUILD_MANIFEST as t };
|
|
85
134
|
|
|
86
|
-
//# sourceMappingURL=build-manifest-
|
|
135
|
+
//# sourceMappingURL=build-manifest-DTmSGLRz.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"build-manifest-DTmSGLRz.js","names":[],"sources":["../../src/server/csp-nonce.ts","../../src/server/build-manifest.ts"],"sourcesContent":["/**\n * CSP nonce — per-request, generated on demand.\n *\n * timber emits several inline `<script>` tags per HTML response — React's\n * bootstrap script and Fizz runtime, the Flight init/chunk scripts, the\n * segment-tree script, and the post-flush noindex script. Under a strict\n * `Content-Security-Policy` (`script-src 'nonce-…' 'strict-dynamic'`) every\n * one of them needs the request's nonce or the browser refuses to run it.\n *\n * The app opts in by reading `ctx.nonce` in `middleware.ts` and putting it\n * in the CSP header it sets through `ctx.headers`. The first read generates\n * the value and stores it on the request context; the render pipeline reads\n * it back with `getCspNonce()` and stamps it on every inline script. A\n * request whose middleware never reads `ctx.nonce` has no nonce, and its\n * markup is byte-identical to a render without this feature. timber does\n * not parse the CSP header — the app owns the policy, timber owns the\n * markup, and `ctx.nonce` is the one value both are built from.\n *\n * `proxy.ts` cannot participate: it only sees the finished response from\n * `next()`, after the markup exists.\n *\n * See design/13-security.md §\"Content Security Policy\" (TIM-1414).\n */\n\nimport { requestContextAls } from './als-registry.ts';\n\n/**\n * Generate a CSP nonce: 128 random bits, base64. Matches CSP's\n * `base64-value` grammar, so it is valid in the header verbatim and safe\n * inside a double-quoted HTML attribute without escaping.\n */\nfunction generateNonce(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n let binary = '';\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary);\n}\n\n/**\n * The request's CSP nonce, creating it on first call. Backs the\n * `ctx.nonce` getter on `MiddlewareContext`. Outside a request context\n * (tests, build-time rendering) a fresh value is returned but not\n * retained, since there is no request for it to belong to.\n */\nexport function requestCspNonce(): string {\n const store = requestContextAls.getStore();\n if (!store) return generateNonce();\n store.cspNonce ??= generateNonce();\n return store.cspNonce;\n}\n\n/**\n * The request's CSP nonce if middleware asked for one, else `undefined` —\n * in which case the pipeline emits bare `<script>` tags.\n */\nexport function getCspNonce(): string | undefined {\n return requestContextAls.getStore()?.cspNonce;\n}\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n","/**\n * Build manifest types and utilities for CSS and JS asset tracking.\n *\n * The build manifest maps route segment file paths to their output\n * chunks from Vite's client build. This enables:\n * - <link rel=\"stylesheet\"> injection in HTML <head>\n * - <script type=\"module\"> with hashed URLs in production\n * - <link rel=\"modulepreload\"> for client chunk dependencies\n * - Link preload headers for Early Hints (103)\n *\n * In dev mode, Vite's HMR client handles CSS/JS injection, so the build\n * manifest is empty. In production, it's populated from Vite's\n * .vite/manifest.json after the client build.\n *\n * Design docs: 18-build-system.md §\"Build Manifest\", 02-rendering-pipeline.md §\"Early Hints\"\n */\n\n/** A font asset entry in the build manifest. */\nexport interface ManifestFontEntry {\n /** URL path to the font file (e.g. `/_timber/fonts/inter-latin-400-abc123.woff2`). */\n href: string;\n /** Font format (e.g. `woff2`). */\n format: string;\n /** Crossorigin attribute — always `anonymous` for fonts. */\n crossOrigin: string;\n}\n\n/** Build manifest mapping input file paths to output asset URLs. */\nexport interface BuildManifest {\n /** Map from input file path (relative to project root) to output CSS URLs. */\n css: Record<string, string[]>;\n /** Map from input file path to output JS chunk URL (hashed filename). */\n js: Record<string, string>;\n /** Map from input file path to transitive JS dependency URLs for modulepreload. */\n modulepreload: Record<string, string[]>;\n /** Map from input file path to font assets used by that module. */\n fonts: Record<string, ManifestFontEntry[]>;\n /**\n * Cache-busting hashes for metadata route files (opengraph-image, etc.).\n * Map from file path (relative to project root) to short content hash.\n * In dev mode this is empty — a startup nonce is used instead.\n */\n metadataRouteHashes?: Record<string, string>;\n /**\n * Static request-dependency map from the Vite plugin's module-graph analysis.\n * Map from segment entry file path to whether it's request-dependent.\n * Used by buildSegmentInfo() for X-Timber-Segments in production.\n */\n requestDep?: Record<string, boolean>;\n}\n\n/**\n * Empty build manifest used in dev mode, and the single source of truth for\n * what an empty manifest contains.\n *\n * `virtual:timber-build-manifest` serializes this constant into its generated\n * source rather than restating it — one literal for the dev module, one for the\n * production module's `globalThis.__TIMBER_BUILD_MANIFEST__ ?? …` fallback.\n * They were three hand-written objects that had already drifted: this one and\n * the dev literal were missing `requestDep` while the production fallback had\n * it, so a reader who grepped the built bundle for `requestDep` found the one\n * copy that mentioned it and read the fallback as the shipped map (TIM-1300).\n * A field added here now reaches every copy.\n */\nexport const EMPTY_BUILD_MANIFEST: BuildManifest = {\n css: {},\n js: {},\n modulepreload: {},\n fonts: {},\n metadataRouteHashes: {},\n requestDep: {},\n};\n\n/** Segment shape expected by collectRouteCss (matches ManifestSegmentNode). */\ninterface SegmentWithFiles {\n layout?: { filePath: string };\n page?: { filePath: string };\n}\n\n/**\n * Collect all CSS files needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting CSS for each layout and page.\n * Deduplicates while preserving order (root layout CSS first).\n */\nexport function collectRouteCss(segments: SegmentWithFiles[], manifest: BuildManifest): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const cssFiles = manifest.css[file.filePath];\n if (!cssFiles) continue;\n for (const url of cssFiles) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"stylesheet\"> tags for CSS URLs.\n *\n * Returns an HTML string to prepend to headHtml for injection\n * via injectHead() before </head>.\n */\nexport function buildCssLinkTags(cssUrls: string[]): string {\n // Emit only <link rel=\"stylesheet\"> — no preload tags. CSS preloading\n // is handled by 103 Early Hints (Link header) which fires before the\n // HTML stream. Float also emits `<link rel=\"stylesheet\" data-precedence>`\n // at the top of <head> during Fizz rendering — the browser discovers\n // CSS from that tag. A <link rel=\"preload\"> here would arrive *after*\n // Float's stylesheet tag and trigger \"Preload was ignored\" warnings.\n return cssUrls.map((url) => `<link rel=\"stylesheet\" href=\"${url}\">`).join('');\n}\n\n// ─── Font utilities ──────────────────────────────────────────────────────\n\n/**\n * Collect all font entries needed for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting fonts for each layout and page.\n * Deduplicates by href while preserving order.\n */\nexport function collectRouteFonts(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): ManifestFontEntry[] {\n const seen = new Set<string>();\n const result: ManifestFontEntry[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const fonts = manifest.fonts[file.filePath];\n if (!fonts) continue;\n for (const entry of fonts) {\n if (!seen.has(entry.href)) {\n seen.add(entry.href);\n result.push(entry);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"preload\"> tags for font assets.\n *\n * Font preloads use `as=font` and always include `crossorigin` (required\n * for font preloads even for same-origin resources per the spec).\n */\nexport function buildFontPreloadTags(fonts: ManifestFontEntry[]): string {\n return fonts\n .map(\n (f) =>\n `<link rel=\"preload\" href=\"${f.href}\" as=\"font\" type=\"font/${f.format}\" crossorigin=\"${f.crossOrigin}\">`\n )\n .join('');\n}\n\n// ─── JS chunk utilities ──────────────────────────────────────────────────\n\n/**\n * Collect modulepreload URLs for a matched route's segment chain.\n *\n * Walks segments root → leaf, collecting transitive JS dependencies\n * for each layout and page. Deduplicates across segments.\n */\nexport function collectRouteModulepreloads(\n segments: SegmentWithFiles[],\n manifest: BuildManifest\n): string[] {\n const seen = new Set<string>();\n const result: string[] = [];\n\n for (const segment of segments) {\n for (const file of [segment.layout, segment.page]) {\n if (!file) continue;\n const preloads = manifest.modulepreload[file.filePath];\n if (!preloads) continue;\n for (const url of preloads) {\n if (!seen.has(url)) {\n seen.add(url);\n result.push(url);\n }\n }\n }\n }\n\n return result;\n}\n\n/**\n * Generate <link rel=\"modulepreload\"> tags for JS dependency URLs.\n *\n * Modulepreload hints tell the browser to fetch and parse JS modules\n * before they're needed, reducing waterfall latency for dynamic imports.\n */\nexport function buildModulepreloadTags(urls: string[]): string {\n return urls.map((url) => `<link rel=\"modulepreload\" href=\"${url}\">`).join('');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,gBAAwB;CAC/B,MAAM,QAAQ,OAAO,gCAAgB,IAAI,WAAW,EAAE,CAAC;CACvD,IAAI,SAAS;CACb,KAAK,MAAM,KAAK,OAAO,UAAU,OAAO,aAAa,CAAC;CACtD,OAAO,KAAK,MAAM;AACpB;;;;;;;AAQA,SAAgB,kBAA0B;CACxC,MAAM,QAAQ,kBAAkB,SAAS;CACzC,IAAI,CAAC,OAAO,OAAO,cAAc;CACjC,MAAM,aAAa,cAAc;CACjC,OAAO,MAAM;AACf;;;;;;;;;;;;;;;;ACeA,IAAa,uBAAsC;CACjD,KAAK,CAAC;CACN,IAAI,CAAC;CACL,eAAe,CAAC;CAChB,OAAO,CAAC;CACR,qBAAqB,CAAC;CACtB,YAAY,CAAC;AACf;;;;;;;AAcA,SAAgB,gBAAgB,UAA8B,UAAmC;CAC/F,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,IAAI,KAAK;EACnC,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT;;;;;;;AA0BA,SAAgB,kBACd,UACA,UACqB;CACrB,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAA8B,CAAC;CAErC,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,QAAQ,SAAS,MAAM,KAAK;EAClC,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,SAAS,OAClB,IAAI,CAAC,KAAK,IAAI,MAAM,IAAI,GAAG;GACzB,KAAK,IAAI,MAAM,IAAI;GACnB,OAAO,KAAK,KAAK;EACnB;CAEJ;CAGF,OAAO;AACT;;;;;;;AAyBA,SAAgB,2BACd,UACA,UACU;CACV,MAAM,uBAAO,IAAI,IAAY;CAC7B,MAAM,SAAmB,CAAC;CAE1B,KAAK,MAAM,WAAW,UACpB,KAAK,MAAM,QAAQ,CAAC,QAAQ,QAAQ,QAAQ,IAAI,GAAG;EACjD,IAAI,CAAC,MAAM;EACX,MAAM,WAAW,SAAS,cAAc,KAAK;EAC7C,IAAI,CAAC,UAAU;EACf,KAAK,MAAM,OAAO,UAChB,IAAI,CAAC,KAAK,IAAI,GAAG,GAAG;GAClB,KAAK,IAAI,GAAG;GACZ,OAAO,KAAK,GAAG;EACjB;CAEJ;CAGF,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { B as addSpanEventSync, I as getWaitUntil, d as logSwrRefetchFailed, h as swallow } from "./logger-
|
|
1
|
+
import { B as addSpanEventSync, I as getWaitUntil, d as logSwrRefetchFailed, h as swallow } from "./logger-DDirEsn7.js";
|
|
2
2
|
import { t as fnv1aHash } from "./fast-hash-C-tVYrLb.js";
|
|
3
|
+
import { n as createSingleflight } from "./singleflight-2lUWfcAk.js";
|
|
3
4
|
import { t as estimateByteSize } from "./sizeof-lXffQ1Vr.js";
|
|
4
5
|
import { t as warnLossyJsonValue } from "./json-lossy-check-ClNvBM_3.js";
|
|
5
6
|
import { t as getCdnPurgeHandler } from "./purge-store-Byr8XOjU.js";
|
|
@@ -49,52 +50,6 @@ function stableStringify(value) {
|
|
|
49
50
|
return "{" + pairs.join(",") + "}";
|
|
50
51
|
}
|
|
51
52
|
//#endregion
|
|
52
|
-
//#region src/cache/singleflight.ts
|
|
53
|
-
/**
|
|
54
|
-
* Error thrown when a singleflight call exceeds `timeoutMs`.
|
|
55
|
-
* Exported so callers can distinguish timeout from other errors.
|
|
56
|
-
*/
|
|
57
|
-
var SingleflightTimeoutError = class extends Error {
|
|
58
|
-
constructor(key, timeoutMs) {
|
|
59
|
-
super(`Singleflight timeout: key "${key}" exceeded ${timeoutMs}ms`);
|
|
60
|
-
this.name = "SingleflightTimeoutError";
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
function createSingleflight(opts) {
|
|
64
|
-
const inflight = /* @__PURE__ */ new Map();
|
|
65
|
-
const timeoutMs = opts?.timeoutMs;
|
|
66
|
-
return { do(key, fn) {
|
|
67
|
-
const existing = inflight.get(key);
|
|
68
|
-
if (existing) return existing;
|
|
69
|
-
const ac = new AbortController();
|
|
70
|
-
let promise;
|
|
71
|
-
if (timeoutMs != null && timeoutMs > 0) promise = new Promise((resolve, reject) => {
|
|
72
|
-
const timer = setTimeout(() => {
|
|
73
|
-
ac.abort();
|
|
74
|
-
reject(new SingleflightTimeoutError(key, timeoutMs));
|
|
75
|
-
}, timeoutMs);
|
|
76
|
-
try {
|
|
77
|
-
fn(ac.signal).then((value) => {
|
|
78
|
-
clearTimeout(timer);
|
|
79
|
-
resolve(value);
|
|
80
|
-
}, (err) => {
|
|
81
|
-
clearTimeout(timer);
|
|
82
|
-
reject(err);
|
|
83
|
-
});
|
|
84
|
-
} catch (err) {
|
|
85
|
-
clearTimeout(timer);
|
|
86
|
-
reject(err);
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
else promise = fn(ac.signal);
|
|
90
|
-
const tracked = promise.finally(() => {
|
|
91
|
-
inflight.delete(key);
|
|
92
|
-
});
|
|
93
|
-
inflight.set(key, tracked);
|
|
94
|
-
return tracked;
|
|
95
|
-
} };
|
|
96
|
-
}
|
|
97
|
-
//#endregion
|
|
98
53
|
//#region src/cache/invalidation-epoch.ts
|
|
99
54
|
/**
|
|
100
55
|
* Per-process invalidation epoch tracking for timber.cache (TIM-1028).
|
|
@@ -1189,6 +1144,6 @@ var cache = {
|
|
|
1189
1144
|
}
|
|
1190
1145
|
};
|
|
1191
1146
|
//#endregion
|
|
1192
|
-
export { setDefaultSingleflightTimeout as _, getManifestEntry as a, wasInvalidatedSince as b, lookupPrebuiltPayload as c, checkVersionSkew as d, MemoryCacheHandler as f, setCacheHandler as g, getCacheHandler as h, storeOverlayEntry as i, setPrebuiltPayloadSource as l, RedisCacheHandler as m, lookupOverlay as n, hasPrebuiltPayloadSource as o, TagAwareCacheHandler as p, overlayKey as r, isParamIndependent as s, cache as t, applyReloadHeaders as u, currentInvalidationEpoch as v,
|
|
1147
|
+
export { setDefaultSingleflightTimeout as _, getManifestEntry as a, wasInvalidatedSince as b, lookupPrebuiltPayload as c, checkVersionSkew as d, MemoryCacheHandler as f, setCacheHandler as g, getCacheHandler as h, storeOverlayEntry as i, setPrebuiltPayloadSource as l, RedisCacheHandler as m, lookupOverlay as n, hasPrebuiltPayloadSource as o, TagAwareCacheHandler as p, overlayKey as r, isParamIndependent as s, cache as t, applyReloadHeaders as u, currentInvalidationEpoch as v, lastInvalidationEpochFor as y };
|
|
1193
1148
|
|
|
1194
|
-
//# sourceMappingURL=cache-api-
|
|
1149
|
+
//# sourceMappingURL=cache-api-DqzgTEqk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache-api-DqzgTEqk.js","names":[],"sources":["../../src/cache/stable-stringify.ts","../../src/cache/invalidation-epoch.ts","../../src/cache/timber-cache.ts","../../src/cache/handler-store.ts","../../src/cache/redis-handler.ts","../../src/cache/tag-aware-handler.ts","../../src/cache/index.ts","../../src/server/version-skew.ts","../../src/server/prebuilt/manifest-tag-index.ts","../../src/server/prebuilt/payload-source.ts","../../src/server/prebuilt/overlay.ts","../../src/cache/cache-api.ts"],"sourcesContent":["/**\n * Deterministic JSON serialization with sorted object keys.\n * Used for cache key generation — ensures { a: 1, b: 2 } and { b: 2, a: 1 }\n * produce the same string.\n *\n * Matches JSON.stringify semantics for toJSON: Date serializes to its ISO\n * string, URL to its href, and class instances with a custom toJSON use it.\n * Map and Set serialize their entries explicitly (insertion-order\n * independent). Values that would serialize lossily — functions, symbols,\n * and non-plain objects with no enumerable own state (RegExp, class\n * instances holding data behind getters or internal slots) — throw instead:\n * every such value would collapse to the same cache key, silently returning\n * one argument's cached data for another (TIM-1020).\n */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return String(value);\n\n const type = typeof value;\n if (type === 'function' || type === 'symbol') {\n throw new TypeError(\n `stableStringify: cannot serialize a ${type} into a stable cache key — ` +\n 'all such values would collide. Provide an explicit `key` option to cache().'\n );\n }\n if (type !== 'object') return JSON.stringify(value);\n\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).join(',') + ']';\n }\n\n // Honor toJSON like JSON.stringify does (Date → ISO string, URL → href,\n // custom class serialization). JSON.stringify does not re-invoke toJSON\n // on the value it returns, so a toJSON that returns `this` falls through\n // to plain own-property serialization instead of recursing forever.\n const withToJSON = value as { toJSON?: () => unknown };\n if (typeof withToJSON.toJSON === 'function') {\n const json = withToJSON.toJSON();\n if (json !== value) return stableStringify(json);\n }\n\n // Map/Set have no enumerable own properties — serialize entries explicitly.\n // Entries are sorted after serialization so insertion order doesn't change\n // the key. The Map(/Set( prefixes can't collide with object ('{'), array\n // ('['), or string ('\"') output.\n if (value instanceof Map) {\n const entries = [...value.entries()].map(\n ([k, v]) => stableStringify(k) + '=>' + stableStringify(v)\n );\n return 'Map(' + entries.sort().join(',') + ')';\n }\n if (value instanceof Set) {\n const members = [...value].map((member) => stableStringify(member));\n return 'Set(' + members.sort().join(',') + ')';\n }\n\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const pairs: string[] = [];\n for (const key of keys) {\n if (obj[key] === undefined) continue;\n // A callable own toJSON only reaches this loop via the returns-`this`\n // fall-through above. It's the serialization protocol, not data —\n // JSON.stringify omits it too.\n if (key === 'toJSON' && typeof obj[key] === 'function') continue;\n pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n\n // A non-plain object that serializes to '{}' carries its state behind\n // getters or internal slots (RegExp, sessions, ORM entities). Serializing\n // it would give every instance the same cache key.\n if (pairs.length === 0) {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n const name = (value as object).constructor?.name || 'Object';\n throw new TypeError(\n `stableStringify: ${name} instance has no serializable own state — ` +\n 'all instances would share one cache key. Provide an explicit `key` ' +\n 'option to cache(), or add a toJSON() method.'\n );\n }\n }\n\n return '{' + pairs.join(',') + '}';\n}\n","/**\n * Per-process invalidation epoch tracking for timber.cache (TIM-1028).\n *\n * handler.set for a cache miss runs after `fn()` resolves. An explicit\n * `cache.invalidate({ tag })` / `revalidateTag` that lands while fn is in\n * flight would otherwise be silently undone — the just-invalidated value\n * re-stored as fresh for the full TTL, resurrecting pre-mutation data.\n *\n * Every invalidation bumps a monotonic epoch and records it against the\n * invalidated key/tag. Before storing a result, the cache wrapper checks\n * whether its key or any of its tags were invalidated after fn started and\n * skips the write if so. Skipping is always safe: the only cost is one\n * extra cache miss on the next call.\n *\n * Scope: per-process, like the singleflight map. An invalidation issued by\n * another instance against a shared handler (Redis/KV) during fn flight is\n * not observable here — closing that window fully would require store-level\n * versioning, which no CacheHandler backend offers.\n */\n\nlet epoch = 0;\n\n/**\n * Last-invalidated epoch per `key:<k>` / `tag:<t>` entry. Insertion order is\n * epoch order (entries are re-inserted on update), so the oldest entry is\n * always first — pruning evicts lowest epochs.\n */\nconst lastInvalidated = new Map<string, number>();\n\n/**\n * Bound on tracked entries so high-cardinality tag invalidation (e.g.\n * per-user tags) cannot grow this map without limit.\n */\nconst MAX_TRACKED_ENTRIES = 10_000;\n\n/**\n * Highest epoch evicted from the map. Any execution that started at or\n * before this epoch conservatively counts as invalidated — history was\n * truncated, so we can no longer prove it wasn't.\n */\nlet evictedEpochFloor = 0;\n\n/** The current epoch. Capture before running fn(), pass to wasInvalidatedSince. */\nexport function currentInvalidationEpoch(): number {\n return epoch;\n}\n\n/**\n * Record an invalidation. Call BEFORE handler.invalidate() so an execution\n * whose set-check races the invalidation errs toward skipping the write.\n */\nexport function recordInvalidation(opts: { key?: string; tag?: string }): void {\n epoch++;\n if (opts.key) track(`key:${opts.key}`);\n if (opts.tag) track(`tag:${opts.tag}`);\n}\n\nfunction track(entry: string): void {\n lastInvalidated.delete(entry);\n lastInvalidated.set(entry, epoch);\n while (lastInvalidated.size > MAX_TRACKED_ENTRIES) {\n const oldest = lastInvalidated.entries().next().value;\n if (oldest === undefined) break;\n evictedEpochFloor = Math.max(evictedEpochFloor, oldest[1]);\n lastInvalidated.delete(oldest[0]);\n }\n}\n\n/**\n * Whether the key or any tag was invalidated after `startEpoch` (the epoch\n * captured when fn started executing).\n */\nexport function wasInvalidatedSince(startEpoch: number, key: string, tags: string[]): boolean {\n return lastInvalidationEpochFor(key, tags) > startEpoch;\n}\n\n/**\n * The highest epoch at which the key or any of the tags was invalidated\n * (0 if never). Used to scope the singleflight key: callers arriving after\n * an invalidation must not coalesce onto a flight that started before it —\n * they would receive the pre-invalidation result the invalidation was\n * issued to discard.\n */\nexport function lastInvalidationEpochFor(key: string, tags: string[]): number {\n let last = evictedEpochFloor;\n const keyEpoch = lastInvalidated.get(`key:${key}`);\n if (keyEpoch !== undefined && keyEpoch > last) last = keyEpoch;\n for (const tag of tags) {\n const tagEpoch = lastInvalidated.get(`tag:${tag}`);\n if (tagEpoch !== undefined && tagEpoch > last) last = tagEpoch;\n }\n return last;\n}\n","import type { CacheHandler, CacheOptions } from './index.ts';\nimport { stableStringify } from './stable-stringify.ts';\nimport { createSingleflight } from './singleflight.ts';\nimport {\n currentInvalidationEpoch,\n lastInvalidationEpochFor,\n wasInvalidatedSince,\n} from './invalidation-epoch.ts';\nimport { addSpanEventSync } from '../server/tracing.ts';\nimport { logSwrRefetchFailed, swallow } from '../server/logger.ts';\nimport { getWaitUntil } from '../server/waituntil-bridge.ts';\nimport { fnv1aHash } from './fast-hash.ts';\n\nlet defaultSingleflight = createSingleflight();\n\n/**\n * Per-key monotonic generation counter for CAS writes (TIM-1158).\n *\n * Unbounded, like the singleflight map — the key space is the same set of\n * cache keys the handler already tracks. Pruning was removed because it\n * desyncs from MemoryCacheHandler.generations: a pruned key restarts at 1\n * while the handler still holds the old higher generation, causing fresh\n * writes to be rejected as stale.\n */\nconst writeGenerations = new Map<string, number>();\nfunction nextGeneration(key: string): number {\n const gen = (writeGenerations.get(key) ?? 0) + 1;\n writeGenerations.set(key, gen);\n return gen;\n}\n\n/**\n * Set the timeout for the module-level default singleflight.\n * Called at framework boot with renderTimeoutMs from timber.config.ts so that\n * cache calls without a per-call timeoutMs still get deadlock protection.\n * See design/06-caching.md §\"Singleflight Timeout — Deadlock Risk\".\n */\nexport function setDefaultSingleflightTimeout(timeoutMs: number): void {\n defaultSingleflight = createSingleflight({ timeoutMs });\n}\n\n/**\n * Generate a cache key from function identity and serialized args.\n *\n * Uses FNV-1a (fast non-crypto hash) instead of SHA-256. Cache keys don't\n * need collision resistance — they need speed. The fnId prefix provides\n * namespace isolation; the hash covers the args.\n *\n * See TIM-370 for perf motivation.\n */\nfunction defaultKeyGenerator(fnId: string, args: unknown[]): string {\n const raw = fnId + ':' + stableStringify(args);\n return fnId + ':' + fnv1aHash(raw);\n}\n\n/**\n * Resolve tags from the options — supports static array or function form.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction resolveTags<Fn extends (...args: any[]) => any>(\n opts: CacheOptions<Fn>,\n args: Parameters<Fn>\n): string[] {\n if (!opts.tags) return [];\n if (Array.isArray(opts.tags)) return opts.tags;\n return opts.tags(...args);\n}\n\n/** Per-process count of byte-identical fn sources seen by deriveFallbackFnId. */\nconst fallbackIdOccurrences = new Map<string, number>();\nlet hasWarnedFallbackId = false;\n\n/**\n * Derive a fallback fnId for callsites the timber-cache-transform Vite plugin\n * could not statically detect (aliased bindings, user re-export wrappers).\n *\n * The base is fnv1a(fn.toString()) — deterministic across instances and cold\n * starts of the same build, so two *different* functions can never swap fnIds\n * by module-evaluation order (the TIM-997 poisoning scenario that the old\n * process-local counter allowed; see TIM-1054). A per-process occurrence\n * suffix disambiguates byte-identical duplicate sources. That residue is the\n * one remaining hazard: closures produced by the same factory share source\n * text but capture different values, and their occurrence order may differ\n * across instances — such callsites need an explicit `key` option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction deriveFallbackFnId(fn: (...args: any[]) => any): string {\n const sourceHash = fnv1aHash(fn.toString());\n const occurrence = fallbackIdOccurrences.get(sourceHash) ?? 0;\n fallbackIdOccurrences.set(sourceHash, occurrence + 1);\n\n if (!hasWarnedFallbackId && typeof process !== 'undefined' && process.env?.NODE_ENV !== 'test') {\n hasWarnedFallbackId = true;\n console.warn(\n '[timber] cache() callsite has no build-time stable ID and no explicit `key` option — ' +\n 'the call is not statically visible to the timber Vite plugin (e.g. an aliased ' +\n 'binding like `const c = cache` or a re-export wrapper module). Falling back to a ' +\n 'function-source hash for the cache key. With a shared CacheHandler (Redis/KV) this ' +\n 'is safe for distinct functions, but byte-identical closures from a factory can swap ' +\n 'cache entries across instances. Provide an explicit `key` option to make the cache ' +\n 'key contract stable and auditable.'\n );\n }\n\n return `timber-cache:fn:${sourceHash}:${occurrence}`;\n}\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - FNV-1a default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution AND single\n * handler.set — the write happens inside the coalesced callback (TIM-1028)\n * - Writes are skipped when the key/tags were invalidated while fn was in\n * flight, so explicit invalidation is never silently undone (TIM-1028)\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - The handler is resolved per invocation via `getHandler`, never captured\n * at wrapper-creation time — module-scope cache() wrappers created before\n * the framework's boot wiring calls setCacheHandler() still use the\n * configured handler once it arrives (TIM-1029)\n * - No ALS dependency for correctness — cache() works outside a request\n * context. The waitUntil ALS bridge is read optionally so the SWR\n * background refetch survives handler return on Workers/Lambda.\n *\n * Cache hits/misses are recorded as OTEL span events on the enclosing\n * span (not child spans). The DevSpanProcessor reads these for dev log output.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function createCache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n getHandler: () => CacheHandler,\n stableId?: string\n): Fn {\n // With an explicit `key` option the fnId never reaches key generation, so\n // no fallback derivation (or warning) is needed in that case.\n const fnId = stableId ?? (opts.key ? undefined : deriveFallbackFnId(fn));\n\n // Per-call timeoutMs gets a dedicated singleflight instance. Otherwise\n // resolve defaultSingleflight per invocation (not captured at creation\n // time) so wrappers created before boot pick up the timeout once\n // setDefaultSingleflightTimeout is called (TIM-1032, same rationale as\n // getCacheHandler for TIM-1029).\n const perCallSf =\n opts.timeoutMs !== undefined ? createSingleflight({ timeoutMs: opts.timeoutMs }) : undefined;\n\n // Cast to Fn to preserve the original function's generic call signature.\n // Without this, generic type parameters (e.g. <T> in apiFetch<T>) are\n // erased and callers lose type safety on the return type.\n return (async (...args: Parameters<Fn>): Promise<Awaited<ReturnType<Fn>>> => {\n const sf = perCallSf ?? defaultSingleflight;\n const key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId as string, args);\n\n const cacheStart = performance.now();\n const cached = await getHandler().get(key);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span).\n // Fire-and-forget — no microtask overhead on the cache hot path.\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // From here fn() will execute (SWR refetch or miss). Scope the\n // singleflight key by the last invalidation epoch affecting this\n // key/tags: a caller arriving after an invalidation must not coalesce\n // onto a flight that started before it — it would receive the\n // pre-invalidation result the invalidation was issued to discard.\n // NUL separator: cannot collide with user-provided key strings.\n const tags = resolveTags(opts, args);\n const flightKey = `${key}\\u0000${lastInvalidationEpochFor(key, tags)}`;\n\n /**\n * Run fn and store the result — exactly once per coalesced execution,\n * inside the singleflight callback. The write is skipped when:\n * - the key/tags were invalidated after fn started (TIM-1028), or\n * - the singleflight timed out (signal aborted) — the timed-out\n * flight's write could overwrite a newer value from a subsequent\n * flight (TIM-1092), or\n * - the handler rejects the write because a newer generation has\n * already been stored (TIM-1158 CAS guard).\n */\n const executeAndStore = async (signal: AbortSignal): Promise<Awaited<ReturnType<Fn>>> => {\n const startEpoch = currentInvalidationEpoch();\n const generation = nextGeneration(key);\n const result = await fn(...args);\n if (!signal.aborted && !wasInvalidatedSince(startEpoch, key, tags)) {\n try {\n await getHandler().set(key, result, { ttl: opts.ttl, tags, generation });\n } catch (err) {\n // Cache-write failure must not fail the request (TIM-1046).\n // JSON-serializing handlers (Redis, KV) throw on BigInt; network\n // errors can surface from any shared handler. The result is valid\n // — serve it uncached rather than rejecting a successful fn().\n swallow(err, `cache set failed for key \"${key}\"`);\n }\n }\n return result;\n };\n\n if (cached && cached.stale && opts.staleWhileRevalidate) {\n // Record stale cache hit as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n stale: true,\n });\n // Serve stale immediately, trigger background refetch\n const refetch = sf\n .do(`swr:${flightKey}`, async (signal) => {\n try {\n await executeAndStore(signal);\n } catch (err) {\n // Failed refetch — stale entry continues to be served.\n logSwrRefetchFailed({ cacheKey: key, error: err });\n }\n })\n .catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n // Platforms that cancel work when the handler returns (Cloudflare\n // Workers, Lambda) would otherwise kill the refetch mid-flight —\n // stale data re-served forever. Register the (never-rejecting)\n // refetch with the request's waitUntil; undefined outside a request\n // context or on platforms without lifecycle extension (Node servers\n // keep floating promises alive, so behavior there is unchanged).\n getWaitUntil()?.(refetch);\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight.\n // The handler.set lives inside the coalesced callback, so N concurrent\n // misses produce exactly one write (TIM-1028).\n const result = await sf.do(flightKey, executeAndStore);\n\n // Record cache miss as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result;\n }) as unknown as Fn;\n}\n","/**\n * Module-level cache handler singleton.\n *\n * Lazily initialized to MemoryCacheHandler on first access. The framework\n * replaces this at boot from timber.config.ts via setCacheHandler().\n *\n * This module avoids importing from ./index to prevent circular dependencies.\n */\n\n// Inline the interface to avoid circular import with index.ts\ninterface CacheHandlerLike {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\nlet handler: CacheHandlerLike | null = null;\n\nlet explicitlyConfigured = false;\n\n/** Replace the active cache handler. Called by the framework at boot. */\nexport function setCacheHandler(h: CacheHandlerLike): void {\n handler = h;\n explicitlyConfigured = true;\n}\n\n/** Whether the handler was explicitly configured (vs the default in-memory fallback). */\nexport function isCacheHandlerConfigured(): boolean {\n return explicitlyConfigured;\n}\n\n/**\n * Get the active cache handler. Creates a default MemoryCacheHandler on\n * first access if none has been set via setCacheHandler().\n */\nexport function getCacheHandler(): CacheHandlerLike {\n if (!handler) {\n // Inline a minimal LRU cache to avoid circular dep with index.ts.\n // In production, the framework always calls setCacheHandler() at boot.\n handler = createDefaultHandler();\n }\n return handler;\n}\n\nfunction createDefaultHandler(): CacheHandlerLike {\n const store = new Map<string, { value: unknown; expiresAt: number; tags: string[] }>();\n const maxEntries = 1000;\n\n return {\n async get(key) {\n const entry = store.get(key);\n if (!entry) return null;\n store.delete(key);\n store.set(key, entry);\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n },\n async set(key, value, opts) {\n if (store.has(key)) store.delete(key);\n while (store.size >= maxEntries) {\n const oldest = store.keys().next().value;\n if (oldest !== undefined) store.delete(oldest);\n else break;\n }\n store.set(key, { value, expiresAt: Date.now() + opts.ttl * 1000, tags: opts.tags });\n },\n async invalidate(opts) {\n if (opts.key) store.delete(opts.key);\n if (opts.tag) {\n for (const [key, entry] of store) {\n if (entry.tags.includes(opts.tag)) store.delete(key);\n }\n }\n },\n };\n}\n","import type { CacheHandler } from './index.ts';\nimport { warnLossyJsonValue } from './json-lossy-check.ts';\n\n/**\n * Minimal Redis client contract for `RedisCacheHandler`.\n *\n * This is deliberately NOT the native shape of any client library. ioredis,\n * node-redis v4, and @upstash/redis all disagree on TTL argument shapes\n * (positional `'EX'` vs `{ EX }` vs `{ ex }`), method casing (`sadd` vs\n * `sAdd`), and array handling in `del` — a contract that pattern-matches one\n * client lets another silently drop the expiry (TIM-1030: node-redis ignored\n * the positional `'EX'` and wrote keys with no TTL). Instead, TTL semantics\n * are explicit in the signature and you adapt your client with a thin\n * wrapper, so a mismatch is a type error rather than silent unbounded\n * keyspace growth.\n *\n * @example ioredis\n * ```ts\n * import Redis from 'ioredis';\n * const redis = new Redis(process.env.REDIS_URL);\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, 'EX', ttl),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, ...m),\n * srem: (k, ...m) => redis.srem(k, ...m),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * execMulti: async (ops) => {\n * const p = redis.multi();\n * for (const op of ops) {\n * switch (op.op) {\n * case 'set': p.set(op.key, op.value, 'EX', op.ttlSeconds); break;\n * case 'sadd': p.sadd(op.key, ...op.members); break;\n * case 'expireNX': p.expire(op.key, op.seconds, 'NX'); break;\n * case 'expireGT': p.expire(op.key, op.seconds, 'GT'); break;\n * case 'del': p.del(op.key); break;\n * }\n * }\n * await p.exec();\n * },\n * };\n * ```\n *\n * @example node-redis v4\n * ```ts\n * import { createClient } from 'redis';\n * const redis = createClient({ url: process.env.REDIS_URL });\n * await redis.connect();\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { EX: ttl }),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sAdd(k, m),\n * srem: (k, ...m) => redis.sRem(k, m),\n * smembers: (k) => redis.sMembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n *\n * @example @upstash/redis\n * ```ts\n * import { Redis } from '@upstash/redis';\n * // automaticDeserialization must be off: the handler stores JSON strings\n * // and parses them itself — auto-parsing would hand back objects.\n * const redis = new Redis({ url, token, automaticDeserialization: false });\n * const client: RedisClient = {\n * get: (k) => redis.get(k),\n * set: (k, v, ttl) => redis.set(k, v, { ex: ttl }),\n * expireNX: (k, s) => redis.expire(k, s, 'NX'),\n * expireGT: (k, s) => redis.expire(k, s, 'GT'),\n * del: (k) => redis.del(k),\n * sadd: (k, ...m) => redis.sadd(k, m[0], ...m.slice(1)),\n * srem: (k, ...m) => redis.srem(k, m[0], ...m.slice(1)),\n * smembers: (k) => redis.smembers(k),\n * ttl: (k) => redis.ttl(k),\n * };\n * ```\n */\nexport type RedisWriteOp =\n | { op: 'set'; key: string; value: string; ttlSeconds: number }\n | { op: 'sadd'; key: string; members: string[] }\n | { op: 'expireNX'; key: string; seconds: number }\n | { op: 'expireGT'; key: string; seconds: number }\n | { op: 'del'; key: string };\n\nexport interface RedisClient {\n /** `GET key` — the stored string, or null when absent. */\n get(key: string): Promise<string | null>;\n /**\n * `SET key value EX ttlSeconds` — store with an expiry. The TTL is a\n * required positional argument so no adapter can forget it.\n */\n set(key: string, value: string, ttlSeconds: number): Promise<unknown>;\n /**\n * `EXPIRE key seconds NX` — set the TTL only if the key has no existing\n * expiry (Redis 7.0+). Used to set the initial TTL on new tag sets.\n */\n expireNX(key: string, seconds: number): Promise<unknown>;\n /**\n * `EXPIRE key seconds GT` — update the TTL only if the new value is greater\n * than the current one (Redis 7.0+). Used to extend tag set TTLs without\n * allowing a short-TTL writer to shrink them.\n */\n expireGT(key: string, seconds: number): Promise<unknown>;\n /** `DEL key` — delete a single key. Multi-key deletes loop per key. */\n del(key: string): Promise<unknown>;\n /** `SADD key member [member ...]` — add members to a set. */\n sadd(key: string, ...members: string[]): Promise<unknown>;\n /** `SREM key member [member ...]` — remove members from a set. */\n srem(key: string, ...members: string[]): Promise<unknown>;\n /** `SMEMBERS key` — all members of a set. */\n smembers(key: string): Promise<string[]>;\n /**\n * `TTL key` — remaining time-to-live in seconds. Returns -2 if the key does\n * not exist, -1 if the key exists but has no expiry.\n */\n ttl(key: string): Promise<number>;\n /**\n * Execute a batch of write operations atomically via `MULTI/EXEC`.\n * When provided, `set()` uses this to make tag-index writes and the data\n * write atomic — no `invalidate({tag})` can interleave. Optional: when\n * absent, operations run sequentially (correct but not race-free).\n */\n execMulti?(ops: RedisWriteOp[]): Promise<void>;\n}\n\nconst KEY_PREFIX = 'timber:cache:';\nconst TAG_PREFIX = 'timber:tag:';\n\n/**\n * Redis-backed CacheHandler for distributed caching.\n *\n * All instances sharing the same Redis see each other's cache entries and\n * invalidations. Tag-based invalidation uses Redis Sets to track which keys\n * belong to which tags.\n *\n * Bring your own Redis client wrapped to the {@link RedisClient} contract —\n * see the adapter examples on the interface for ioredis, node-redis v4, and\n * @upstash/redis.\n */\nexport class RedisCacheHandler implements CacheHandler {\n private client: RedisClient;\n private prefix: string;\n\n constructor(client: RedisClient, opts?: { prefix?: string }) {\n this.client = client;\n this.prefix = opts?.prefix ?? '';\n }\n\n private cacheKey(key: string): string {\n return `${this.prefix}${KEY_PREFIX}${key}`;\n }\n\n private tagKey(tag: string): string {\n return `${this.prefix}${TAG_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.client.get(this.cacheKey(key));\n if (raw === null) return null;\n\n const entry = JSON.parse(raw) as { value: unknown; expiresAt: number };\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void> {\n warnLossyJsonValue(value, key);\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n\n // Serialize upfront so BigInt/non-serializable errors throw before any\n // writes — prevents tag indexes pointing at stale data from a prior set().\n const payload = JSON.stringify({ value, expiresAt, tags: opts.tags });\n\n // Redis TTL with generous margin beyond the logical TTL to allow SWR reads\n // on stale entries. The logical staleness is determined by expiresAt.\n // We use 2x TTL + 60s as the Redis expiry so stale entries remain\n // available for SWR background refetches.\n const redisTtlSeconds = Math.max(opts.ttl * 2 + 60, 120);\n\n const writeOps: RedisWriteOp[] = [];\n for (const tag of opts.tags) {\n writeOps.push({ op: 'sadd', key: this.tagKey(tag), members: [key] });\n writeOps.push({ op: 'expireNX', key: this.tagKey(tag), seconds: redisTtlSeconds });\n writeOps.push({ op: 'expireGT', key: this.tagKey(tag), seconds: redisTtlSeconds });\n }\n writeOps.push({ op: 'set', key: ck, value: payload, ttlSeconds: redisTtlSeconds });\n\n if (this.client.execMulti) {\n await this.client.execMulti(writeOps);\n } else {\n for (const op of writeOps) {\n await this.execOp(op);\n }\n }\n }\n\n private async execOp(op: RedisWriteOp): Promise<void> {\n switch (op.op) {\n case 'set':\n await this.client.set(op.key, op.value, op.ttlSeconds);\n break;\n case 'sadd':\n await this.client.sadd(op.key, ...op.members);\n break;\n case 'expireNX':\n await this.client.expireNX(op.key, op.seconds);\n break;\n case 'expireGT':\n await this.client.expireGT(op.key, op.seconds);\n break;\n case 'del':\n await this.client.del(op.key);\n break;\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n const raw = await this.client.get(this.cacheKey(opts.key));\n if (raw !== null) {\n const entry = JSON.parse(raw) as { tags?: string[] };\n if (entry.tags) {\n await Promise.all(entry.tags.map((tag) => this.client.srem(this.tagKey(tag), opts.key!)));\n }\n }\n await this.client.del(this.cacheKey(opts.key));\n }\n\n if (opts.tag) {\n const tk = this.tagKey(opts.tag);\n const keys = await this.client.smembers(tk);\n\n // Re-check each member before deleting — the tag set can contain stale\n // memberships from entries whose tags changed since they were added.\n // Mirrors TagAwareCacheHandler's eager strategy (tag-aware-handler.ts:183-198).\n await Promise.all(\n keys.map(async (k) => {\n const raw = await this.client.get(this.cacheKey(k));\n if (raw === null) {\n await this.client.srem(tk, k);\n return;\n }\n const entry = JSON.parse(raw) as { tags?: string[] };\n if (entry.tags?.includes(opts.tag!)) {\n await this.client.del(this.cacheKey(k));\n }\n await this.client.srem(tk, k);\n })\n );\n\n // Clean up the now-empty tag set so it doesn't consume memory\n const remaining = await this.client.smembers(tk);\n if (remaining.length === 0) {\n await this.client.del(tk);\n }\n }\n }\n}\n","/**\n * TagAwareCacheHandler — wraps any CacheStore and adds tag-based invalidation.\n *\n * Three strategies, selected by store capabilities (best available wins):\n *\n * 1. **Native** (store has setWithTags + invalidateTag): Delegates entirely.\n * The store owns tag indexing. Used for Vercel Runtime Cache, DO-backed\n * stores, or any platform with first-class tag support.\n *\n * 2. **Eager** (store has sadd/smembers/srem/sdel): Maintains an inverted\n * index via atomic set operations. Invalidation enumerates the set and\n * deletes entries. Used for Redis.\n *\n * 3. **Lazy** (bare get/set/del only): Version-stamps entries with tag\n * counters. Invalidation bumps a counter (O(1)). Reads validate stored\n * versions against current. Race-free, correct under eventual consistency.\n * Used for Cloudflare KV.\n *\n * Implements the CacheHandler interface consumed by timber-cache.ts.\n */\n\nimport type { CacheHandler } from './index.ts';\nimport type { CacheStore } from './store.ts';\n\nconst DATA_PREFIX = 'd:';\nconst TAG_SET_PREFIX = 'ts:';\nconst TAG_VERSION_PREFIX = 'tv:';\n\ntype Strategy = 'native' | 'eager' | 'lazy';\n\n/** Stored entry format for eager strategy. */\ninterface EagerEntry {\n value: unknown;\n expiresAt: number;\n tags: string[];\n}\n\n/** Stored entry format for lazy (version-stamp) strategy. */\ninterface LazyEntry {\n value: unknown;\n expiresAt: number;\n tags: string[];\n tagVersions: Record<string, number>;\n}\n\nfunction detectStrategy(store: CacheStore): Strategy {\n if (store.setWithTags && store.invalidateTag) return 'native';\n if (store.sadd && store.smembers && store.srem && store.sdel) return 'eager';\n return 'lazy';\n}\n\nexport class TagAwareCacheHandler implements CacheHandler {\n private store: CacheStore;\n private prefix: string;\n private strategy: Strategy;\n\n constructor(store: CacheStore, opts?: { prefix?: string }) {\n this.store = store;\n this.prefix = opts?.prefix ?? 'timber:';\n this.strategy = detectStrategy(store);\n }\n\n get consistency(): 'strong' | 'eventual' | 'local' {\n return this.store.consistency;\n }\n\n private dataKey(key: string): string {\n return `${this.prefix}${DATA_PREFIX}${key}`;\n }\n\n /** Namespace tags for native stores so prefix isolates shared stores. */\n private prefixTags(tags: string[]): string[] {\n return tags.map((t) => `${this.prefix}${t}`);\n }\n\n private tagSetKey(tag: string): string {\n return `${this.prefix}${TAG_SET_PREFIX}${tag}`;\n }\n\n private tagVersionKey(tag: string): string {\n return `${this.prefix}${TAG_VERSION_PREFIX}${tag}`;\n }\n\n async get(key: string): Promise<{ value: unknown; stale: boolean } | null> {\n const raw = await this.store.get(this.dataKey(key));\n if (raw === null) return null;\n\n if (this.strategy === 'native' || this.strategy === 'eager') {\n const entry = JSON.parse(raw) as EagerEntry;\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n // Lazy: validate tag versions before returning\n const entry = JSON.parse(raw) as LazyEntry;\n if (entry.tags.length > 0) {\n const currentVersions = await this.getTagVersions(entry.tags);\n for (const tag of entry.tags) {\n const stored = entry.tagVersions[tag] ?? 0;\n const current = currentVersions[tag] ?? 0;\n if (current > stored) return null;\n }\n }\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void> {\n const physicalTtl = Math.max(opts.ttl * 2 + 60, 120);\n\n if (this.strategy === 'native') {\n const entry: EagerEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n };\n const payload = JSON.stringify(entry);\n if (opts.tags.length > 0) {\n await this.store.setWithTags!(\n this.dataKey(key),\n payload,\n physicalTtl,\n this.prefixTags(opts.tags)\n );\n } else {\n await this.store.set(this.dataKey(key), payload, physicalTtl);\n }\n return;\n }\n\n if (this.strategy === 'eager') {\n const entry: EagerEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n };\n await this.store.set(this.dataKey(key), JSON.stringify(entry), physicalTtl);\n if (opts.tags.length > 0) {\n await Promise.all(\n opts.tags.map((tag) => this.store.sadd!(this.tagSetKey(tag), [key], physicalTtl))\n );\n }\n return;\n }\n\n // Lazy: snapshot current tag versions into the entry\n const tagVersions = opts.tags.length > 0 ? await this.getTagVersions(opts.tags) : {};\n const entry: LazyEntry = {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n tagVersions,\n };\n await this.store.set(this.dataKey(key), JSON.stringify(entry), physicalTtl);\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\n if (this.strategy === 'eager') {\n const raw = await this.store.get(this.dataKey(opts.key));\n if (raw !== null) {\n const entry = JSON.parse(raw) as EagerEntry;\n if (entry.tags.length > 0) {\n await Promise.all(\n entry.tags.map((tag) => this.store.srem!(this.tagSetKey(tag), [opts.key!]))\n );\n }\n }\n }\n await this.store.del(this.dataKey(opts.key));\n }\n\n if (opts.tag) {\n const tag = opts.tag;\n if (this.strategy === 'native') {\n await this.store.invalidateTag!(`${this.prefix}${tag}`);\n } else if (this.strategy === 'eager') {\n const members = await this.store.smembers!(this.tagSetKey(tag));\n // Verify each member still carries the tag before deleting — the set\n // can contain stale memberships from overwritten entries or LRU eviction.\n // Remove only the snapshot members (via srem, not sdel) so concurrent\n // writes that add new members between smembers() and cleanup are preserved.\n await Promise.all(\n members.map(async (k) => {\n const raw = await this.store.get(this.dataKey(k));\n if (raw === null) {\n await this.store.srem!(this.tagSetKey(tag), [k]);\n return;\n }\n const entry = JSON.parse(raw) as EagerEntry;\n if (entry.tags.includes(tag)) {\n await this.store.del(this.dataKey(k));\n await this.store.srem!(this.tagSetKey(tag), [k]);\n } else {\n await this.store.srem!(this.tagSetKey(tag), [k]);\n }\n })\n );\n } else {\n await this.bumpTagVersion(opts.tag);\n }\n }\n }\n\n // --- Lazy strategy helpers ---\n\n private async getTagVersions(tags: string[]): Promise<Record<string, number>> {\n const versions: Record<string, number> = {};\n await Promise.all(\n tags.map(async (tag) => {\n const raw = await this.store.get(this.tagVersionKey(tag));\n versions[tag] = raw !== null ? parseInt(raw, 10) : 0;\n })\n );\n return versions;\n }\n\n private async bumpTagVersion(tag: string): Promise<void> {\n const key = this.tagVersionKey(tag);\n const raw = await this.store.get(key);\n const stored = raw !== null ? parseInt(raw, 10) : 0;\n // max(stored, now) + 1: strictly advancing even within the same\n // millisecond (two bumps in 1ms produce N, N+1 not N, N). On\n // eventually-consistent stores the read can be stale, but Date.now()\n // provides a floor — regression only if BOTH the read is stale AND the\n // clock is behind, bounded by the store's propagation window (~60s).\n const version = Math.max(stored, Date.now()) + 1;\n // Version keys must outlive all data entries stamped with them. Data\n // entries use physical TTL of max(ttl*2+60, 120); 365 days exceeds any\n // practical cache lifetime.\n await this.store.set(key, String(version), 365 * 86400);\n }\n}\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.ts';\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface CacheOptions<Fn extends (...args: any[]) => any> {\n ttl: number;\n key?: (...args: Parameters<Fn>) => string;\n staleWhileRevalidate?: boolean;\n tags?: string[] | ((...args: Parameters<Fn>) => string[]);\n /** Timeout (ms) for singleflight-coalesced calls. Prevents hung fn() from\n * permanently blocking all future callers for the same cache key. See TIM-518. */\n timeoutMs?: number;\n}\n\nexport interface MemoryCacheHandlerOptions {\n /** Maximum number of entries. Oldest accessed entries are evicted first. Default: 1000. */\n maxEntries?: number;\n /**\n * @deprecated Use `maxEntries` instead. Will be removed in a future release.\n * Alias for `maxEntries` — maximum number of entries (not bytes).\n */\n maxSize?: number;\n /** Maximum total byte budget for all cached values. Oldest entries are evicted when exceeded. Default: no limit. */\n maxBytes?: number;\n /** Maximum byte size for a single cache entry. Entries exceeding this are silently dropped. Default: no limit. */\n maxEntryBytes?: number;\n}\n\nexport class MemoryCacheHandler implements CacheHandler {\n private store = new Map<\n string,\n { value: unknown; expiresAt: number; tags: string[]; byteSize: number }\n >();\n private generations = new Map<string, number>();\n private maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\n private readonly _trackBytes: boolean;\n\n constructor(opts?: MemoryCacheHandlerOptions) {\n // maxEntries takes precedence over deprecated maxSize\n this.maxEntries = opts?.maxEntries ?? opts?.maxSize ?? 1000;\n this.maxBytes = opts?.maxBytes;\n this.maxEntryBytes = opts?.maxEntryBytes;\n this._trackBytes = this.maxBytes !== undefined || this.maxEntryBytes !== undefined;\n }\n\n async get(key: string) {\n const entry = this.store.get(key);\n if (!entry) return null;\n\n // Move to end of Map (most recently used) for LRU ordering\n this.store.delete(key);\n this.store.set(key, entry);\n\n const stale = Date.now() > entry.expiresAt;\n return { value: entry.value, stale };\n }\n\n async set(\n key: string,\n value: unknown,\n opts: { ttl: number; tags: string[]; generation?: number }\n ) {\n // CAS guard: skip write if a newer generation has already been written\n if (opts.generation !== undefined) {\n const current = this.generations.get(key) ?? 0;\n if (opts.generation < current) return;\n }\n\n const byteSize = this._trackBytes ? estimateByteSize(value) : 0;\n\n // Reject entries exceeding per-entry byte limit\n if (this.maxEntryBytes !== undefined && byteSize > this.maxEntryBytes) {\n return;\n }\n\n // If key already exists, delete first to refresh insertion order and reclaim bytes\n if (this.store.has(key)) {\n const existing = this.store.get(key)!;\n this.currentBytes -= existing.byteSize;\n this.store.delete(key);\n }\n\n // Evict oldest entries (front of Map) if at entry count capacity\n while (this.store.size >= this.maxEntries) {\n this.evictOldest();\n }\n\n // Evict oldest entries if byte budget would be exceeded\n if (this.maxBytes !== undefined) {\n while (this.currentBytes + byteSize > this.maxBytes && this.store.size > 0) {\n this.evictOldest();\n }\n // If the single entry exceeds the total byte budget, don't store it\n if (this.currentBytes + byteSize > this.maxBytes) {\n return;\n }\n }\n\n // Record generation only after all admission checks pass\n if (opts.generation !== undefined) {\n this.generations.set(key, opts.generation);\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + opts.ttl * 1000,\n tags: opts.tags,\n byteSize,\n });\n this.currentBytes += byteSize;\n }\n\n async invalidate(opts: { key?: string; tag?: string }) {\n if (opts.key) {\n const entry = this.store.get(opts.key);\n if (entry) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(opts.key);\n }\n this.generations.delete(opts.key);\n }\n if (opts.tag) {\n for (const [key, entry] of this.store) {\n if (entry.tags.includes(opts.tag)) {\n this.currentBytes -= entry.byteSize;\n this.store.delete(key);\n this.generations.delete(key);\n }\n }\n }\n }\n\n /** Number of entries currently in the cache. */\n get size(): number {\n return this.store.size;\n }\n\n /** Estimated total byte size of all cached values. Only tracked when maxBytes or maxEntryBytes is configured; returns 0 otherwise. */\n get bytes(): number {\n return this.currentBytes;\n }\n\n /** Evict the oldest entry (front of Map). */\n private evictOldest(): void {\n const oldest = this.store.keys().next().value;\n if (oldest !== undefined) {\n const entry = this.store.get(oldest)!;\n this.currentBytes -= entry.byteSize;\n this.store.delete(oldest);\n this.generations.delete(oldest);\n }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler.ts';\nexport type { RedisClient, RedisWriteOp } from './redis-handler.ts';\nexport { cache } from './cache-api.ts';\nexport { setCacheHandler, getCacheHandler } from './handler-store.ts';\nexport { setDefaultSingleflightTimeout } from './timber-cache.ts';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof.ts';\n\n// --- Cache Store layering (design/46) ---\nexport { TagAwareCacheHandler } from './tag-aware-handler.ts';\nexport type { CacheStore } from './store.ts';\n// stableStringify, createSingleflight, and SingleflightTimeoutError are\n// internal utilities used by the cache implementation. They are not\n// re-exported here — import directly from the source files if needed\n// within the package. See TIM-720.\n","/**\n * Version Skew Detection — graceful recovery when stale clients hit new deployments.\n *\n * When a new version of the app is deployed, clients with open tabs still have\n * the old JavaScript bundle. Without version skew handling, these stale clients\n * will experience:\n *\n * 1. Server action calls that crash (action IDs are content-hashed)\n * 2. Chunk load failures (old filenames gone from CDN)\n * 3. RSC payload mismatches (component references differ between builds)\n *\n * This module implements deployment ID comparison:\n * - A per-build deployment ID is generated at build time (see build-manifest.ts)\n * - The client sends it via `X-Timber-Deployment-Id` header on every RSC/action request\n * - The server compares it against the current build's ID\n * - On mismatch: signal the client to reload (not crash)\n *\n * The deployment ID is always-on in production. Dev mode skips the check\n * (HMR handles code updates without full reloads).\n *\n * See design/25-production-deployments.md, TIM-446\n */\n\n// ─── Constants ───────────────────────────────────────────────────\n\n/** Header sent by the client with every RSC/action request. */\nexport const DEPLOYMENT_ID_HEADER = 'X-Timber-Deployment-Id';\n\n/** Response header that signals the client to do a full page reload. */\nexport const RELOAD_HEADER = 'X-Timber-Reload';\n\n// ─── Deployment ID ───────────────────────────────────────────────\n\n/**\n * The current build's deployment ID. Set at startup from the manifest init\n * module (globalThis.__TIMBER_DEPLOYMENT_ID__). Null in dev mode.\n */\nlet currentDeploymentId: string | null = null;\n\n/**\n * Set the current deployment ID. Called once at server startup from the\n * manifest init module. In dev mode this is never called (deployment ID\n * checks are skipped).\n */\nexport function setDeploymentId(id: string): void {\n currentDeploymentId = id;\n}\n\n/**\n * Get the current deployment ID. Returns null in dev mode.\n */\nexport function getDeploymentId(): string | null {\n return currentDeploymentId;\n}\n\n// ─── Skew Detection ──────────────────────────────────────────────\n\n/** Result of a version skew check. */\nexport interface SkewCheckResult {\n /** Whether the client's deployment ID matches the server's. */\n ok: boolean;\n /** The client's deployment ID (null if header not sent — e.g., initial page load). */\n clientId: string | null;\n}\n\n/**\n * Check if a request's deployment ID matches the current build.\n *\n * Returns `{ ok: true }` when:\n * - Dev mode (no deployment ID set — HMR handles updates)\n * - No deployment ID header (initial page load, non-RSC request)\n * - Deployment IDs match\n *\n * Returns `{ ok: false }` when:\n * - Client sends a deployment ID that differs from the current build\n */\nexport function checkVersionSkew(req: Request): SkewCheckResult {\n // Dev mode — no deployment ID checks (HMR handles updates)\n if (!currentDeploymentId) {\n return { ok: true, clientId: null };\n }\n\n const clientId = req.headers.get(DEPLOYMENT_ID_HEADER);\n\n // No header — initial page load or non-RSC request. Always OK.\n if (!clientId) {\n return { ok: true, clientId: null };\n }\n\n // Compare deployment IDs\n if (clientId === currentDeploymentId) {\n return { ok: true, clientId };\n }\n\n return { ok: false, clientId };\n}\n\n/**\n * Apply version skew reload headers to a response.\n * Sets X-Timber-Reload: 1 to signal the client to do a full page reload.\n */\nexport function applyReloadHeaders(headers: Headers): void {\n headers.set(RELOAD_HEADER, '1');\n}\n","/**\n * Manifest tag index — maps tags to seed cache keys for tombstone writes.\n *\n * When `revalidateTag(tag)` fires, the framework must write tombstones for\n * every build-seed entry carrying that tag. The manifest records tags per\n * entry; this module inverts the index at startup so the lookup is O(1) per\n * tag instead of a full manifest scan per invalidation.\n *\n * The index is built lazily on first access and cached for the process\n * lifetime — the manifest is immutable within a deploy.\n *\n * See design/45-cache-lifetimes.md §ISR mechanics.\n */\n\nimport type { PrebuiltManifest } from './payload-source.ts';\n\nexport interface SeedKeyInfo {\n componentId: string;\n cacheKey: string;\n}\n\n/**\n * Build the inverted tag → seed key index from the manifest.\n *\n * Returns a Map where each tag maps to the set of (componentId, cacheKey)\n * pairs whose manifest entries carry that tag. Only entries with non-empty\n * `tags` arrays participate.\n */\nexport function buildTagIndex(manifest: PrebuiltManifest): Map<string, SeedKeyInfo[]> {\n const index = new Map<string, SeedKeyInfo[]>();\n for (const [componentId, component] of Object.entries(manifest)) {\n if (!component || typeof component !== 'object' || !('entries' in component)) continue;\n for (const [cacheKey, entry] of Object.entries(component.entries)) {\n if (!entry.tags || entry.tags.length === 0) continue;\n for (const tag of entry.tags) {\n let list = index.get(tag);\n if (!list) {\n list = [];\n index.set(tag, list);\n }\n list.push({ componentId, cacheKey });\n }\n }\n }\n return index;\n}\n","/**\n * Prebuilt payload source — the adapter seam through which the runtime\n * reads build-time flight artifacts (`.timber/dist/prebuilt/`).\n *\n * The runtime never touches the filesystem directly: adapters register a\n * source at startup (Node: fs reads; Cloudflare: the assets binding —\n * design/44-render-at-build-time.md §Adapter Integration). Artifacts are\n * produced by the post-build capture pass (TIM-1119, prebuilt-builder.ts);\n * adapter registration of the source is TIM-1122. Until a source is\n * registered (adapter not wired yet, dev mode, no artifacts built), every\n * lookup misses and cache.component wrappers render live — the designed\n * dynamic-fallback behavior.\n *\n * Phase 3 (design/45 runtime tier) inserts the CacheHandler overlay lookup\n * in front of `lookupPrebuiltPayload` — overlay first, then artifact. The\n * single-lookup-function shape here is that seam.\n */\n\nimport { initTagIndex, resetTagIndex } from './overlay.ts';\nimport type { CoercedParams } from '../../shared/param-value.ts';\n\nexport interface PrebuiltManifestEntry {\n /** Segment params this entry was captured under. */\n params: CoercedParams;\n /** Payload path relative to the prebuilt/ directory. */\n file: string;\n /** Payload size in bytes (build report / diagnostics). */\n bytes?: number;\n /** Runtime invalidation tags (design/45 ISR tier). */\n tags?: string[];\n /** Epoch ms when this entry was captured (seed freshness for ISR). */\n buildTimestamp?: number;\n}\n\nexport interface PrebuiltManifest {\n [componentId: string]: {\n entries: Record<string, PrebuiltManifestEntry>;\n /** When true, the component does not read segment params — the cache key uses `{}`. */\n paramIndependent?: boolean;\n };\n}\n\nexport interface PrebuiltPayloadSource {\n /** Load prebuilt/manifest.json. Null when no artifacts exist. */\n loadManifest(): Promise<PrebuiltManifest | null>;\n /** Read a `.flight` payload by manifest file path. Null when missing. */\n readPayload(file: string): Promise<Uint8Array | null>;\n}\n\nlet source: PrebuiltPayloadSource | null = null;\nlet manifestPromise: Promise<PrebuiltManifest | null> | null = null;\n\n/**\n * Ceiling on the memoized manifest load. Without it, a stalled\n * `loadManifest()` would leave `manifestPromise` pending forever and every\n * subsequent cache.component render would await the same hung promise —\n * the coalesced-promise deadlock class from design/13-security.md (A5).\n * On expiry the load memoizes as null (permanent dynamic fallback, same\n * policy as a failed load) and callers proceed immediately.\n */\nconst MANIFEST_LOAD_TIMEOUT_MS = 5_000;\n\n/**\n * Per-read ceiling on payload reads. The read is awaited inside a server\n * component render — a stalled adapter promise would otherwise hang the\n * RSC stream until the render timeout kills the whole page, when the\n * correct degradation is a miss → live render (codex review round 4 on\n * PR #835).\n */\nconst PAYLOAD_READ_TIMEOUT_MS = 5_000;\n\n/** Race a source promise against a timeout that resolves to `fallback`. */\nasync function withTimeout<T>(\n work: Promise<T>,\n timeoutMs: number,\n fallback: T,\n onTimeout: () => void\n): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n work,\n new Promise<T>((resolve) => {\n timer = setTimeout(() => {\n onTimeout();\n resolve(fallback);\n }, timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nasync function loadManifestWithTimeout(\n src: PrebuiltPayloadSource\n): Promise<PrebuiltManifest | null> {\n let manifest: PrebuiltManifest | null;\n try {\n manifest = await withTimeout(src.loadManifest(), MANIFEST_LOAD_TIMEOUT_MS, null, () => {\n console.error(\n `[timber] prebuilt manifest load exceeded ${MANIFEST_LOAD_TIMEOUT_MS}ms — all cache.component lookups will render dynamically`\n );\n });\n } catch (error) {\n console.error(\n '[timber] failed to load prebuilt manifest — all cache.component lookups will miss:',\n error\n );\n return null;\n }\n if (manifest) {\n initTagIndex(manifest);\n }\n return manifest;\n}\n\n/**\n * Register the payload source. Called once at server startup by the\n * adapter/entry wiring (TIM-1122); tests inject fakes. Passing null\n * unregisters (and drops the memoized manifest).\n */\nexport function setPrebuiltPayloadSource(next: PrebuiltPayloadSource | null): void {\n source = next;\n manifestPromise = null;\n if (!next) resetTagIndex();\n}\n\n/**\n * Whether a source is registered — the gate for both marker emission and\n * splice-transform installation. False means zero prebuilt overhead.\n */\nexport function hasPrebuiltPayloadSource(): boolean {\n return source !== null;\n}\n\n/**\n * Ensure the manifest is loaded (and the tag index initialized). No-op\n * when no source is registered. Used by the tombstone path to avoid\n * skipping tombstones on cold processes where the first request is an\n * action rather than a page render.\n */\nexport async function ensureManifestLoaded(): Promise<void> {\n if (source === null) return;\n manifestPromise ??= loadManifestWithTimeout(source);\n await manifestPromise;\n}\n\n/**\n * Look up a manifest entry (metadata only, no payload read).\n * Used by the overlay to check seed existence and freshness.\n */\nexport async function isParamIndependent(componentId: string): Promise<boolean> {\n if (source === null) return false;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n return manifest?.[componentId]?.paramIndependent === true;\n}\n\nexport async function getManifestEntry(\n componentId: string,\n cacheKey: string\n): Promise<PrebuiltManifestEntry | null> {\n if (source === null) return null;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n return manifest?.[componentId]?.entries?.[cacheKey] ?? null;\n}\n\n/**\n * Look up a cached payload: manifest entry → payload bytes.\n * Null on any miss or read failure — callers fall back to live render.\n *\n * The manifest is loaded once and memoized (design/44 §manifest.json:\n * loaded at startup, held in memory; payloads read on demand). A failed\n * manifest load is memoized as null rather than retried per-request — a\n * broken artifact should degrade to dynamic rendering, not add a failing\n * read to every request.\n */\nexport async function lookupPrebuiltPayload(\n componentId: string,\n cacheKey: string\n): Promise<Uint8Array | null> {\n if (source === null) return null;\n manifestPromise ??= loadManifestWithTimeout(source);\n const manifest = await manifestPromise;\n const entry = manifest?.[componentId]?.entries?.[cacheKey];\n if (!entry) return null;\n try {\n return await withTimeout(source.readPayload(entry.file), PAYLOAD_READ_TIMEOUT_MS, null, () => {\n console.error(\n `[timber] prebuilt payload read for \"${entry.file}\" exceeded ${PAYLOAD_READ_TIMEOUT_MS}ms — rendering dynamically`\n );\n });\n } catch (error) {\n console.error(\n `[timber] failed to read prebuilt payload \"${entry.file}\" for ${componentId} — rendering dynamically:`,\n error\n );\n return null;\n }\n}\n","/**\n * Component cache overlay — runtime CacheHandler layer for ISR.\n *\n * Sits in front of the immutable build artifact (`.flight` files) and\n * stores replacement payloads and tombstones via the configured\n * CacheHandler. Overlay entries are per-deploy namespaced:\n * `timber:c:{deploymentId}:{componentId}:{hash}`\n *\n * The CacheHandler contract is untouched — tombstones and the tag index\n * live above the interface as value conventions. Redis, KV, and custom\n * handlers work unmodified.\n *\n * See design/45-cache-lifetimes.md §ISR mechanics.\n */\n\nimport { getCacheHandler, isCacheHandlerConfigured } from '../../cache/handler-store.ts';\nimport { MemoryCacheHandler } from '../../cache/index.ts';\nimport { getDeploymentId } from '../version-skew.ts';\nimport { buildTagIndex, type SeedKeyInfo } from './manifest-tag-index.ts';\nimport type { PrebuiltManifest } from './payload-source.ts';\nimport { ensureManifestLoaded } from './payload-source.ts';\n\n/** Default ceiling TTL for tag-only entries (24 hours), in seconds. */\nconst CEILING_TTL_SECONDS = 24 * 60 * 60;\n\n/** Deploy-long physical TTL for seed-backed overlay records (90 days). */\nconst DEPLOY_LONG_TTL_SECONDS = 90 * 24 * 60 * 60;\n\n// ─── Overlay record shapes (value conventions above CacheHandler) ────────\n\n/**\n * A cached component flight payload stored in the overlay.\n * The `_t` discriminant distinguishes this from a tombstone.\n */\nexport interface ComponentOverlayRecord {\n _t: 'co';\n /** Base64-encoded flight payload bytes. */\n p: string;\n /** Logical freshness deadline (Date.now() + ttl * 1000). */\n fu: number;\n /** Whether a build-artifact seed exists for this key. */\n s: boolean;\n}\n\n/**\n * A tombstone marking a build seed as invalidated.\n * Written by revalidateTag for seeds carrying the invalidated tag.\n */\nexport interface ComponentTombstoneRecord {\n _t: 'ct';\n}\n\ntype OverlayValue = ComponentOverlayRecord | ComponentTombstoneRecord;\n\nexport function isOverlayRecord(v: unknown): v is ComponentOverlayRecord {\n return v !== null && typeof v === 'object' && (v as Record<string, unknown>)._t === 'co';\n}\n\nexport function isTombstone(v: unknown): v is ComponentTombstoneRecord {\n return v !== null && typeof v === 'object' && (v as Record<string, unknown>)._t === 'ct';\n}\n\n// ─── Overlay key generation ──────────────────────────────────────────────\n\nexport function overlayKey(componentId: string, cacheKey: string): string {\n const deploymentId = getDeploymentId() ?? 'dev';\n return `timber:c:${deploymentId}:${componentId}:${cacheKey}`;\n}\n\n// ─── Overlay read ────────────────────────────────────────────────────────\n\nexport interface OverlayLookupResult {\n kind: 'fresh' | 'stale' | 'tombstone';\n /** The overlay value (null for tombstones). */\n record: ComponentOverlayRecord | null;\n /** Raw flight payload bytes (decoded from base64). Null for tombstones. */\n payload: Uint8Array | null;\n}\n\n/**\n * Look up an overlay entry in the cache handler.\n * Returns null on a clean miss (no overlay entry at all).\n */\nexport async function lookupOverlay(\n componentId: string,\n cacheKey: string\n): Promise<OverlayLookupResult | null> {\n const handler = getCacheHandler();\n const key = overlayKey(componentId, cacheKey);\n const result = await handler.get(key);\n if (!result) return null;\n\n const value = result.value as OverlayValue;\n if (isTombstone(value)) {\n return { kind: 'tombstone', record: null, payload: null };\n }\n if (isOverlayRecord(value)) {\n const logicallyStale = Date.now() > value.fu;\n return {\n kind: logicallyStale ? 'stale' : 'fresh',\n record: value,\n payload: base64ToBytes(value.p),\n };\n }\n // Unknown value shape — treat as miss (forward compatibility).\n return null;\n}\n\n// ─── Overlay write ───────────────────────────────────────────────────────\n\n/**\n * Resolve the effective TTL for a component's runtime lifetime.\n * Tag-only entries (no explicit ttl) get the ceiling TTL (design/45\n * §Tag-only entries carry a ceiling TTL).\n */\nexport function effectiveTtl(ttl: number | undefined): number {\n return ttl ?? CEILING_TTL_SECONDS;\n}\n\n/**\n * Store a component flight payload in the overlay.\n */\nexport async function storeOverlayEntry(\n componentId: string,\n cacheKey: string,\n payloadBytes: Uint8Array,\n opts: {\n ttl?: number;\n tags: string[];\n hasSeed: boolean;\n }\n): Promise<void> {\n const handler = getCacheHandler();\n const key = overlayKey(componentId, cacheKey);\n const logicalTtl = effectiveTtl(opts.ttl);\n const physicalTtl = opts.hasSeed ? DEPLOY_LONG_TTL_SECONDS : logicalTtl;\n\n const record: ComponentOverlayRecord = {\n _t: 'co',\n p: bytesToBase64(payloadBytes),\n fu: Date.now() + logicalTtl * 1000,\n s: opts.hasSeed,\n };\n\n await handler.set(key, record, { ttl: physicalTtl, tags: opts.tags });\n}\n\n// ─── Tombstone writes ────────────────────────────────────────────────────\n\nlet tagIndex: Map<string, SeedKeyInfo[]> | null = null;\n\n/**\n * Initialize the tag index from the prebuilt manifest. Called once when the\n * manifest is loaded. Without a manifest (no prebuilt components), this is\n * never called and revalidateTag skips the tombstone path entirely.\n */\nexport function initTagIndex(manifest: PrebuiltManifest): void {\n tagIndex = buildTagIndex(manifest);\n emitIsrDiagnosticIfNeeded(manifest);\n}\n\n/**\n * Get the tag index, if initialized.\n * @internal — exported for testing.\n */\nexport function getTagIndex(): Map<string, SeedKeyInfo[]> | null {\n return tagIndex;\n}\n\n/**\n * Reset the tag index (for tests).\n * @internal\n */\nexport function resetTagIndex(): void {\n tagIndex = null;\n}\n\n/**\n * Write tombstones for all seed entries carrying the given tag.\n * Called from cache.invalidate (cache-api.ts) AFTER the handler's own\n * invalidation clears overlay entries.\n *\n * The tombstone prevents the immutable seed from being served after\n * invalidation — without it, a handler.invalidate that clears the overlay\n * would expose the (now-stale) build artifact on the next request.\n *\n * Ensures the manifest is loaded first so cold-process actions that\n * invalidate before any page render still write tombstones.\n */\nexport async function writeTombstonesForTag(tag: string): Promise<void> {\n if (!tagIndex) {\n await ensureManifestLoaded();\n }\n if (!tagIndex) return;\n const seeds = tagIndex.get(tag);\n if (!seeds || seeds.length === 0) return;\n\n const handler = getCacheHandler();\n const tombstone: ComponentTombstoneRecord = { _t: 'ct' };\n\n await Promise.all(\n seeds.map((seed) => {\n const key = overlayKey(seed.componentId, seed.cacheKey);\n return handler.set(key, tombstone, {\n ttl: DEPLOY_LONG_TTL_SECONDS,\n tags: [tag],\n });\n })\n );\n}\n\n// ─── ISR build diagnostic ────────────────────────────────────────────────\n\nlet isrDiagnosticEmitted = false;\n\nfunction emitIsrDiagnosticIfNeeded(manifest: PrebuiltManifest): void {\n if (isrDiagnosticEmitted) return;\n\n const handler = getCacheHandler();\n const isMemoryBased = handler instanceof MemoryCacheHandler || !isCacheHandlerConfigured();\n if (!isMemoryBased) return;\n\n for (const [, component] of Object.entries(manifest)) {\n if (!component || typeof component !== 'object' || !('entries' in component)) continue;\n for (const [, entry] of Object.entries(component.entries)) {\n if (entry.tags && entry.tags.length > 0) {\n isrDiagnosticEmitted = true;\n console.warn(\n '[timber] tag revalidation of prerendered components requires a shared cache ' +\n 'handler in multi-instance deployments. The current MemoryCacheHandler is ' +\n 'per-process — revalidateTag on one instance will not purge the build seed ' +\n 'on others. Configure a shared handler (Redis, KV) for production ISR.'\n );\n return;\n }\n }\n }\n}\n\n/**\n * Reset the diagnostic flag (for tests).\n * @internal\n */\nexport function resetIsrDiagnostic(): void {\n isrDiagnosticEmitted = false;\n}\n\n// ─── Encoding helpers ────────────────────────────────────────────────────\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\nfunction base64ToBytes(b64: string): Uint8Array {\n return new Uint8Array(Buffer.from(b64, 'base64'));\n}\n","import type { CacheOptions } from './index.ts';\nimport type { PrebuiltComponentOptions } from '../server/prebuilt-runtime.ts';\nimport { createCache } from './timber-cache.ts';\nimport { getCacheHandler } from './handler-store.ts';\nimport { recordInvalidation } from './invalidation-epoch.ts';\nimport { writeTombstonesForTag } from '../server/prebuilt/overlay.ts';\nimport { getCdnPurgeHandler } from '../cdn/purge-store.ts';\n\nconst componentFallbackWarned = new WeakSet<object>();\n\n/**\n * Cache namespace — `cache.data`, `cache.component`, `cache.invalidate`.\n *\n * ```ts\n * import { cache } from '@timber-js/app/cache';\n *\n * const getUser = cache.data(\n * async (id: string) => db.users.findUnique({ where: { id } }),\n * { ttl: 60, tags: (id) => [`user:${id}`] }\n * );\n * ```\n */\nexport const cache = {\n /**\n * Wrap an async function with cross-request caching.\n *\n * The configured cache handler (defaults to MemoryCacheHandler, overridable\n * via timber.config.ts) is re-resolved on every call, so module-scope\n * wrappers created before `setCacheHandler()` still pick up the configured\n * handler (TIM-1029).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n data<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>,\n stableId?: string\n ): Fn {\n return createCache(fn, opts, getCacheHandler, stableId);\n },\n\n /**\n * Invalidate cache entries by tag or key.\n *\n * ```ts\n * cache.invalidate({ tag: 'products' });\n * cache.invalidate({ key: 'user:abc' });\n * ```\n */\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n // Record before the handler delete so a cached fn in flight skips its\n // post-resolve set instead of resurrecting the invalidated value (TIM-1028).\n recordInvalidation(opts);\n await getCacheHandler().invalidate(opts);\n // Write tombstones for build-seed entries carrying the tag (design/45\n // §ISR mechanics). Runs AFTER handler.invalidate so the tombstone\n // overwrites the cleared overlay slot. This covers ALL invalidation\n // paths — actions, webhooks, route handlers — not just executeAction.\n if (opts.tag) {\n await writeTombstonesForTag(opts.tag);\n }\n // Trigger CDN purge if a handler is configured (design/25 §Layer 2).\n // Purge is best-effort: a CDN API failure or timeout must not block\n // cache invalidation. 10s ceiling prevents a hung CDN API from stalling\n // the entire revalidateTag/action flow.\n if (opts.tag) {\n const purgeHandler = getCdnPurgeHandler();\n if (purgeHandler) {\n try {\n await Promise.race([\n purgeHandler.purgeTags([opts.tag]),\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new Error('CDN purge timed out (10s)')), 10_000)\n ),\n ]);\n } catch (err) {\n console.error('[timber] CDN purge failed for tag:', err);\n }\n }\n }\n },\n\n /**\n * Runtime fallback for `cache.component(...)` callsites the timber-prebuilt\n * transform does not rewrite — nested/computed/argument-position forms (see\n * plugins/prebuilt.ts). Only module-scope `const X = cache.component(...)`\n * declarations are transformed and eligible for prebuilding; everything else\n * lands here, warns once per component, and renders dynamically. Same\n * safety-net pattern as the data cache's runtime fnId fallback (TIM-1054):\n * an untraceable callsite degrades in performance, never in correctness.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n component<C extends (props: any) => unknown>(\n componentFn: C,\n _options?: PrebuiltComponentOptions\n ): C {\n if (!componentFallbackWarned.has(componentFn)) {\n componentFallbackWarned.add(componentFn);\n const name = componentFn.name || 'anonymous component';\n console.warn(\n `[timber] cache.component: \"${name}\" was not transformed at build time — ` +\n `rendering dynamically. Only module-scope declarations ` +\n `(const X = cache.component(...)) are prebuilt.`\n );\n }\n return componentFn;\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAcA,SAAgB,gBAAgB,OAAwB;CACtD,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO,OAAO,KAAK;CAE9D,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,cAAc,SAAS,UAClC,MAAM,IAAI,UACR,uCAAuC,KAAK,yGAE9C;CAEF,IAAI,SAAS,UAAU,OAAO,KAAK,UAAU,KAAK;CAElD,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO,MAAM,MAAM,KAAK,SAAS,gBAAgB,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI;CAO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