@timber-js/app 0.2.0-alpha.224 → 0.2.0-alpha.226
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-7dTXYJfu.js → actions-B1xSIv32.js} +2 -2
- package/dist/_chunks/{actions-7dTXYJfu.js.map → actions-B1xSIv32.js.map} +1 -1
- package/dist/_chunks/{cache-api-TDZ4hlDc.js → cache-api-DsSXA4Sp.js} +68 -47
- package/dist/_chunks/cache-api-DsSXA4Sp.js.map +1 -0
- package/dist/_chunks/{cli-check-Dv3f8d2j.js → cli-check-B33yhAPa.js} +2 -2
- package/dist/_chunks/{cli-check-Dv3f8d2j.js.map → cli-check-B33yhAPa.js.map} +1 -1
- package/dist/_chunks/cli-context-BPdyA7Fp.js +1 -0
- package/dist/_chunks/{cli-context-CbZp32SK.js → cli-context-CwTKMjVe.js} +10 -2
- package/dist/_chunks/cli-context-CwTKMjVe.js.map +1 -0
- package/dist/_chunks/{error-boundary-DRQXGWCp.js → error-boundary-D3YyVVuP.js} +2 -2
- package/dist/_chunks/{error-boundary-DRQXGWCp.js.map → error-boundary-D3YyVVuP.js.map} +1 -1
- package/dist/_chunks/navigation-root-M3B2ZrdO.js.map +1 -1
- package/dist/_chunks/{singleflight-BChPMjwH.js → singleflight-CzoOVB9Y.js} +2 -3
- package/dist/_chunks/singleflight-CzoOVB9Y.js.map +1 -0
- package/dist/_chunks/{status-page-marker-XIQXlTOb.js → status-page-marker-C8POawuF.js} +2 -2
- package/dist/_chunks/{status-page-marker-XIQXlTOb.js.map → status-page-marker-C8POawuF.js.map} +1 -1
- package/dist/adapters/cloudflare-kv-cache.d.ts +0 -1
- package/dist/adapters/cloudflare-kv-cache.d.ts.map +1 -1
- package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
- package/dist/cache/index.d.ts +5 -5
- package/dist/cache/index.d.ts.map +1 -1
- package/dist/cache/index.js +1 -1
- package/dist/cache/redis-handler.d.ts +0 -1
- package/dist/cache/redis-handler.d.ts.map +1 -1
- package/dist/cache/singleflight.d.ts +12 -2
- package/dist/cache/singleflight.d.ts.map +1 -1
- package/dist/cache/stable-stringify.d.ts +6 -0
- package/dist/cache/stable-stringify.d.ts.map +1 -1
- package/dist/cache/tag-aware-handler.d.ts +0 -1
- package/dist/cache/tag-aware-handler.d.ts.map +1 -1
- package/dist/cache/timber-cache.d.ts +1 -1
- package/dist/cache/timber-cache.d.ts.map +1 -1
- package/dist/cli-context.d.ts +8 -0
- package/dist/cli-context.d.ts.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +8 -2
- package/dist/cli.js.map +1 -1
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/internal.js +3 -3
- package/dist/client/navigation-root.d.ts.map +1 -1
- package/dist/client/nuqs-adapter.d.ts +4 -1
- package/dist/client/nuqs-adapter.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +112 -0
- package/dist/index.js.map +1 -1
- package/dist/plugins/client-in-server-package-deps.d.ts +63 -0
- package/dist/plugins/client-in-server-package-deps.d.ts.map +1 -0
- package/dist/plugins/optimize-package-imports.d.ts +11 -0
- package/dist/plugins/optimize-package-imports.d.ts.map +1 -1
- package/dist/server/flight-injector-core.d.ts.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal.js +162 -33
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline-helpers.d.ts +5 -2
- package/dist/server/pipeline-helpers.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/prebuilt-runtime.d.ts.map +1 -1
- package/dist/server/response-framing.d.ts +43 -0
- package/dist/server/response-framing.d.ts.map +1 -0
- package/dist/server/ssr-entry.d.ts.map +1 -1
- package/dist/server/ssr-wrappers.d.ts +9 -10
- package/dist/server/ssr-wrappers.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/adapters/cloudflare-kv-cache.ts +1 -5
- package/src/cache/index.ts +7 -27
- package/src/cache/redis-handler.ts +1 -5
- package/src/cache/singleflight.ts +17 -5
- package/src/cache/stable-stringify.ts +53 -0
- package/src/cache/tag-aware-handler.ts +1 -5
- package/src/cache/timber-cache.ts +55 -52
- package/src/cli-context.ts +9 -0
- package/src/cli.ts +16 -0
- package/src/client/navigation-root.tsx +7 -6
- package/src/client/nuqs-adapter.tsx +46 -28
- package/src/index.ts +2 -0
- package/src/plugins/client-in-server-package-deps.ts +139 -0
- package/src/plugins/optimize-package-imports.ts +1 -1
- package/src/server/flight-injector-core.ts +13 -9
- package/src/server/pipeline-helpers.ts +9 -5
- package/src/server/pipeline.ts +7 -0
- package/src/server/prebuilt-runtime.ts +125 -121
- package/src/server/response-framing.ts +59 -0
- package/src/server/ssr-entry.ts +0 -2
- package/src/server/ssr-wrappers.tsx +39 -49
- package/dist/_chunks/cache-api-TDZ4hlDc.js.map +0 -1
- package/dist/_chunks/cli-context-CbZp32SK.js.map +0 -1
- package/dist/_chunks/cli-context-n5hmkdla.js +0 -1
- package/dist/_chunks/singleflight-BChPMjwH.js.map +0 -1
- package/dist/server/nuqs-ssr-provider.d.ts +0 -32
- package/dist/server/nuqs-ssr-provider.d.ts.map +0 -1
- package/src/server/nuqs-ssr-provider.tsx +0 -64
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cache-api-TDZ4hlDc.js","names":["withTimeout"],"sources":["../../src/server/waituntil-bridge.ts","../../src/cache/stable-stringify.ts","../../src/cache/guarded-read.ts","../../src/cache/key-discipline.ts","../../src/cache/timber-cache.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 * Per-request waitUntil bridge — ALS bridge for platform adapters.\n *\n * The generated entry point (Nitro, Cloudflare) wraps the handler with\n * `runWithWaitUntil`, binding the platform's lifecycle extension function\n * (e.g., h3's `event.waitUntil()` or CF's `ctx.waitUntil()`) for the\n * request duration. The `waitUntil()` primitive reads from this ALS to\n * dispatch background work to the correct platform API.\n *\n * Design doc: design/11-platform.md §\"waitUntil()\"\n */\n\nimport { waitUntilAls } from './als-registry.ts';\n\n/**\n * Run a function with a per-request waitUntil handler installed.\n *\n * Called by generated entry points (Nitro node-server/bun, Cloudflare)\n * to bind the platform's lifecycle extension for the request duration.\n */\nexport function runWithWaitUntil<T>(\n waitUntilFn: (promise: Promise<unknown>) => void,\n fn: () => T\n): T {\n return waitUntilAls.run(waitUntilFn, fn);\n}\n\n/**\n * Get the current request's waitUntil function, if available.\n *\n * Returns undefined when no platform adapter has installed a waitUntil\n * handler for the current request (e.g., on platforms that don't support\n * lifecycle extension, or outside a request context).\n */\nexport function getWaitUntil(): ((promise: Promise<unknown>) => void) | undefined {\n return waitUntilAls.getStore();\n}\n","/**\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 * Cache reads never fail a request.\n *\n * A cache is an optimization: when the store is down, slow, or returns\n * garbage, the request must still succeed by doing the work the cache would\n * have skipped. Writes already follow this rule (timber-cache.ts swallows a\n * failed handler.set, TIM-1046); reads go through here so a throwing or hung\n * handler.get costs a live fetch or render, never a failed or stalled request.\n *\n * The timeout matters as much as the catch. Shared-store clients often queue\n * commands while disconnected (ioredis retries each one up to 20 times by\n * default), so an outage shows up as a read that never settles, not an error.\n *\n * Invalidation is deliberately NOT guarded: a failed invalidate that looked\n * like success would leave stale data in place silently.\n *\n * See design/06-caching.md §\"Store failures\".\n */\n\nimport { logCacheReadFailed } from '../server/logger.ts';\nimport { withTimeout } from '../server/render-timeout.ts';\n\n/** Ceiling for a single cache read. A healthy store answers in milliseconds. */\nexport const CACHE_READ_TIMEOUT_MS = 1_000;\n\n/**\n * Run a cache read. A throw, a rejection, or no answer within\n * CACHE_READ_TIMEOUT_MS logs a warning and resolves to `onFailure`, which the\n * caller picks: `null` where a failed read means \"miss\", a distinct value\n * where a miss would fall back to something the failed read might have\n * overridden (an invalidated build seed — server/prebuilt/overlay.ts).\n */\nexport async function guardedRead<T, F>(\n cacheKey: string,\n read: () => Promise<T>,\n onFailure: F\n): Promise<T | F> {\n try {\n return await withTimeout(read(), CACHE_READ_TIMEOUT_MS, `cache read for \"${cacheKey}\"`);\n } catch (error) {\n logCacheReadFailed({ cacheKey, error });\n return onFailure;\n }\n}\n","/**\n * Key-discipline diagnostic for both cache tiers (design/45 §Enforcement).\n *\n * A cached value is stored under a key computed from declared inputs only —\n * props and segment params for `cache.component`, the function's arguments\n * for `cache.data`. A request-context read while the value is being computed\n * is the data-leak danger zone (design/06 security note): the result varies\n * by user but the key does not. While the cached work runs, the ALS store is\n * wrapped in a transparent observing proxy; any request-context read\n * produces a structured, rate-limited production diagnostic.\n *\n * The diagnostic fires per offending callsite, rate-limited to once per\n * interval (default 60 s) — not once per process. This ensures the\n * signal stays visible in log aggregators across restarts and deploys.\n *\n * When `strictKeyDiscipline` is enabled (via timber.config.ts\n * `cache.strictKeyDiscipline: true`), the diagnostic is promoted to a\n * thrown error that prevents the tainted value from being cached.\n */\n\nimport { requestContextAls, type RequestContextStore } from '../server/als-registry.ts';\nimport { logKeyDisciplineViolation } from '../server/logger.ts';\n\n/** Store fields every tier's key leaves out, by the API that reads them. */\nconst REQUEST_FIELDS: ReadonlyMap<PropertyKey, string> = new Map([\n ['headers', 'headers()'],\n ['parsedCookies', 'cookies()'],\n ['searchParams', 'searchParams'],\n]);\n\n/**\n * The data tier also leaves out segment params: a cache.component key\n * includes them, a cache.data key holds only the function's arguments.\n */\nconst DATA_TIER_FIELDS: ReadonlyMap<PropertyKey, string> = new Map([\n ...REQUEST_FIELDS,\n ['segmentParams', 'segment params'],\n ['slotParams', 'segment params'],\n]);\n\n/** Which cache tier a callsite belongs to — selects the diagnostic wording. */\nexport type KeyDisciplineTier = 'cache.component' | 'cache.data';\n\n/** A cached callsite whose work is observed for request-context reads. */\nexport interface KeyDisciplineSite {\n tier: KeyDisciplineTier;\n /** Stable id of the callsite — the rate-limit key within its tier. */\n id: string;\n /** Human-readable name for the message; defaults to the id. */\n label?: string;\n /** The cache key this call computed — logged so the entry can be found. */\n cacheKey?: string;\n}\n\ninterface TierRules {\n /** Store fields whose read is a violation, mapped to the API name logged. */\n observed: ReadonlyMap<PropertyKey, string>;\n keyedBy: string;\n passAs: string;\n work: string;\n}\n\nconst TIERS: Record<KeyDisciplineTier, TierRules> = {\n 'cache.component': {\n observed: REQUEST_FIELDS,\n keyedBy: 'props and segment params',\n passAs: 'as props',\n work: 'a cache capture render',\n },\n 'cache.data': {\n observed: DATA_TIER_FIELDS,\n keyedBy: \"the function's arguments\",\n passAs: 'as an argument',\n work: 'a cached call',\n },\n};\n\n/** Rate-limit interval: one diagnostic per callsite per 60 seconds. */\nconst RATE_LIMIT_MS = 60_000;\n\n/**\n * Last emission timestamp per `${tier}:${id}`. Past this many entries,\n * ones whose window has elapsed are pruned — an untransformed callsite\n * re-created per request gets a fresh fallback id each time.\n */\nconst lastEmitted = new Map<string, number>();\nconst PRUNE_AT = 1_000;\n\n/**\n * Thrown in strict mode. A distinct class so a caller holding an earlier\n * result computed by the same fn (a stale SWR entry) can drop it.\n */\nexport class KeyDisciplineViolation extends Error {\n override name = 'KeyDisciplineViolation';\n}\n\nlet strict = false;\n\n/**\n * Configure strict key-discipline mode. When true, a violation throws\n * instead of logging — the tainted value is never cached.\n * Called at boot from the RSC entry with the resolved config value.\n */\nexport function setKeyDisciplineStrict(enabled: boolean): void {\n strict = enabled;\n}\n\n/**\n * Run a cached callsite's work under the observing proxy, then report any\n * request-context read it made. The proxy is transparent — it forwards all\n * reads and writes; it only observes.\n *\n * Outside a request context `run` executes as-is: there is nothing to read,\n * and cache.data must keep working there. In default mode a callsite that\n * reported within the rate-limit window is not observed at all. In strict\n * mode a violation rejects after `run` resolves, so the caller never stores\n * the value.\n */\nexport async function observeKeyDiscipline<T>(\n site: KeyDisciplineSite,\n run: () => Promise<T>\n): Promise<T> {\n const store = requestContextAls.getStore();\n if (!store || !shouldCheck(site)) return run();\n\n const { proxy, accessedApis } = createObservingProxy(store, TIERS[site.tier].observed);\n const result = await requestContextAls.run(proxy, run);\n if (accessedApis.size > 0) reportViolation(site, accessedApis);\n return result;\n}\n\nfunction rateLimitKey(site: KeyDisciplineSite): string {\n return `${site.tier}:${site.id}`;\n}\n\n/**\n * Whether to observe this callsite on this call. Always in strict mode;\n * otherwise only once the rate-limit window since its last report elapsed.\n */\nfunction shouldCheck(site: KeyDisciplineSite): boolean {\n if (strict) return true;\n const last = lastEmitted.get(rateLimitKey(site));\n if (last === undefined) return true;\n return Date.now() - last >= RATE_LIMIT_MS;\n}\n\nfunction createObservingProxy(\n store: RequestContextStore,\n observed: ReadonlyMap<PropertyKey, string>\n): {\n proxy: RequestContextStore;\n accessedApis: Set<string>;\n} {\n const accessedApis = new Set<string>();\n const proxy = new Proxy(store, {\n get(target, prop, receiver) {\n // A Map, not an object literal: `constructor` or `toString` read\n // off the store must not count as a request-context read.\n const api = observed.get(prop);\n if (api) accessedApis.add(api);\n return Reflect.get(target, prop, receiver);\n },\n });\n return { proxy, accessedApis };\n}\n\n/**\n * Throw in strict mode; otherwise emit a structured error-level diagnostic\n * through the logger (same path as render errors), rate-limited per callsite.\n */\nfunction reportViolation(site: KeyDisciplineSite, apis: Set<string>): void {\n const { tier, id } = site;\n const name = site.label ?? id;\n const apiList = Array.from(apis).join(', ');\n const wording = TIERS[tier];\n const remedy =\n `Either pass request-derived values ${wording.passAs} (included in the ` +\n `cache key) or remove the ${apiList} call.`;\n\n if (strict) {\n throw new KeyDisciplineViolation(\n `[timber] ${tier} key-discipline violation: \"${name}\" reads ${apiList} ` +\n `during ${wording.work}. The cache key is computed from ` +\n `${wording.keyedBy} only — caching this result would serve one ` +\n `user's data to another. ${remedy} ` +\n `To downgrade this to a warning, set cache.strictKeyDiscipline: false ` +\n `in timber.config.ts.`\n );\n }\n\n const now = Date.now();\n const key = rateLimitKey(site);\n const last = lastEmitted.get(key);\n if (last !== undefined && now - last < RATE_LIMIT_MS) return;\n if (lastEmitted.size >= PRUNE_AT) {\n for (const [k, t] of lastEmitted) if (now - t >= RATE_LIMIT_MS) lastEmitted.delete(k);\n }\n lastEmitted.set(key, now);\n\n logKeyDisciplineViolation(`${tier} cross-user data leak risk`, {\n ...(tier === 'cache.component'\n ? { component: name }\n : { fn: name, id, cacheKey: site.cacheKey }),\n accessedApis: Array.from(apis),\n message:\n `${tier} \"${name}\" reads ${apiList} but the cache key is computed ` +\n `from ${wording.keyedBy} only. If the result varies by ${apiList}, ` +\n `different users may see each other's cached data. ${remedy}`,\n });\n}\n\n/**\n * Reset all diagnostic state. Exported for tests only.\n */\nexport function resetKeyDisciplineState(): void {\n lastEmitted.clear();\n strict = false;\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 { logCacheMiss, logSwrRefetchFailed, swallow } from '../server/logger.ts';\nimport { guardedRead } from './guarded-read.ts';\nimport { getWaitUntil } from '../server/waituntil-bridge.ts';\nimport { fnv1aHash } from './fast-hash.ts';\nimport { devDataCacheKey } from '../server/prebuilt/dev-store.ts';\nimport { KeyDisciplineViolation, observeKeyDiscipline } from './key-discipline.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, and\n * inside one, fn runs under the key-discipline observer (design/45\n * §Enforcement): the key comes from the arguments only, so a\n * request-context read in fn is reported, or rejected in strict mode\n * before the result is stored.\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 // Key-discipline rate-limit id. An explicit-key callsite without a\n // build-time ID has no fnId; its source hash is stable enough for a\n // rate limit and, unlike deriveFallbackFnId, never warns.\n const disciplineId = fnId ?? `key-fn:${fnv1aHash(fn.toString())}`;\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 // The key the handler sees: in dev, scoped to the source generation.\n const storeKey = devDataCacheKey(key);\n\n const cacheStart = performance.now();\n const cached = await guardedRead(key, () => getHandler().get(storeKey), null);\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. The\n // store key, not the logical key: in dev it carries the source\n // generation, so a caller after a save never joins a pre-save flight.\n const tags = resolveTags(opts, args);\n const flightKey = `${storeKey}\\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 // Observed on every execution — the miss path and the SWR refetch,\n // which runs in the triggering request's context. Never on a hit:\n // a hit runs no fn, so it reads nothing.\n let result: Awaited<ReturnType<Fn>>;\n try {\n result = await observeKeyDiscipline(\n { tier: 'cache.data', id: disciplineId, label: fn.name || undefined, cacheKey: key },\n () => fn(...args)\n );\n } catch (err) {\n // Strict key discipline rejected this fn, so any entry already\n // under the key was computed by the same request-reading fn (stored\n // before strict mode was on). Drop it rather than serve it to\n // everyone as stale — but only under the same guards as a write: a\n // timed-out or superseded flight must not delete a newer result.\n if (\n err instanceof KeyDisciplineViolation &&\n !signal.aborted &&\n writeGenerations.get(key) === generation\n ) {\n await getHandler()\n .invalidate({ key: storeKey })\n .catch((e: unknown) => swallow(e, `cache invalidate failed for key \"${key}\"`));\n }\n throw err;\n }\n if (!signal.aborted && !wasInvalidatedSince(startEpoch, key, tags)) {\n try {\n await getHandler().set(storeKey, 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 (unless\n // executeAndStore dropped it for a key-discipline violation).\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 logCacheMiss({ cacheKey: key });\n\n return result;\n }) as unknown as Fn;\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\n/** A store whose optional capability methods are known to be present. */\ntype StoreWith<K extends keyof CacheStore> = CacheStore & Required<Pick<CacheStore, K>>;\ntype NativeStore = StoreWith<'setWithTags' | 'invalidateTag'>;\ntype EagerStore = StoreWith<'sadd' | 'smembers' | 'srem' | 'sdel'>;\n\n/**\n * The detected strategy carries the store narrowed to the capabilities that\n * strategy relies on, so each branch calls those methods without assertions.\n */\ntype Strategy =\n | { kind: 'native'; store: NativeStore }\n | { kind: 'eager'; store: EagerStore }\n | { kind: '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 isNativeStore(store: CacheStore): store is NativeStore {\n return !!(store.setWithTags && store.invalidateTag);\n}\n\nfunction isEagerStore(store: CacheStore): store is EagerStore {\n return !!(store.sadd && store.smembers && store.srem && store.sdel);\n}\n\nfunction detectStrategy(store: CacheStore): Strategy {\n if (isNativeStore(store)) return { kind: 'native', store };\n if (isEagerStore(store)) return { kind: 'eager', store };\n return { kind: '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.kind !== 'lazy') {\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 const strategy = this.strategy;\n\n if (strategy.kind === '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 strategy.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 (strategy.kind === '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) => strategy.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 const strategy = this.strategy;\n\n if (opts.key) {\n const key = opts.key;\n if (strategy.kind === 'eager') {\n const raw = await this.store.get(this.dataKey(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) => strategy.store.srem(this.tagSetKey(tag), [key]))\n );\n }\n }\n }\n await this.store.del(this.dataKey(key));\n }\n\n if (opts.tag) {\n const tag = opts.tag;\n if (strategy.kind === 'native') {\n await strategy.store.invalidateTag(`${this.prefix}${tag}`);\n } else if (strategy.kind === 'eager') {\n const members = await strategy.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 && (JSON.parse(raw) as EagerEntry).tags.includes(tag)) {\n await this.store.del(this.dataKey(k));\n }\n await strategy.store.srem(this.tagSetKey(tag), [k]);\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 runtime config\n * (`virtual:timber-config`'s `deploymentId`). Null in dev mode.\n */\nlet currentDeploymentId: string | null = null;\n\n/**\n * Set the current deployment ID. Called once at server startup by the RSC\n * entry's `createRequestHandler()`. In dev mode this is never called\n * (deployment ID 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/** A seed entry: build artifact bytes, or their dev-store counterpart. */\nexport interface Seed {\n payload: Uint8Array;\n /** When the seed was rendered — the logical start of its `ttl`. */\n capturedAt: number;\n}\n\n/** The build-artifact seed for an entry, or null if the build has none. */\nexport async function lookupArtifactSeed(\n id: string,\n cacheKey: string,\n needsTimestamp: boolean\n): Promise<Seed | null> {\n const payload = await lookupPrebuiltPayload(id, cacheKey);\n if (payload === null) return null;\n const entry = needsTimestamp ? await getManifestEntry(id, cacheKey) : null;\n return { payload, capturedAt: entry?.buildTimestamp ?? 0 };\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 { guardedRead } from '../../cache/guarded-read.ts';\nimport { wasInvalidatedSince } from '../../cache/invalidation-epoch.ts';\nimport { getDeploymentId } from '../version-skew.ts';\nimport { devOverlayNamespace } from './dev-store.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\n/**\n * In dev the deployment ID is null; the dev store namespace stands in for\n * it and changes on every source change, so entries stored before a save\n * become unreachable (server/prebuilt/dev-store.ts).\n */\nexport function overlayKey(componentId: string, cacheKey: string): string {\n const deploymentId = getDeploymentId() ?? devOverlayNamespace() ?? 'dev';\n return `timber:c:${deploymentId}:${componentId}:${cacheKey}`;\n}\n\n/**\n * Whether a re-render that started at `startEpoch` may store its capture\n * under `oKey`: nothing invalidated the key or its tags meanwhile\n * (TIM-1028), and the overlay key has not moved on. In dev a save moves it\n * to a new namespace, and the bytes may come from the pre-save code: stored,\n * they would answer every request after the save.\n */\nexport function mayStoreRerender(\n startEpoch: number,\n componentId: string,\n cacheKey: string,\n oKey: string,\n tags: string[]\n): boolean {\n return !wasInvalidatedSince(startEpoch, oKey, tags) && overlayKey(componentId, cacheKey) === oKey;\n}\n\n// ─── Overlay read ────────────────────────────────────────────────────────\n\nexport interface OverlayLookupResult {\n /**\n * `unreadable`: the handler read threw or timed out (cache/guarded-read.ts).\n * Not a miss — a miss falls through to the build seed, and the overlay the\n * read could not reach may hold that seed's tombstone. The caller renders\n * instead of trusting the seed.\n */\n kind: 'fresh' | 'stale' | 'tombstone' | 'unreadable';\n /** The overlay value (null for tombstones and unreadable reads). */\n record: ComponentOverlayRecord | null;\n /** Raw flight payload bytes (decoded from base64). Null for tombstones and unreadable reads. */\n payload: Uint8Array | null;\n}\n\nconst READ_FAILED: unique symbol = Symbol('overlay read failed');\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 guardedRead(key, () => handler.get(key), READ_FAILED);\n if (result === READ_FAILED) return { kind: 'unreadable', record: null, payload: null };\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 { devDataCacheKey, invalidateDevSeedsByTag } from '../server/prebuilt/dev-store.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(\n opts.key === undefined ? opts : { ...opts, key: devDataCacheKey(opts.key) }\n );\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 // Dev has no build seeds to tombstone — its seeds live in the dev\n // store, so drop them instead (no-op outside dev, TIM-1588).\n invalidateDevSeedsByTag(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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,SAAgB,eAAkE;CAChF,OAAO,aAAa,SAAS;AAC/B;;;;;;;;;;;;;;;;ACtBA,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,UAA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;EAKA,IAAI,KAAK,KAAK;GACZ,MAAM,sBAAsB,KAAK,GAAG;GAGpC,wBAAwB,KAAK,GAAG;EAClC;EAKA,IAAI,KAAK,KAAK;GACZ,MAAM,eAAe,mBAAmB;GACxC,IAAI,cACF,IAAI;IACF,MAAM,QAAQ,KAAK,CACjB,aAAa,UAAU,CAAC,KAAK,GAAG,CAAC,GACjC,IAAI,SAAe,GAAG,WACpB,iBAAiB,uBAAO,IAAI,MAAM,2BAA2B,CAAC,GAAG,GAAM,CACzE,CACF,CAAC;GACH,SAAS,KAAK;IACZ,QAAQ,MAAM,sCAAsC,GAAG;GACzD;EAEJ;CACF;;;;;;;;;;CAYA,UACE,aACA,UACG;EACH,IAAI,CAAC,wBAAwB,IAAI,WAAW,GAAG;GAC7C,wBAAwB,IAAI,WAAW;GACvC,MAAM,OAAO,YAAY,QAAQ;GACjC,QAAQ,KACN,8BAA8B,KAAK,2IAGrC;EACF;EACA,OAAO;CACT;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli-context-CbZp32SK.js","names":[],"sources":["../../src/cli-context.ts"],"sourcesContent":["/**\n * Resolve timber's configuration the way `timber build` resolves it, for CLI\n * commands that run outside the build: `timber check` and `timber preview`.\n *\n * Reading `timber.config.ts` directly is **not** equivalent, which is the whole\n * reason this goes through Vite (TIM-1332, review round 3; TIM-1531):\n *\n * - Config passed inline — `timber({ pageExtensions, adapter, output })` in\n * `vite.config.ts` — lives only in the plugin's closure. Nothing that\n * re-reads the config file can see it.\n * - `root` is Vite's resolved root, not the caller's cwd, and the two differ in\n * the monorepo layouts TIM-498 describes.\n * - The build directory can come from Vite's `build.outDir`, which only a\n * resolved Vite config knows.\n * - `--config` names a Vite config file; only Vite can load it.\n *\n * There is no fallback to a second, hand-rolled resolution. A project whose\n * Vite config does not produce the timber plugin cannot be built either, so a\n * command that quietly proceeded on a guess would act on an app that does not\n * exist.\n *\n * Design docs: 11-platform.md §CLI\n */\n\nimport { isTimberPluginApi, type PluginContext } from './plugin-context.ts';\n\n/** The plugin that publishes timber's resolved context on its Vite `api`. */\nconst TIMBER_ROOT_SYNC_PLUGIN = 'timber-root-sync';\n\n/** The subset of a resolved Vite plugin this module reads. */\nexport interface PluginWithApi {\n name: string;\n api?: unknown;\n}\n\n/**\n * Vite's own `resolveConfig`, narrowed to what this module passes and reads.\n *\n * The seam sits at `resolveConfig` rather than at \"give me the plugins\" so the\n * *arguments* are the thing under test: which config file, which command, and\n * which mode defaults. Those arguments have been wrong three separate times\n * (TIM-1332 rounds 4-6), and a double that answered \"here are the plugins\"\n * could not see any of it. The double returns what Vite returns — plugins with\n * an opaque `api` — so the lookup and narrowing under test stay the real ones.\n */\nexport type ResolveViteConfig = (\n inlineConfig: { configFile: string | undefined },\n command: 'build',\n defaultMode: string,\n defaultNodeEnv: string\n) => Promise<{ plugins: readonly PluginWithApi[] }>;\n\n/**\n * Ask Vite for the resolved config, which is what carries timber's context.\n *\n * `resolveConfig` runs the whole config pipeline — config file discovery,\n * `config` and `configResolved` hooks — so the context it produces is the one\n * `timber build` would use. Measured at ~300-400ms on a real app.\n */\nconst defaultResolveViteConfig: ResolveViteConfig = async (\n inlineConfig,\n command,\n defaultMode,\n defaultNodeEnv\n) => {\n const { resolveConfig } = await import('vite');\n return resolveConfig(inlineConfig, command, defaultMode, defaultNodeEnv);\n};\n\n/**\n * The mode defaults `timber build` resolves under.\n *\n * `resolveConfig`'s own defaults are `'development'` for both, but nothing\n * reaches it with those on a build: `createBuilder` goes through Vite's\n * internal `resolveConfigToBuild`, which calls\n * `resolveConfig(inlineConfig, 'build', 'production', 'production')`. A config\n * written as `defineConfig(({ mode }) => …)`, or one that loads `.env.production`,\n * therefore resolves to a *different* app under the two. Passing the defaults\n * explicitly is what makes \"check validates what build builds\" — and \"preview\n * serves what build wrote\" — true rather than true-by-coincidence for configs\n * that ignore mode (TIM-1332, round 6).\n */\nconst BUILD_MODE_DEFAULTS = ['production', 'production'] as const;\n\n/**\n * Resolve the project through Vite and return timber's context as\n * `timber build` would see it.\n *\n * @param command The CLI command asking, named in the error message.\n * @param viteConfigFile `--config`. Undefined means Vite's own discovery, the\n * same as `timber build` without the flag.\n */\nexport async function resolveTimberContext(\n command: string,\n viteConfigFile: string | undefined,\n resolveViteConfig: ResolveViteConfig = defaultResolveViteConfig\n): Promise<PluginContext> {\n // `configFile: undefined` is Vite's own \"discover it\" value, so the default\n // path stays exactly what Vite does for `timber build` without `--config`.\n const { plugins } = await resolveViteConfig(\n { configFile: viteConfigFile },\n 'build',\n ...BUILD_MODE_DEFAULTS\n );\n\n const rootSync = plugins.find((plugin) => plugin.name === TIMBER_ROOT_SYNC_PLUGIN);\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] Could not read the resolved timber configuration from your Vite config.\\n\\n` +\n ` \\`timber ${command}\\` resolves your project through Vite so it sees the same\\n` +\n ` configuration \\`timber build\\` uses — including config passed inline to timber().\\n\\n` +\n ` Check that vite.config.ts exists and lists the timber plugin:\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n\n return rootSync.api.getContext();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,0BAA0B;;;;;;;;AAgChC,IAAM,2BAA8C,OAClD,cACA,SACA,aACA,mBACG;CACH,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,OAAO,cAAc,cAAc,SAAS,aAAa,cAAc;AACzE;;;;;;;;;;;;;;AAeA,IAAM,sBAAsB,CAAC,cAAc,YAAY;;;;;;;;;AAUvD,eAAsB,qBACpB,SACA,gBACA,oBAAuC,0BACf;CAGxB,MAAM,EAAE,YAAY,MAAM,kBACxB,EAAE,YAAY,eAAe,GAC7B,SACA,GAAG,mBACL;CAEA,MAAM,WAAW,QAAQ,MAAM,WAAW,OAAO,SAAS,uBAAuB;CACjF,IAAI,CAAC,YAAY,CAAC,kBAAkB,SAAS,GAAG,GAC9C,MAAM,IAAI,MACR,kGACgB,QAAQ,iTAK1B;CAGF,OAAO,SAAS,IAAI,WAAW;AACjC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { t as resolveTimberContext } from "./cli-context-CbZp32SK.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"singleflight-BChPMjwH.js","names":[],"sources":["../../src/cache/singleflight.ts"],"sourcesContent":["/**\n * Singleflight coalesces concurrent calls with the same key into a single\n * execution. All callers receive the same result (or error).\n *\n * Per-process, in-memory. Each process coalesces independently.\n *\n * An optional `timeoutMs` prevents hung `fn()` calls from permanently\n * blocking all future callers for that key. When set, `fn()` is raced\n * against a timeout — if the timeout fires first, the promise rejects\n * with `SingleflightTimeoutError`, `finally` cleans up the key, and\n * subsequent callers can retry. See TIM-518.\n */\n\nexport interface SingleflightOptions {\n /** Maximum time (ms) a coalesced call may run before being rejected. */\n timeoutMs?: number;\n}\n\nexport interface Singleflight {\n do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;\n /** Return the in-flight promise for a key, or undefined if none. */\n get(key: string): Promise<unknown> | undefined;\n}\n\n/**\n * Error thrown when a singleflight call exceeds `timeoutMs`.\n * Exported so callers can distinguish timeout from other errors.\n */\nexport class SingleflightTimeoutError extends Error {\n constructor(key: string, timeoutMs: number) {\n super(`Singleflight timeout: key \"${key}\" exceeded ${timeoutMs}ms`);\n this.name = 'SingleflightTimeoutError';\n }\n}\n\nexport function createSingleflight(opts?: SingleflightOptions): Singleflight {\n const inflight = new Map<string, Promise<unknown>>();\n const timeoutMs = opts?.timeoutMs;\n\n return {\n do<T>(key: string, fn: (signal: AbortSignal) => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\n const ac = new AbortController();\n let promise: Promise<T>;\n\n if (timeoutMs != null && timeoutMs > 0) {\n // Race fn() against a timeout to prevent hung calls from\n // permanently blocking the key. See TIM-518.\n // Abort the signal on timeout so the callback can skip\n // side effects (e.g. cache writes). See TIM-1092.\n promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n // The timeout error is also the signal's reason, so the body\n // can tell why it was aborted (runBackgroundFlight reports it).\n const timeout = new SingleflightTimeoutError(key, timeoutMs);\n ac.abort(timeout);\n reject(timeout);\n }, timeoutMs);\n try {\n fn(ac.signal).then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (err) => {\n clearTimeout(timer);\n reject(err);\n }\n );\n } catch (err) {\n clearTimeout(timer);\n reject(err);\n }\n });\n } else {\n promise = fn(ac.signal);\n }\n\n const tracked = promise.finally(() => {\n inflight.delete(key);\n });\n\n inflight.set(key, tracked);\n return tracked as Promise<T>;\n },\n get(key: string): Promise<unknown> | undefined {\n return inflight.get(key);\n },\n };\n}\n"],"mappings":";;;;;AA4BA,IAAa,2BAAb,cAA8C,MAAM;CAClD,YAAY,KAAa,WAAmB;EAC1C,MAAM,8BAA8B,IAAI,aAAa,UAAU,GAAG;EAClE,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,mBAAmB,MAA0C;CAC3E,MAAM,2BAAW,IAAI,IAA8B;CACnD,MAAM,YAAY,MAAM;CAExB,OAAO;EACL,GAAM,KAAa,IAAqD;GACtE,MAAM,WAAW,SAAS,IAAI,GAAG;GACjC,IAAI,UAAU,OAAO;GAErB,MAAM,KAAK,IAAI,gBAAgB;GAC/B,IAAI;GAEJ,IAAI,aAAa,QAAQ,YAAY,GAKnC,UAAU,IAAI,SAAY,SAAS,WAAW;IAC5C,MAAM,QAAQ,iBAAiB;KAG7B,MAAM,UAAU,IAAI,yBAAyB,KAAK,SAAS;KAC3D,GAAG,MAAM,OAAO;KAChB,OAAO,OAAO;IAChB,GAAG,SAAS;IACZ,IAAI;KACF,GAAG,GAAG,MAAM,CAAC,CAAC,MACX,UAAU;MACT,aAAa,KAAK;MAClB,QAAQ,KAAK;KACf,IACC,QAAQ;MACP,aAAa,KAAK;MAClB,OAAO,GAAG;KACZ,CACF;IACF,SAAS,KAAK;KACZ,aAAa,KAAK;KAClB,OAAO,GAAG;IACZ;GACF,CAAC;QAED,UAAU,GAAG,GAAG,MAAM;GAGxB,MAAM,UAAU,QAAQ,cAAc;IACpC,SAAS,OAAO,GAAG;GACrB,CAAC;GAED,SAAS,IAAI,KAAK,OAAO;GACzB,OAAO;EACT;EACA,IAAI,KAA2C;GAC7C,OAAO,SAAS,IAAI,GAAG;EACzB;CACF;AACF"}
|
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server-side nuqs adapter provider for SSR rendering.
|
|
3
|
-
*
|
|
4
|
-
* During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
|
|
5
|
-
* useQueryState) need the nuqs adapter context. The client adapter
|
|
6
|
-
* (TimberNuqsAdapter) relies on `window` and React hooks that are
|
|
7
|
-
* client-only. This provider supplies a static, SSR-safe adapter
|
|
8
|
-
* that feeds the current request's search params into the nuqs context.
|
|
9
|
-
*
|
|
10
|
-
* The returned component wraps the React tree so that nuqs hooks render
|
|
11
|
-
* the correct initial values during server-side rendering. On the client,
|
|
12
|
-
* TimberNuqsAdapter (injected by browser-entry.ts) takes over.
|
|
13
|
-
*
|
|
14
|
-
* Design doc: design/23-search-params.md §"Custom Adapter"
|
|
15
|
-
*/
|
|
16
|
-
import { type ReactNode } from 'react';
|
|
17
|
-
/**
|
|
18
|
-
* Wrap the SSR element tree with a nuqs adapter context.
|
|
19
|
-
*
|
|
20
|
-
* Called by ssr-entry.ts before passing the element to renderSsrStream.
|
|
21
|
-
* Takes the NavContext raw query string and provides it to nuqs hooks
|
|
22
|
-
* running during SSR so they render with the correct initial values.
|
|
23
|
-
*
|
|
24
|
-
* The raw string — not a collapsed record — is what preserves repeated
|
|
25
|
-
* query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
|
|
26
|
-
* `location.search` the client adapter reads after hydration (TIM-1428).
|
|
27
|
-
*
|
|
28
|
-
* @param search - The request's raw app-visible query string (`''` or `?…`)
|
|
29
|
-
* @param children - The React element tree to wrap
|
|
30
|
-
*/
|
|
31
|
-
export declare function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode;
|
|
32
|
-
//# sourceMappingURL=nuqs-ssr-provider.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nuqs-ssr-provider.d.ts","sourceRoot":"","sources":["../../src/server/nuqs-ssr-provider.tsx"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAiB,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AA2BtD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,SAAS,GAAG,SAAS,CAMjF"}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Server-side nuqs adapter provider for SSR rendering.
|
|
3
|
-
*
|
|
4
|
-
* During SSR, `'use client'` components that call nuqs hooks (useQueryStates,
|
|
5
|
-
* useQueryState) need the nuqs adapter context. The client adapter
|
|
6
|
-
* (TimberNuqsAdapter) relies on `window` and React hooks that are
|
|
7
|
-
* client-only. This provider supplies a static, SSR-safe adapter
|
|
8
|
-
* that feeds the current request's search params into the nuqs context.
|
|
9
|
-
*
|
|
10
|
-
* The returned component wraps the React tree so that nuqs hooks render
|
|
11
|
-
* the correct initial values during server-side rendering. On the client,
|
|
12
|
-
* TimberNuqsAdapter (injected by browser-entry.ts) takes over.
|
|
13
|
-
*
|
|
14
|
-
* Design doc: design/23-search-params.md §"Custom Adapter"
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
import { createElement, type ReactNode } from 'react';
|
|
18
|
-
import {
|
|
19
|
-
unstable_createAdapterProvider as createAdapterProvider,
|
|
20
|
-
type unstable_AdapterInterface as AdapterInterface,
|
|
21
|
-
} from 'nuqs/adapters/custom';
|
|
22
|
-
|
|
23
|
-
// ─── SSR Adapter ──────────────────────────────────────────────────
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Create a nuqs adapter provider for SSR that serves a static snapshot
|
|
27
|
-
* of search params. The `updateUrl` is a no-op because URL updates
|
|
28
|
-
* cannot happen on the server.
|
|
29
|
-
*/
|
|
30
|
-
function makeNuqsSsrAdapter(searchParams: URLSearchParams) {
|
|
31
|
-
function useNuqsSsrAdapter(_watchKeys: string[]): AdapterInterface {
|
|
32
|
-
return {
|
|
33
|
-
searchParams,
|
|
34
|
-
updateUrl: () => {},
|
|
35
|
-
getSearchParamsSnapshot: () => searchParams,
|
|
36
|
-
};
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return createAdapterProvider(useNuqsSsrAdapter);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// ─── Provider Component ───────────────────────────────────────────
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* Wrap the SSR element tree with a nuqs adapter context.
|
|
46
|
-
*
|
|
47
|
-
* Called by ssr-entry.ts before passing the element to renderSsrStream.
|
|
48
|
-
* Takes the NavContext raw query string and provides it to nuqs hooks
|
|
49
|
-
* running during SSR so they render with the correct initial values.
|
|
50
|
-
*
|
|
51
|
-
* The raw string — not a collapsed record — is what preserves repeated
|
|
52
|
-
* query keys (`?tag=a&tag=b`) for nuqs multi parsers, matching the raw
|
|
53
|
-
* `location.search` the client adapter reads after hydration (TIM-1428).
|
|
54
|
-
*
|
|
55
|
-
* @param search - The request's raw app-visible query string (`''` or `?…`)
|
|
56
|
-
* @param children - The React element tree to wrap
|
|
57
|
-
*/
|
|
58
|
-
export function withNuqsSsrAdapter(search: string, children: ReactNode): ReactNode {
|
|
59
|
-
const searchParams = new URLSearchParams(search);
|
|
60
|
-
const Provider = makeNuqsSsrAdapter(searchParams);
|
|
61
|
-
// AdapterProvider types require children in the props object (not as 3rd arg)
|
|
62
|
-
// eslint-disable-next-line react/no-children-prop
|
|
63
|
-
return createElement(Provider, { defaultOptions: { shallow: false, scroll: true }, children });
|
|
64
|
-
}
|