@timber-js/app 0.2.0-alpha.132 → 0.2.0-alpha.134

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +8 -0
  2. package/dist/_chunks/{actions-BNhpxrnV.js → actions-B8Fhsosm.js} +51 -12
  3. package/dist/_chunks/actions-B8Fhsosm.js.map +1 -0
  4. package/dist/_chunks/build-output-helper-K7oUCRqU.js.map +1 -1
  5. package/dist/_chunks/cli-schema-sync-q-Ce6-iG.js.map +1 -1
  6. package/dist/_chunks/codec-registry-DqkeAydt.js.map +1 -1
  7. package/dist/_chunks/define-DMq-Yjp7.js.map +1 -1
  8. package/dist/_chunks/define-jeHDXZGq.js.map +1 -1
  9. package/dist/_chunks/format-BjN9HLu9.js.map +1 -1
  10. package/dist/_chunks/handler-store-bIAstrxQ.js.map +1 -1
  11. package/dist/_chunks/href-validation-BJmD5mZh.js +124 -0
  12. package/dist/_chunks/href-validation-BJmD5mZh.js.map +1 -0
  13. package/dist/_chunks/logger-CMd9P1xQ.js.map +1 -1
  14. package/dist/_chunks/metadata-routes-DESG8uk5.js.map +1 -1
  15. package/dist/_chunks/navigation-root-B5-RmsPi.js.map +1 -1
  16. package/dist/_chunks/registry-BI9cgCt7.js.map +1 -1
  17. package/dist/_chunks/resolve-schema-DU2nbVOi.js.map +1 -1
  18. package/dist/_chunks/router-ref-B2-2kIIC.js.map +1 -1
  19. package/dist/_chunks/schema-bridge-o0SwFtXW.js.map +1 -1
  20. package/dist/_chunks/segment-classify-BjfuctV2.js.map +1 -1
  21. package/dist/_chunks/segment-context-Bg0pFbLT.js.map +1 -1
  22. package/dist/_chunks/ssr-data-DVX8S7vj.js.map +1 -1
  23. package/dist/_chunks/stale-reload-CCqb62Z3.js.map +1 -1
  24. package/dist/_chunks/tracing-DP5djRq5.js.map +1 -1
  25. package/dist/_chunks/use-query-states-C9G6LP0F.js.map +1 -1
  26. package/dist/_chunks/use-segment-params-CIeinIx2.js.map +1 -1
  27. package/dist/_chunks/validation-AfEFM5ze.js.map +1 -1
  28. package/dist/_chunks/walkers-BbEu2_Pp.js.map +1 -1
  29. package/dist/_chunks/warnings-CAzunaGo.js.map +1 -1
  30. package/dist/adapters/cloudflare-dev.js.map +1 -1
  31. package/dist/adapters/cloudflare-kv-cache.js.map +1 -1
  32. package/dist/adapters/cloudflare.js.map +1 -1
  33. package/dist/adapters/nitro.js.map +1 -1
  34. package/dist/cache/index.js.map +1 -1
  35. package/dist/cli.js.map +1 -1
  36. package/dist/client/error-boundary.js.map +1 -1
  37. package/dist/client/index.js +5 -17
  38. package/dist/client/index.js.map +1 -1
  39. package/dist/client/internal.js.map +1 -1
  40. package/dist/client/link.d.ts +2 -4
  41. package/dist/client/link.d.ts.map +1 -1
  42. package/dist/client/use-router.d.ts.map +1 -1
  43. package/dist/codec.js.map +1 -1
  44. package/dist/cookies/index.js.map +1 -1
  45. package/dist/index.js +153 -0
  46. package/dist/index.js.map +1 -1
  47. package/dist/params/index.js.map +1 -1
  48. package/dist/search-params/index.js.map +1 -1
  49. package/dist/server/deny-renderer.d.ts.map +1 -1
  50. package/dist/server/index.js +1 -1
  51. package/dist/server/index.js.map +1 -1
  52. package/dist/server/internal.js +22 -11
  53. package/dist/server/internal.js.map +1 -1
  54. package/dist/server/pipeline-interception.d.ts.map +1 -1
  55. package/dist/server/pipeline-phases.d.ts +5 -1
  56. package/dist/server/pipeline-phases.d.ts.map +1 -1
  57. package/dist/server/pipeline.d.ts.map +1 -1
  58. package/dist/server/primitives.d.ts +5 -2
  59. package/dist/server/primitives.d.ts.map +1 -1
  60. package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
  61. package/dist/shared/href-validation.d.ts +38 -0
  62. package/dist/shared/href-validation.d.ts.map +1 -0
  63. package/dist/shims/font-google.js.map +1 -1
  64. package/dist/shims/font-local.js.map +1 -1
  65. package/package.json +12 -13
  66. package/src/cli.ts +0 -0
  67. package/src/client/link.tsx +5 -32
  68. package/src/client/use-router.ts +3 -0
  69. package/src/server/deny-renderer.ts +0 -1
  70. package/src/server/pipeline-interception.ts +1 -0
  71. package/src/server/pipeline-phases.ts +30 -19
  72. package/src/server/pipeline.ts +18 -1
  73. package/src/server/primitives.ts +8 -17
  74. package/src/server/rsc-entry/rsc-payload.ts +0 -4
  75. package/src/shared/href-validation.ts +123 -0
  76. package/dist/_chunks/actions-BNhpxrnV.js.map +0 -1
  77. package/dist/_chunks/merge-search-params-Cm1j99HC.js +0 -41
  78. package/dist/_chunks/merge-search-params-Cm1j99HC.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare.js","names":[],"sources":["../../src/adapters/cloudflare.ts"],"sourcesContent":["// Cloudflare Workers adapter\n//\n// Primary deployment target. Generates a Workers-compatible entry point\n// and wrangler.jsonc configuration. See design/11-platform.md §\"Cloudflare Workers\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Bindings passthrough ─────────────────────────────────────────────────\n// ALS stores the env object per-request so server components and middleware\n// can access KV, D1, DO, R2, Queues, etc. via getCloudflareBindings().\n// No global fallback — if called outside a request, it throws.\n// See design/11-platform.md §\"Platform Target\" and design/25-production-deployments.md.\n//\n// The ALS is stored on globalThis via Symbol.for so it survives Vite's\n// module instance split in dev mode. The Vite host process (where\n// cloudflareDevBindings → runWithBindings runs) and the RSC module runner\n// (where getCloudflareBindings runs) load separate instances of this file,\n// each with their own module-level variables. globalThis + Symbol.for\n// ensures both share the same ALS — same pattern React uses for\n// Symbol.for('react.element').\n\nconst BINDINGS_ALS_KEY = Symbol.for('timber:cf-bindings-als');\n\nfunction getBindingsAls(): AsyncLocalStorage<Record<string, unknown>> {\n let als = (globalThis as any)[BINDINGS_ALS_KEY] as\n | AsyncLocalStorage<Record<string, unknown>>\n | undefined;\n if (!als) {\n als = new AsyncLocalStorage<Record<string, unknown>>();\n (globalThis as any)[BINDINGS_ALS_KEY] = als;\n }\n return als;\n}\n\n/**\n * Get Cloudflare Worker bindings for the current request.\n *\n * Returns the `env` object passed to the Worker's `fetch` handler,\n * giving direct access to KV, D1, Durable Objects, R2, Queues, and\n * any other bindings configured in `wrangler.jsonc`.\n *\n * Must be called within a request context (server component, middleware,\n * server action). Throws outside a request.\n *\n * @example\n * ```ts\n * import { getCloudflareBindings } from '@timber-js/app/adapters/cloudflare'\n *\n * export default async function Page() {\n * const { MY_KV, MY_DB } = getCloudflareBindings()\n * const data = await MY_KV.get('key')\n * return <div>{data}</div>\n * }\n * ```\n */\nexport function getCloudflareBindings<T = Record<string, unknown>>(): T {\n const env = getBindingsAls().getStore();\n if (!env) {\n throw new Error(\n 'getCloudflareBindings() called outside a Cloudflare Workers request context. ' +\n 'It can only be called from server components, middleware, or server actions ' +\n 'when running on the Cloudflare adapter.'\n );\n }\n return env as T;\n}\n\n/**\n * Run a function with Cloudflare bindings available via getCloudflareBindings().\n * @internal Used by wrapWithExecutionContext.\n */\nexport function runWithBindings<T>(env: Record<string, unknown>, fn: () => T): T {\n return getBindingsAls().run(env, fn);\n}\n\n// ─── Binding configuration types ──────────────────────────────────────────────\n// Declarative binding config that maps to wrangler.jsonc binding sections.\n// See design/35-cloudflare-primitives.md §\"Binding Declarations in Adapter Config\".\n\n/** KV namespace binding. `id` defaults to `''` (filled in by wrangler or dashboard). */\nexport interface CloudflareKVBinding {\n name: string;\n id?: string;\n}\n\n/** D1 database binding. `database_id` is required (from Cloudflare dashboard). */\nexport interface CloudflareD1Binding {\n name: string;\n database_id: string;\n}\n\n/** R2 bucket binding. `bucket_name` must match the bucket created in Cloudflare. */\nexport interface CloudflareR2Binding {\n name: string;\n bucket_name: string;\n}\n\n/** Queue producer binding. `queue` is the queue name in Cloudflare. */\nexport interface CloudflareQueueProducer {\n name: string;\n queue: string;\n}\n\n/** Queue consumer declaration. Attached to the worker, not a binding name. */\nexport interface CloudflareQueueConsumer {\n queue: string;\n max_batch_size?: number;\n max_retries?: number;\n dead_letter_queue?: string;\n}\n\n/** Durable Object binding. `script_name` is for external DO references. */\nexport interface CloudflareDurableObjectBinding {\n name: string;\n class_name: string;\n script_name?: string;\n}\n\n/**\n * Declarative Cloudflare bindings configuration.\n *\n * These are converted to the appropriate wrangler.jsonc sections\n * (`kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, `durable_objects`).\n * The `wrangler` escape hatch overrides any generated binding sections\n * if there's a conflict.\n *\n * @example\n * ```ts\n * cloudflare({\n * bindings: {\n * kv: [{ name: 'TIMBER_CACHE' }],\n * d1: [{ name: 'MY_DB', database_id: 'xxxx' }],\n * r2: [{ name: 'MY_BUCKET', bucket_name: 'my-bucket' }],\n * queues: {\n * producers: [{ name: 'EMAIL_QUEUE', queue: 'email-queue' }],\n * consumers: [{ queue: 'email-queue', max_batch_size: 10 }],\n * },\n * durableObjects: [{ name: 'MY_DO', class_name: 'MyDurableObject' }],\n * },\n * })\n * ```\n */\nexport interface CloudflareBindings {\n kv?: CloudflareKVBinding[];\n d1?: CloudflareD1Binding[];\n r2?: CloudflareR2Binding[];\n queues?: {\n producers?: CloudflareQueueProducer[];\n consumers?: CloudflareQueueConsumer[];\n };\n durableObjects?: CloudflareDurableObjectBinding[];\n}\n\n/** Options for the Cloudflare Workers adapter. */\nexport interface CloudflareAdapterOptions {\n /**\n * Cloudflare compatibility date.\n * @default Current date in YYYY-MM-DD format at build time.\n */\n compatibilityDate?: string;\n\n /**\n * Additional compatibility flags.\n * @default ['nodejs_compat']\n */\n compatibilityFlags?: string[];\n\n /**\n * Declarative Cloudflare bindings. Generates the appropriate\n * `kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, and\n * `durable_objects` sections in wrangler.jsonc.\n *\n * If both `bindings` and `wrangler` specify the same section,\n * `wrangler` wins (it's the escape hatch).\n */\n bindings?: CloudflareBindings;\n\n /**\n * Custom wrangler.jsonc fields to merge.\n * Overrides generated values (including bindings-generated sections).\n */\n wrangler?: Record<string, unknown>;\n\n /**\n * Path to a module that exports additional Worker handlers (queue, scheduled, email, etc.).\n * The module is imported in the generated `_worker.js` and its named exports are\n * spread into the default export alongside `fetch`.\n *\n * The module receives `(batch/event, env, ctx)` — standard Cloudflare handler signatures.\n * It does NOT have access to timber's request pipeline (no ALS, no getCloudflareBindings).\n * Use `env` directly for bindings.\n *\n * @example\n * ```ts\n * // timber.config.ts\n * adapter: cloudflare({ workerHandlers: './src/worker-handlers.ts' })\n *\n * // src/worker-handlers.ts\n * export async function queue(batch, env) { ... }\n * export async function scheduled(controller, env, ctx) { ... }\n * ```\n */\n workerHandlers?: string;\n}\n\n/**\n * Create a Cloudflare Workers adapter.\n *\n * @example\n * ```ts\n * import { cloudflare } from '@timber-js/app/adapters/cloudflare'\n *\n * export default {\n * output: 'server',\n * adapter: cloudflare(),\n * }\n * ```\n */\nexport function cloudflare(options: CloudflareAdapterOptions = {}): TimberPlatformAdapter {\n return {\n name: 'cloudflare',\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'cloudflare');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'static',\n });\n\n // Compile optional worker handlers (queue, scheduled, etc.)\n // Uses Vite's build API to bundle the TypeScript source into ESM.\n let hasWorkerHandlers = false;\n if (options.workerHandlers) {\n const handlersEntry = join(process.cwd(), options.workerHandlers);\n const { build: viteBuild } = await import('vite');\n await viteBuild({\n configFile: false,\n logLevel: 'info',\n build: {\n lib: {\n entry: handlersEntry,\n formats: ['es'],\n fileName: () => '_worker-handlers.js',\n },\n outDir,\n emptyOutDir: false,\n minify: false,\n rollupOptions: {\n external: [/^node:/],\n },\n },\n });\n hasWorkerHandlers = true;\n }\n\n // Generate the Workers entry point\n const hasManifestInit = !!config.manifestInit;\n const workerEntry = generateWorkerEntry(outDir, outDir, hasManifestInit, hasWorkerHandlers);\n await writeFile(join(outDir, '_worker.js'), workerEntry);\n\n // Generate wrangler.jsonc\n const wranglerConfig = generateWranglerConfig(config, options);\n await writeFile(join(outDir, 'wrangler.jsonc'), JSON.stringify(wranglerConfig, null, 2));\n },\n\n async preview(_config: TimberConfig, buildDir: string) {\n const cmd = generatePreviewCommand(buildDir);\n await spawnPreviewProcess(cmd.command, cmd.args, cmd.cwd);\n },\n\n // Default no-op. wrapWithExecutionContext() replaces this per-request\n // with a function that routes to ctx.waitUntil().\n waitUntil(_promise: Promise<unknown>) {},\n };\n}\n\n/**\n * Wrap a timber request handler to bind the Cloudflare execution context\n * for `waitUntil()` support and env bindings passthrough.\n * Called from the generated worker entry.\n *\n * This function:\n * 1. Binds `adapter.waitUntil()` to `ctx.waitUntil()` per-request\n * 2. Makes `env` accessible via `getCloudflareBindings()` per-request via ALS\n */\nexport function wrapWithExecutionContext(\n adapter: TimberPlatformAdapter,\n handler: (req: Request) => Promise<Response>\n): CfExportedHandler<Record<string, unknown>> {\n return {\n async fetch(\n request: Request,\n env: Record<string, unknown>,\n ctx: CfExecutionContext\n ): Promise<Response> {\n // Bind the adapter's waitUntil to the Workers execution context\n const originalWaitUntil = adapter.waitUntil;\n adapter.waitUntil = (promise: Promise<unknown>) => {\n ctx.waitUntil(promise);\n };\n\n try {\n // Run the handler within ALS so getCloudflareBindings() works\n return await runWithBindings(env, () => handler(request));\n } finally {\n // Restore (in case adapter is reused across isolate resets)\n adapter.waitUntil = originalWaitUntil;\n }\n },\n };\n}\n\n// ─── Exported helpers (used by tests and build) ─────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateWorkerEntry(\n buildDir: string,\n outDir: string,\n hasManifestInit = false,\n hasWorkerHandlers = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let rscEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!rscEntryRelative.startsWith('.')) {\n rscEntryRelative = './' + rscEntryRelative;\n }\n\n // Build manifest init must be imported before the RSC handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Optional additional Worker handlers (queue, scheduled, email, etc.)\n // Compiled by buildOutput via Vite's build API into _worker-handlers.js.\n // The module's named exports are spread into the default export alongside fetch.\n const handlersImport = hasWorkerHandlers\n ? \"import * as workerHandlers from './_worker-handlers.js'\\n\"\n : '';\n const handlersSpread = hasWorkerHandlers ? ' ...workerHandlers,\\n' : '';\n\n return `// Generated by @timber-js/app/adapters/cloudflare\n// Do not edit — this file is regenerated on each build.\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${manifestImport}import handler from '${rscEntryRelative}'\n${handlersImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nglobalThis.process ??= { env: {} }\nprocess.env.TIMBER_RUNTIME = 'cloudflare'\n\n// Bind Cloudflare env to ALS so getCloudflareBindings() works at runtime.\n// Uses the same Symbol.for key as getCloudflareBindings() reads from.\nconst ALS_KEY = Symbol.for('timber:cf-bindings-als')\nlet bindingsAls = globalThis[ALS_KEY]\nif (!bindingsAls) {\n bindingsAls = new AsyncLocalStorage()\n globalThis[ALS_KEY] = bindingsAls\n}\n\nexport default {\n${handlersSpread} async fetch(request, env, ctx) {\n return bindingsAls.run(env, () => handler(request))\n }\n}\n`;\n}\n\n/** Wrangler binding sections generated from `CloudflareBindings`. */\nexport interface WranglerBindingsConfig {\n kv_namespaces?: Array<{ binding: string; id: string }>;\n d1_databases?: Array<{ binding: string; database_id: string }>;\n r2_buckets?: Array<{ binding: string; bucket_name: string }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<Record<string, unknown>>;\n };\n durable_objects?: {\n bindings: Array<Record<string, string>>;\n };\n}\n\n/**\n * Convert declarative `CloudflareBindings` into wrangler.jsonc binding sections.\n *\n * Maps:\n * - `kv` → `kv_namespaces`\n * - `d1` → `d1_databases`\n * - `r2` → `r2_buckets`\n * - `queues` → `queues` (producers + consumers)\n * - `durableObjects` → `durable_objects`\n *\n * Empty arrays are omitted from the output.\n *\n * @internal Exported for testing.\n */\nexport function generateBindingsConfig(\n bindings: CloudflareBindings | undefined\n): WranglerBindingsConfig {\n if (!bindings) return {};\n\n const result: WranglerBindingsConfig = {};\n\n // KV namespaces\n if (bindings.kv && bindings.kv.length > 0) {\n result.kv_namespaces = bindings.kv.map((kv) => ({\n binding: kv.name,\n id: kv.id ?? '',\n }));\n }\n\n // D1 databases\n if (bindings.d1 && bindings.d1.length > 0) {\n result.d1_databases = bindings.d1.map((d1) => ({\n binding: d1.name,\n database_id: d1.database_id,\n }));\n }\n\n // R2 buckets\n if (bindings.r2 && bindings.r2.length > 0) {\n result.r2_buckets = bindings.r2.map((r2) => ({\n binding: r2.name,\n bucket_name: r2.bucket_name,\n }));\n }\n\n // Queues (producers and/or consumers)\n if (bindings.queues) {\n const queues: Record<string, unknown> = {};\n if (bindings.queues.producers && bindings.queues.producers.length > 0) {\n queues.producers = bindings.queues.producers.map((p) => ({\n binding: p.name,\n queue: p.queue,\n }));\n }\n if (bindings.queues.consumers && bindings.queues.consumers.length > 0) {\n queues.consumers = bindings.queues.consumers.map((c) => {\n const consumer: Record<string, unknown> = { queue: c.queue };\n if (c.max_batch_size !== undefined) consumer.max_batch_size = c.max_batch_size;\n if (c.max_retries !== undefined) consumer.max_retries = c.max_retries;\n if (c.dead_letter_queue !== undefined) consumer.dead_letter_queue = c.dead_letter_queue;\n return consumer;\n });\n }\n if (Object.keys(queues).length > 0) {\n result.queues = queues;\n }\n }\n\n // Durable Objects\n if (bindings.durableObjects && bindings.durableObjects.length > 0) {\n result.durable_objects = {\n bindings: bindings.durableObjects.map((dobj) => {\n const entry: Record<string, string> = {\n name: dobj.name,\n class_name: dobj.class_name,\n };\n if (dobj.script_name) entry.script_name = dobj.script_name;\n return entry;\n }),\n };\n }\n\n return result;\n}\n\n/**\n * One-level deep merge: for each key in `override`, if both the base and\n * override values are plain objects (not arrays, not null), merge their\n * keys with override winning on conflicts. Everything else (primitives,\n * arrays, null) is replaced outright — matching the intuitive behavior\n * where `kv_namespaces: [...]` replaces fully but\n * `durable_objects: { migrations }` merges with generated `bindings`.\n */\nfunction shallowDeepMerge(\n base: Record<string, unknown>,\n override: Record<string, unknown>\n): Record<string, unknown> {\n const result = { ...base };\n for (const key of Object.keys(override)) {\n const baseVal = result[key];\n const overVal = override[key];\n if (isPlainObject(baseVal) && isPlainObject(overVal)) {\n result[key] = { ...baseVal, ...overVal };\n } else {\n result[key] = overVal;\n }\n }\n return result;\n}\n\n/** True for `{}` literals — false for arrays, null, Date, etc. */\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return val !== null && typeof val === 'object' && !Array.isArray(val);\n}\n\n/** @internal Exported for testing. */\nexport function generateWranglerConfig(\n config: TimberConfig,\n options: CloudflareAdapterOptions\n): Record<string, unknown> {\n const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);\n\n const flags = options.compatibilityFlags ?? ['nodejs_compat'];\n\n const base: Record<string, unknown> = {\n name: 'timber-app',\n main: '_worker.js',\n compatibility_date: compatDate,\n compatibility_flags: flags,\n // The build output is already fully bundled by Vite — skip wrangler's\n // esbuild pass to avoid issues with top-level await and module format.\n no_bundle: true,\n find_additional_modules: true,\n rules: [{ type: 'ESModule', globs: ['**/*.js'] }],\n assets: {\n directory: './static',\n },\n };\n\n // Layer 1: merge bindings-generated sections into base\n const bindingsConfig = generateBindingsConfig(options.bindings);\n const merged = { ...base, ...bindingsConfig };\n\n // Layer 2: wrangler escape hatch with deep merge for nested plain objects.\n // A shallow spread would replace entire sections like durable_objects and\n // queues — e.g. adding migrations via wrangler would drop the generated\n // durable_objects.bindings. Deep merge preserves generated keys while\n // letting wrangler override on actual key-level conflicts.\n if (options.wrangler) {\n return shallowDeepMerge(merged, options.wrangler);\n }\n\n return merged;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Command descriptor for preview — testable without spawning a process. */\nexport interface PreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generatePreviewCommand(buildDir: string): PreviewCommand {\n const cfDir = join(buildDir, 'cloudflare');\n return {\n command: 'wrangler',\n args: ['dev', '--local', '--config', join(cfDir, 'wrangler.jsonc')],\n cwd: cfDir,\n };\n}\n\n/**\n * Spawn a long-running preview process and pipe stdio to the parent.\n * Resolves when the process exits.\n */\nfunction spawnPreviewProcess(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Cloudflare Workers type stubs ───────────────────────────────────────────\n// Local type declarations so this file compiles without @cloudflare/workers-types.\n// These are NOT declared globally — that would clash with @cloudflare/workers-types\n// when users install it. Instead, they're module-scoped and used only within\n// this file's function signatures.\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExportedHandler<Env = Record<string, unknown>> {\n fetch?(request: Request, env: Env, ctx: CfExecutionContext): Promise<Response> | Response;\n}\n"],"mappings":";;;;;;AA0BA,IAAM,mBAAmB,OAAO,IAAI,yBAAyB;AAE7D,SAAS,iBAA6D;CACpE,IAAI,MAAO,WAAmB;AAG9B,KAAI,CAAC,KAAK;AACR,QAAM,IAAI,mBAA4C;AACrD,aAAmB,oBAAoB;;AAE1C,QAAO;;;;;;;;;;;;;;;;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MAAM,GAAG,GAAG;EAQnF,qBANY,QAAQ,sBAAsB,CAAC,gBAAgB;EAS3D,WAAW;EACX,yBAAyB;EACzB,OAAO,CAAC;GAAE,MAAM;GAAY,OAAO,CAAC,UAAU;GAAE,CAAC;EACjD,QAAQ,EACN,WAAW,YACZ;EACF;CAGD,MAAM,iBAAiB,uBAAuB,QAAQ,SAAS;CAC/D,MAAM,SAAS;EAAE,GAAG;EAAM,GAAG;EAAgB;AAO7C,KAAI,QAAQ,SACV,QAAO,iBAAiB,QAAQ,QAAQ,SAAS;AAGnD,QAAO;;;AAaT,SAAgB,uBAAuB,UAAkC;CACvE,MAAM,QAAQ,KAAK,UAAU,aAAa;AAC1C,QAAO;EACL,SAAS;EACT,MAAM;GAAC;GAAO;GAAW;GAAY,KAAK,OAAO,iBAAiB;GAAC;EACnE,KAAK;EACN;;;;;;AAOH,SAAS,oBAAoB,SAAiB,MAAgB,KAA4B;AACxF,QAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,QAAQ,SAAS,SAAS,MAAM,EAAE,KAAK,GAAG,QAAQ;AACtD,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;AACF,QAAM,QAAQ,KAAK,QAAQ,OAAO;AAClC,QAAM,QAAQ,KAAK,QAAQ,OAAO;GAClC"}
1
+ {"version":3,"file":"cloudflare.js","names":[],"sources":["../../src/adapters/cloudflare.ts"],"sourcesContent":["// Cloudflare Workers adapter\n//\n// Primary deployment target. Generates a Workers-compatible entry point\n// and wrangler.jsonc configuration. See design/11-platform.md §\"Cloudflare Workers\".\n\nimport { writeFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Bindings passthrough ─────────────────────────────────────────────────\n// ALS stores the env object per-request so server components and middleware\n// can access KV, D1, DO, R2, Queues, etc. via getCloudflareBindings().\n// No global fallback — if called outside a request, it throws.\n// See design/11-platform.md §\"Platform Target\" and design/25-production-deployments.md.\n//\n// The ALS is stored on globalThis via Symbol.for so it survives Vite's\n// module instance split in dev mode. The Vite host process (where\n// cloudflareDevBindings → runWithBindings runs) and the RSC module runner\n// (where getCloudflareBindings runs) load separate instances of this file,\n// each with their own module-level variables. globalThis + Symbol.for\n// ensures both share the same ALS — same pattern React uses for\n// Symbol.for('react.element').\n\nconst BINDINGS_ALS_KEY = Symbol.for('timber:cf-bindings-als');\n\nfunction getBindingsAls(): AsyncLocalStorage<Record<string, unknown>> {\n let als = (globalThis as any)[BINDINGS_ALS_KEY] as\n | AsyncLocalStorage<Record<string, unknown>>\n | undefined;\n if (!als) {\n als = new AsyncLocalStorage<Record<string, unknown>>();\n (globalThis as any)[BINDINGS_ALS_KEY] = als;\n }\n return als;\n}\n\n/**\n * Get Cloudflare Worker bindings for the current request.\n *\n * Returns the `env` object passed to the Worker's `fetch` handler,\n * giving direct access to KV, D1, Durable Objects, R2, Queues, and\n * any other bindings configured in `wrangler.jsonc`.\n *\n * Must be called within a request context (server component, middleware,\n * server action). Throws outside a request.\n *\n * @example\n * ```ts\n * import { getCloudflareBindings } from '@timber-js/app/adapters/cloudflare'\n *\n * export default async function Page() {\n * const { MY_KV, MY_DB } = getCloudflareBindings()\n * const data = await MY_KV.get('key')\n * return <div>{data}</div>\n * }\n * ```\n */\nexport function getCloudflareBindings<T = Record<string, unknown>>(): T {\n const env = getBindingsAls().getStore();\n if (!env) {\n throw new Error(\n 'getCloudflareBindings() called outside a Cloudflare Workers request context. ' +\n 'It can only be called from server components, middleware, or server actions ' +\n 'when running on the Cloudflare adapter.'\n );\n }\n return env as T;\n}\n\n/**\n * Run a function with Cloudflare bindings available via getCloudflareBindings().\n * @internal Used by wrapWithExecutionContext.\n */\nexport function runWithBindings<T>(env: Record<string, unknown>, fn: () => T): T {\n return getBindingsAls().run(env, fn);\n}\n\n// ─── Binding configuration types ──────────────────────────────────────────────\n// Declarative binding config that maps to wrangler.jsonc binding sections.\n// See design/35-cloudflare-primitives.md §\"Binding Declarations in Adapter Config\".\n\n/** KV namespace binding. `id` defaults to `''` (filled in by wrangler or dashboard). */\nexport interface CloudflareKVBinding {\n name: string;\n id?: string;\n}\n\n/** D1 database binding. `database_id` is required (from Cloudflare dashboard). */\nexport interface CloudflareD1Binding {\n name: string;\n database_id: string;\n}\n\n/** R2 bucket binding. `bucket_name` must match the bucket created in Cloudflare. */\nexport interface CloudflareR2Binding {\n name: string;\n bucket_name: string;\n}\n\n/** Queue producer binding. `queue` is the queue name in Cloudflare. */\nexport interface CloudflareQueueProducer {\n name: string;\n queue: string;\n}\n\n/** Queue consumer declaration. Attached to the worker, not a binding name. */\nexport interface CloudflareQueueConsumer {\n queue: string;\n max_batch_size?: number;\n max_retries?: number;\n dead_letter_queue?: string;\n}\n\n/** Durable Object binding. `script_name` is for external DO references. */\nexport interface CloudflareDurableObjectBinding {\n name: string;\n class_name: string;\n script_name?: string;\n}\n\n/**\n * Declarative Cloudflare bindings configuration.\n *\n * These are converted to the appropriate wrangler.jsonc sections\n * (`kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, `durable_objects`).\n * The `wrangler` escape hatch overrides any generated binding sections\n * if there's a conflict.\n *\n * @example\n * ```ts\n * cloudflare({\n * bindings: {\n * kv: [{ name: 'TIMBER_CACHE' }],\n * d1: [{ name: 'MY_DB', database_id: 'xxxx' }],\n * r2: [{ name: 'MY_BUCKET', bucket_name: 'my-bucket' }],\n * queues: {\n * producers: [{ name: 'EMAIL_QUEUE', queue: 'email-queue' }],\n * consumers: [{ queue: 'email-queue', max_batch_size: 10 }],\n * },\n * durableObjects: [{ name: 'MY_DO', class_name: 'MyDurableObject' }],\n * },\n * })\n * ```\n */\nexport interface CloudflareBindings {\n kv?: CloudflareKVBinding[];\n d1?: CloudflareD1Binding[];\n r2?: CloudflareR2Binding[];\n queues?: {\n producers?: CloudflareQueueProducer[];\n consumers?: CloudflareQueueConsumer[];\n };\n durableObjects?: CloudflareDurableObjectBinding[];\n}\n\n/** Options for the Cloudflare Workers adapter. */\nexport interface CloudflareAdapterOptions {\n /**\n * Cloudflare compatibility date.\n * @default Current date in YYYY-MM-DD format at build time.\n */\n compatibilityDate?: string;\n\n /**\n * Additional compatibility flags.\n * @default ['nodejs_compat']\n */\n compatibilityFlags?: string[];\n\n /**\n * Declarative Cloudflare bindings. Generates the appropriate\n * `kv_namespaces`, `d1_databases`, `r2_buckets`, `queues`, and\n * `durable_objects` sections in wrangler.jsonc.\n *\n * If both `bindings` and `wrangler` specify the same section,\n * `wrangler` wins (it's the escape hatch).\n */\n bindings?: CloudflareBindings;\n\n /**\n * Custom wrangler.jsonc fields to merge.\n * Overrides generated values (including bindings-generated sections).\n */\n wrangler?: Record<string, unknown>;\n\n /**\n * Path to a module that exports additional Worker handlers (queue, scheduled, email, etc.).\n * The module is imported in the generated `_worker.js` and its named exports are\n * spread into the default export alongside `fetch`.\n *\n * The module receives `(batch/event, env, ctx)` — standard Cloudflare handler signatures.\n * It does NOT have access to timber's request pipeline (no ALS, no getCloudflareBindings).\n * Use `env` directly for bindings.\n *\n * @example\n * ```ts\n * // timber.config.ts\n * adapter: cloudflare({ workerHandlers: './src/worker-handlers.ts' })\n *\n * // src/worker-handlers.ts\n * export async function queue(batch, env) { ... }\n * export async function scheduled(controller, env, ctx) { ... }\n * ```\n */\n workerHandlers?: string;\n}\n\n/**\n * Create a Cloudflare Workers adapter.\n *\n * @example\n * ```ts\n * import { cloudflare } from '@timber-js/app/adapters/cloudflare'\n *\n * export default {\n * output: 'server',\n * adapter: cloudflare(),\n * }\n * ```\n */\nexport function cloudflare(options: CloudflareAdapterOptions = {}): TimberPlatformAdapter {\n return {\n name: 'cloudflare',\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'cloudflare');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'static',\n });\n\n // Compile optional worker handlers (queue, scheduled, etc.)\n // Uses Vite's build API to bundle the TypeScript source into ESM.\n let hasWorkerHandlers = false;\n if (options.workerHandlers) {\n const handlersEntry = join(process.cwd(), options.workerHandlers);\n const { build: viteBuild } = await import('vite');\n await viteBuild({\n configFile: false,\n logLevel: 'info',\n build: {\n lib: {\n entry: handlersEntry,\n formats: ['es'],\n fileName: () => '_worker-handlers.js',\n },\n outDir,\n emptyOutDir: false,\n minify: false,\n rollupOptions: {\n external: [/^node:/],\n },\n },\n });\n hasWorkerHandlers = true;\n }\n\n // Generate the Workers entry point\n const hasManifestInit = !!config.manifestInit;\n const workerEntry = generateWorkerEntry(outDir, outDir, hasManifestInit, hasWorkerHandlers);\n await writeFile(join(outDir, '_worker.js'), workerEntry);\n\n // Generate wrangler.jsonc\n const wranglerConfig = generateWranglerConfig(config, options);\n await writeFile(join(outDir, 'wrangler.jsonc'), JSON.stringify(wranglerConfig, null, 2));\n },\n\n async preview(_config: TimberConfig, buildDir: string) {\n const cmd = generatePreviewCommand(buildDir);\n await spawnPreviewProcess(cmd.command, cmd.args, cmd.cwd);\n },\n\n // Default no-op. wrapWithExecutionContext() replaces this per-request\n // with a function that routes to ctx.waitUntil().\n waitUntil(_promise: Promise<unknown>) {},\n };\n}\n\n/**\n * Wrap a timber request handler to bind the Cloudflare execution context\n * for `waitUntil()` support and env bindings passthrough.\n * Called from the generated worker entry.\n *\n * This function:\n * 1. Binds `adapter.waitUntil()` to `ctx.waitUntil()` per-request\n * 2. Makes `env` accessible via `getCloudflareBindings()` per-request via ALS\n */\nexport function wrapWithExecutionContext(\n adapter: TimberPlatformAdapter,\n handler: (req: Request) => Promise<Response>\n): CfExportedHandler<Record<string, unknown>> {\n return {\n async fetch(\n request: Request,\n env: Record<string, unknown>,\n ctx: CfExecutionContext\n ): Promise<Response> {\n // Bind the adapter's waitUntil to the Workers execution context\n const originalWaitUntil = adapter.waitUntil;\n adapter.waitUntil = (promise: Promise<unknown>) => {\n ctx.waitUntil(promise);\n };\n\n try {\n // Run the handler within ALS so getCloudflareBindings() works\n return await runWithBindings(env, () => handler(request));\n } finally {\n // Restore (in case adapter is reused across isolate resets)\n adapter.waitUntil = originalWaitUntil;\n }\n },\n };\n}\n\n// ─── Exported helpers (used by tests and build) ─────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateWorkerEntry(\n buildDir: string,\n outDir: string,\n hasManifestInit = false,\n hasWorkerHandlers = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // The Vite RSC plugin outputs it to rsc/index.js.\n let rscEntryRelative = relative(outDir, join(buildDir, 'rsc', 'index.js'));\n // Ensure the import path starts with ./ for ESM compatibility\n if (!rscEntryRelative.startsWith('.')) {\n rscEntryRelative = './' + rscEntryRelative;\n }\n\n // Build manifest init must be imported before the RSC handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Optional additional Worker handlers (queue, scheduled, email, etc.)\n // Compiled by buildOutput via Vite's build API into _worker-handlers.js.\n // The module's named exports are spread into the default export alongside fetch.\n const handlersImport = hasWorkerHandlers\n ? \"import * as workerHandlers from './_worker-handlers.js'\\n\"\n : '';\n const handlersSpread = hasWorkerHandlers ? ' ...workerHandlers,\\n' : '';\n\n return `// Generated by @timber-js/app/adapters/cloudflare\n// Do not edit — this file is regenerated on each build.\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\n${manifestImport}import handler from '${rscEntryRelative}'\n${handlersImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nglobalThis.process ??= { env: {} }\nprocess.env.TIMBER_RUNTIME = 'cloudflare'\n\n// Bind Cloudflare env to ALS so getCloudflareBindings() works at runtime.\n// Uses the same Symbol.for key as getCloudflareBindings() reads from.\nconst ALS_KEY = Symbol.for('timber:cf-bindings-als')\nlet bindingsAls = globalThis[ALS_KEY]\nif (!bindingsAls) {\n bindingsAls = new AsyncLocalStorage()\n globalThis[ALS_KEY] = bindingsAls\n}\n\nexport default {\n${handlersSpread} async fetch(request, env, ctx) {\n return bindingsAls.run(env, () => handler(request))\n }\n}\n`;\n}\n\n/** Wrangler binding sections generated from `CloudflareBindings`. */\nexport interface WranglerBindingsConfig {\n kv_namespaces?: Array<{ binding: string; id: string }>;\n d1_databases?: Array<{ binding: string; database_id: string }>;\n r2_buckets?: Array<{ binding: string; bucket_name: string }>;\n queues?: {\n producers?: Array<{ binding: string; queue: string }>;\n consumers?: Array<Record<string, unknown>>;\n };\n durable_objects?: {\n bindings: Array<Record<string, string>>;\n };\n}\n\n/**\n * Convert declarative `CloudflareBindings` into wrangler.jsonc binding sections.\n *\n * Maps:\n * - `kv` → `kv_namespaces`\n * - `d1` → `d1_databases`\n * - `r2` → `r2_buckets`\n * - `queues` → `queues` (producers + consumers)\n * - `durableObjects` → `durable_objects`\n *\n * Empty arrays are omitted from the output.\n *\n * @internal Exported for testing.\n */\nexport function generateBindingsConfig(\n bindings: CloudflareBindings | undefined\n): WranglerBindingsConfig {\n if (!bindings) return {};\n\n const result: WranglerBindingsConfig = {};\n\n // KV namespaces\n if (bindings.kv && bindings.kv.length > 0) {\n result.kv_namespaces = bindings.kv.map((kv) => ({\n binding: kv.name,\n id: kv.id ?? '',\n }));\n }\n\n // D1 databases\n if (bindings.d1 && bindings.d1.length > 0) {\n result.d1_databases = bindings.d1.map((d1) => ({\n binding: d1.name,\n database_id: d1.database_id,\n }));\n }\n\n // R2 buckets\n if (bindings.r2 && bindings.r2.length > 0) {\n result.r2_buckets = bindings.r2.map((r2) => ({\n binding: r2.name,\n bucket_name: r2.bucket_name,\n }));\n }\n\n // Queues (producers and/or consumers)\n if (bindings.queues) {\n const queues: Record<string, unknown> = {};\n if (bindings.queues.producers && bindings.queues.producers.length > 0) {\n queues.producers = bindings.queues.producers.map((p) => ({\n binding: p.name,\n queue: p.queue,\n }));\n }\n if (bindings.queues.consumers && bindings.queues.consumers.length > 0) {\n queues.consumers = bindings.queues.consumers.map((c) => {\n const consumer: Record<string, unknown> = { queue: c.queue };\n if (c.max_batch_size !== undefined) consumer.max_batch_size = c.max_batch_size;\n if (c.max_retries !== undefined) consumer.max_retries = c.max_retries;\n if (c.dead_letter_queue !== undefined) consumer.dead_letter_queue = c.dead_letter_queue;\n return consumer;\n });\n }\n if (Object.keys(queues).length > 0) {\n result.queues = queues;\n }\n }\n\n // Durable Objects\n if (bindings.durableObjects && bindings.durableObjects.length > 0) {\n result.durable_objects = {\n bindings: bindings.durableObjects.map((dobj) => {\n const entry: Record<string, string> = {\n name: dobj.name,\n class_name: dobj.class_name,\n };\n if (dobj.script_name) entry.script_name = dobj.script_name;\n return entry;\n }),\n };\n }\n\n return result;\n}\n\n/**\n * One-level deep merge: for each key in `override`, if both the base and\n * override values are plain objects (not arrays, not null), merge their\n * keys with override winning on conflicts. Everything else (primitives,\n * arrays, null) is replaced outright — matching the intuitive behavior\n * where `kv_namespaces: [...]` replaces fully but\n * `durable_objects: { migrations }` merges with generated `bindings`.\n */\nfunction shallowDeepMerge(\n base: Record<string, unknown>,\n override: Record<string, unknown>\n): Record<string, unknown> {\n const result = { ...base };\n for (const key of Object.keys(override)) {\n const baseVal = result[key];\n const overVal = override[key];\n if (isPlainObject(baseVal) && isPlainObject(overVal)) {\n result[key] = { ...baseVal, ...overVal };\n } else {\n result[key] = overVal;\n }\n }\n return result;\n}\n\n/** True for `{}` literals — false for arrays, null, Date, etc. */\nfunction isPlainObject(val: unknown): val is Record<string, unknown> {\n return val !== null && typeof val === 'object' && !Array.isArray(val);\n}\n\n/** @internal Exported for testing. */\nexport function generateWranglerConfig(\n config: TimberConfig,\n options: CloudflareAdapterOptions\n): Record<string, unknown> {\n const compatDate = options.compatibilityDate ?? new Date().toISOString().slice(0, 10);\n\n const flags = options.compatibilityFlags ?? ['nodejs_compat'];\n\n const base: Record<string, unknown> = {\n name: 'timber-app',\n main: '_worker.js',\n compatibility_date: compatDate,\n compatibility_flags: flags,\n // The build output is already fully bundled by Vite — skip wrangler's\n // esbuild pass to avoid issues with top-level await and module format.\n no_bundle: true,\n find_additional_modules: true,\n rules: [{ type: 'ESModule', globs: ['**/*.js'] }],\n assets: {\n directory: './static',\n },\n };\n\n // Layer 1: merge bindings-generated sections into base\n const bindingsConfig = generateBindingsConfig(options.bindings);\n const merged = { ...base, ...bindingsConfig };\n\n // Layer 2: wrangler escape hatch with deep merge for nested plain objects.\n // A shallow spread would replace entire sections like durable_objects and\n // queues — e.g. adding migrations via wrangler would drop the generated\n // durable_objects.bindings. Deep merge preserves generated keys while\n // letting wrangler override on actual key-level conflicts.\n if (options.wrangler) {\n return shallowDeepMerge(merged, options.wrangler);\n }\n\n return merged;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Command descriptor for preview — testable without spawning a process. */\nexport interface PreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generatePreviewCommand(buildDir: string): PreviewCommand {\n const cfDir = join(buildDir, 'cloudflare');\n return {\n command: 'wrangler',\n args: ['dev', '--local', '--config', join(cfDir, 'wrangler.jsonc')],\n cwd: cfDir,\n };\n}\n\n/**\n * Spawn a long-running preview process and pipe stdio to the parent.\n * Resolves when the process exits.\n */\nfunction spawnPreviewProcess(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Cloudflare Workers type stubs ───────────────────────────────────────────\n// Local type declarations so this file compiles without @cloudflare/workers-types.\n// These are NOT declared globally — that would clash with @cloudflare/workers-types\n// when users install it. Instead, they're module-scoped and used only within\n// this file's function signatures.\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\n/** @internal Minimal stub — use @cloudflare/workers-types for full types. */\nexport interface CfExportedHandler<Env = Record<string, unknown>> {\n fetch?(request: Request, env: Env, ctx: CfExecutionContext): Promise<Response> | Response;\n}\n"],"mappings":";;;;;;AA0BA,IAAM,mBAAmB,OAAO,IAAI,yBAAyB;AAE7D,SAAS,iBAA6D;CACpE,IAAI,MAAO,WAAmB;CAG9B,IAAI,CAAC,KAAK;EACR,MAAM,IAAI,mBAA4C;EACtD,WAAoB,oBAAoB;;CAE1C,OAAO;;;;;;;;;;;;;;;;;;;;;;;AAwBT,SAAgB,wBAAwD;CACtE,MAAM,MAAM,gBAAgB,CAAC,UAAU;CACvC,IAAI,CAAC,KACH,MAAM,IAAI,MACR,mMAGD;CAEH,OAAO;;;;;;AAOT,SAAgB,gBAAmB,KAA8B,IAAgB;CAC/E,OAAO,gBAAgB,CAAC,IAAI,KAAK,GAAG;;;;;;;;;;;;;;;AAkJtC,SAAgB,WAAW,UAAoC,EAAE,EAAyB;CACxF,OAAO;EACL,MAAM;EAEN,MAAM,YAAY,QAAsB,UAAkB;GACxD,MAAM,SAAS,KAAK,UAAU,aAAa;GAI3C,MAAM,oBAAoB;IACxB;IACA;IACA;IACA,eAAe;IAChB,CAAC;GAIF,IAAI,oBAAoB;GACxB,IAAI,QAAQ,gBAAgB;IAC1B,MAAM,gBAAgB,KAAK,QAAQ,KAAK,EAAE,QAAQ,eAAe;IACjE,MAAM,EAAE,OAAO,cAAc,MAAM,OAAO;IAC1C,MAAM,UAAU;KACd,YAAY;KACZ,UAAU;KACV,OAAO;MACL,KAAK;OACH,OAAO;OACP,SAAS,CAAC,KAAK;OACf,gBAAgB;OACjB;MACD;MACA,aAAa;MACb,QAAQ;MACR,eAAe,EACb,UAAU,CAAC,SAAS,EACrB;MACF;KACF,CAAC;IACF,oBAAoB;;GAKtB,MAAM,cA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@ -1 +1 @@
1
- {"version":3,"file":"nitro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Generated compression module template for self-hosted deployments.\n//\n// This file generates a standalone ESM module (_compress.mjs) that is\n// written to the build output during adapter buildOutput(). It's imported\n// by the Nitro entry and preview server at runtime.\n//\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n// Cloudflare Workers don't need this — the edge auto-compresses.\n//\n// See design/25-production-deployments.md.\n\n/**\n * Generate a standalone ESM module that exports compressResponse().\n *\n * Written to `_compress.mjs` during buildOutput. Imported by the Nitro entry\n * and preview server.\n *\n * @internal Exported for testing.\n */\nexport function generateCompressModule(): string {\n return `// Generated by @timber-js/app — response compression for self-hosted deployments.\n// Do not edit — this file is regenerated on each build.\n// Uses node:zlib createGzip() (C++ native) on Node.js, falls back to\n// CompressionStream (Web API) on other runtimes. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal.\nimport { Readable } from 'node:stream';\nimport { createGzip, constants } from 'node:zlib';\n\nconst COMPRESSIBLE_TYPES = new Set([\n 'text/html', 'text/css', 'text/plain', 'text/xml', 'text/javascript',\n 'text/x-component', 'application/json', 'application/javascript',\n 'application/xml', 'application/xhtml+xml', 'application/rss+xml',\n 'application/atom+xml', 'image/svg+xml',\n]);\n\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\nfunction negotiateEncoding(acceptEncoding) {\n if (!acceptEncoding) return null;\n // Parse tokens with quality values. Per RFC 9110 §12.5.3, q=0 means\n // \"not acceptable\" — the client explicitly rejects that encoding.\n // Brotli (br) is intentionally not handled at the application level.\n const parts = acceptEncoding.split(',');\n for (const part of parts) {\n const [token, ...params] = part.split(';');\n const name = token.trim().toLowerCase();\n if (name !== 'gzip') continue;\n let qValue = 1;\n for (const param of params) {\n const trimmed = param.trim().toLowerCase();\n if (trimmed.startsWith('q=')) {\n qValue = parseFloat(trimmed.slice(2));\n if (Number.isNaN(qValue)) qValue = 1;\n break;\n }\n }\n if (qValue > 0) return 'gzip';\n }\n return null;\n}\n\nfunction shouldCompress(response) {\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n if (response.headers.has('Content-Encoding')) return false;\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n if (mimeType === 'text/event-stream') return false;\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\nfunction compressWithGzip(body) {\n // Use node:zlib (C++ native) for gzip compression. The Web Streams\n // CompressionStream works but every chunk crosses the JS/Promise boundary.\n // node:zlib.createGzip() compresses entirely in C++ with zero per-chunk\n // Promise overhead.\n //\n // Convert: Web ReadableStream → Node Readable → pipe through gzip →\n // Node Readable → Readable.toWeb() → Web ReadableStream\n try {\n const nodeReadable = Readable.fromWeb(body);\n // Z_SYNC_FLUSH ensures each chunk is flushed immediately so the browser\n // receives the HTML shell before Suspense boundaries resolve. Without it,\n // gzip buffers internally and breaks streaming.\n const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n const compressed = nodeReadable.pipe(gzip);\n return Readable.toWeb(compressed);\n } catch {\n // Fallback: CompressionStream (CF Workers, or if node:stream unavailable)\n return body.pipeThrough(new CompressionStream('gzip'));\n }\n}\n\nexport function compressResponse(request, response) {\n if (!shouldCompress(response)) return response;\n const acceptEncoding = request.headers.get('Accept-Encoding') || '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n const compressedBody = compressWithGzip(response.body);\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', existingVary + ', Accept-Encoding');\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { IMMUTABLE_CACHE } from './shared.js';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write the compression helper module for runtime use.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), generateCompressModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n await runNitroBuild(outDir, preset, options.nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n entry: './entry.ts',\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitro/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || process.env.HOSTNAME || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url || '/', \\`http://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const cacheControl = url.pathname.startsWith('/assets/')\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response back to the Node response.\n //\n // Set-Cookie needs special handling: Headers.entries() joins multiple\n // Set-Cookie values with \", \" into a single entry, but each cookie must\n // be its own header per RFC 6265 §4.1. Object.fromEntries() would then\n // collapse them into one malformed Set-Cookie header that browsers reject\n // (or only honor partially). Use getSetCookie() to preserve individual\n // values, and pass them as an array — Node's writeHead accepts\n // Record<string, string | string[]> and emits one header per array entry.\n //\n // Without this, EVERY cookie set by the framework on Node—/Nitro deployments\n // is silently dropped: defineCookie().setCookie() in actions, middleware\n // cookie writes, the framework's own session cookies, all of it. See\n // LOCAL-741.\n const responseHeaders: Record<string, string | string[]> = {};\n webResponse.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n responseHeaders[key] = value;\n }\n });\n const setCookies = webResponse.headers.getSetCookie();\n if (setCookies.length > 0) {\n responseHeaders['set-cookie'] = setCookies;\n }\n res.writeHead(webResponse.status, responseHeaders);\n\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n\n // Cancel the reader when the client disconnects. This causes any\n // pending reader.read() to reject, breaking the pump loop. Critical\n // for SSE and other infinite streams — without this, disconnected\n // clients leak readers.\n let clientDisconnected = false;\n const onClose = () => {\n clientDisconnected = true;\n reader.cancel('Client disconnected').catch(() => {});\n };\n res.on('close', onClose);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n } catch (err) {\n // reader.cancel() from the close handler causes read() to reject.\n // This is expected on client disconnect — not an error.\n if (!clientDisconnected) {\n throw err;\n }\n } finally {\n res.off('close', onClose);\n reader.releaseLock();\n if (!res.writableEnded) {\n res.end();\n }\n }\n } else {\n res.end();\n }\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<void> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,SAAgB,yBAAiC;AAC/C,QAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BT,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,IAAI,EAAE,EAAE;EAC5D;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,WAAW;EACT,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,gBAAgB;EACd,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,cAAc;EACZ,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,mBAAmB;EACjB,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EAQnB,oBAAoB;EACpB,aAAa;EACd;CACD,OAAO;EACL,aAAa;EACb,WAAW;EACX,mBAAmB;EAGnB,oBAAoB;EACpB,aAAa;EACd;CACF;;;;;;;;;;;;;;;;;AAsDD,SAAgB,MAAM,UAA+B,EAAE,EAAyB;CAC9E,MAAM,SAAS,QAAQ,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itro.js","names":[],"sources":["../../src/adapters/compress-module.ts","../../src/adapters/nitro.ts"],"sourcesContent":["// Generated compression module template for self-hosted deployments.\n//\n// This file generates a standalone ESM module (_compress.mjs) that is\n// written to the build output during adapter buildOutput(). It's imported\n// by the Nitro entry and preview server at runtime.\n//\n// Uses CompressionStream (Web API) for gzip. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal and\n// node:zlib buffers output internally, breaking streaming.\n// Cloudflare Workers don't need this — the edge auto-compresses.\n//\n// See design/25-production-deployments.md.\n\n/**\n * Generate a standalone ESM module that exports compressResponse().\n *\n * Written to `_compress.mjs` during buildOutput. Imported by the Nitro entry\n * and preview server.\n *\n * @internal Exported for testing.\n */\nexport function generateCompressModule(): string {\n return `// Generated by @timber-js/app — response compression for self-hosted deployments.\n// Do not edit — this file is regenerated on each build.\n// Uses node:zlib createGzip() (C++ native) on Node.js, falls back to\n// CompressionStream (Web API) on other runtimes. Brotli is left to CDNs/reverse\n// proxies — at streaming quality levels its ratio advantage is marginal.\nimport { Readable } from 'node:stream';\nimport { createGzip, constants } from 'node:zlib';\n\nconst COMPRESSIBLE_TYPES = new Set([\n 'text/html', 'text/css', 'text/plain', 'text/xml', 'text/javascript',\n 'text/x-component', 'application/json', 'application/javascript',\n 'application/xml', 'application/xhtml+xml', 'application/rss+xml',\n 'application/atom+xml', 'image/svg+xml',\n]);\n\nconst NO_COMPRESS_STATUSES = new Set([204, 304]);\n\nfunction negotiateEncoding(acceptEncoding) {\n if (!acceptEncoding) return null;\n // Parse tokens with quality values. Per RFC 9110 §12.5.3, q=0 means\n // \"not acceptable\" — the client explicitly rejects that encoding.\n // Brotli (br) is intentionally not handled at the application level.\n const parts = acceptEncoding.split(',');\n for (const part of parts) {\n const [token, ...params] = part.split(';');\n const name = token.trim().toLowerCase();\n if (name !== 'gzip') continue;\n let qValue = 1;\n for (const param of params) {\n const trimmed = param.trim().toLowerCase();\n if (trimmed.startsWith('q=')) {\n qValue = parseFloat(trimmed.slice(2));\n if (Number.isNaN(qValue)) qValue = 1;\n break;\n }\n }\n if (qValue > 0) return 'gzip';\n }\n return null;\n}\n\nfunction shouldCompress(response) {\n if (!response.body) return false;\n if (NO_COMPRESS_STATUSES.has(response.status)) return false;\n if (response.headers.has('Content-Encoding')) return false;\n const contentType = response.headers.get('Content-Type');\n if (!contentType) return false;\n const mimeType = contentType.split(';')[0].trim().toLowerCase();\n if (mimeType === 'text/event-stream') return false;\n return COMPRESSIBLE_TYPES.has(mimeType);\n}\n\nfunction compressWithGzip(body) {\n // Use node:zlib (C++ native) for gzip compression. The Web Streams\n // CompressionStream works but every chunk crosses the JS/Promise boundary.\n // node:zlib.createGzip() compresses entirely in C++ with zero per-chunk\n // Promise overhead.\n //\n // Convert: Web ReadableStream → Node Readable → pipe through gzip →\n // Node Readable → Readable.toWeb() → Web ReadableStream\n try {\n const nodeReadable = Readable.fromWeb(body);\n // Z_SYNC_FLUSH ensures each chunk is flushed immediately so the browser\n // receives the HTML shell before Suspense boundaries resolve. Without it,\n // gzip buffers internally and breaks streaming.\n const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });\n const compressed = nodeReadable.pipe(gzip);\n return Readable.toWeb(compressed);\n } catch {\n // Fallback: CompressionStream (CF Workers, or if node:stream unavailable)\n return body.pipeThrough(new CompressionStream('gzip'));\n }\n}\n\nexport function compressResponse(request, response) {\n if (!shouldCompress(response)) return response;\n const acceptEncoding = request.headers.get('Accept-Encoding') || '';\n const encoding = negotiateEncoding(acceptEncoding);\n if (!encoding) return response;\n const compressedBody = compressWithGzip(response.body);\n const headers = new Headers(response.headers);\n headers.set('Content-Encoding', encoding);\n headers.delete('Content-Length');\n const existingVary = headers.get('Vary');\n if (existingVary) {\n if (!existingVary.toLowerCase().includes('accept-encoding')) {\n headers.set('Vary', existingVary + ', Accept-Encoding');\n }\n } else {\n headers.set('Vary', 'Accept-Encoding');\n }\n return new Response(compressedBody, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n`;\n}\n","// Nitro adapter — multi-platform deployment\n//\n// Covers everything except Cloudflare Workers: Node.js, Bun, Vercel,\n// Netlify, AWS Lambda, Deno Deploy, Azure Functions. Nitro handles\n// compression, graceful shutdown, static file serving, and platform quirks.\n// See design/11-platform.md and design/25-production-deployments.md.\n\nimport { writeFile, readFile } from 'node:fs/promises';\nimport { execFile } from 'node:child_process';\nimport { join, relative } from 'node:path';\nimport type { TimberPlatformAdapter, TimberConfig } from './types';\nimport { generateCompressModule } from './compress-module.js';\nimport { IMMUTABLE_CACHE } from './shared.js';\nimport { runSharedBuildSteps } from './build-output-helper.js';\n\n// ─── Presets ─────────────────────────────────────────────────────────────────\n\n/**\n * Supported Nitro deployment presets.\n *\n * Each preset maps to a Nitro deployment target. The adapter generates\n * the appropriate configuration and entry point for the selected platform.\n */\nexport type NitroPreset =\n | 'vercel'\n | 'vercel-edge'\n | 'netlify'\n | 'netlify-edge'\n | 'aws-lambda'\n | 'deno-deploy'\n | 'azure-functions'\n | 'node-server'\n | 'bun';\n\n/** Preset-specific Nitro configuration. */\ninterface PresetConfig {\n /** Nitro preset name passed to the Nitro build. */\n nitroPreset: string;\n /** Output directory name within the build dir. */\n outputDir: string;\n /** Whether the runtime supports waitUntil. */\n supportsWaitUntil: boolean;\n /** Whether the runtime supports application-level 103 Early Hints. */\n supportsEarlyHints: boolean;\n /** Value for TIMBER_RUNTIME env var. See design/25-production-deployments.md. */\n runtimeName: string;\n /** Additional nitro.config fields for this preset. */\n extraConfig?: Record<string, unknown>;\n}\n\nconst PRESET_CONFIGS: Record<NitroPreset, PresetConfig> = {\n 'vercel': {\n nitroPreset: 'vercel',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel',\n extraConfig: { vercel: { functions: { maxDuration: 30 } } },\n },\n 'vercel-edge': {\n nitroPreset: 'vercel-edge',\n outputDir: '.vercel/output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'vercel-edge',\n },\n 'netlify': {\n nitroPreset: 'netlify',\n outputDir: '.netlify/functions-internal',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'netlify',\n },\n 'netlify-edge': {\n nitroPreset: 'netlify-edge',\n outputDir: '.netlify/edge-functions',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'netlify-edge',\n },\n 'aws-lambda': {\n nitroPreset: 'aws-lambda',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'aws-lambda',\n },\n 'deno-deploy': {\n nitroPreset: 'deno-deploy',\n outputDir: '.output',\n supportsWaitUntil: true,\n supportsEarlyHints: false,\n runtimeName: 'deno-deploy',\n },\n 'azure-functions': {\n nitroPreset: 'azure-functions',\n outputDir: '.output',\n supportsWaitUntil: false,\n supportsEarlyHints: false,\n runtimeName: 'azure-functions',\n },\n 'node-server': {\n nitroPreset: 'node-server',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled by default: most node-server deployments sit behind a\n // reverse proxy (nginx, caddy, traefik) that doesn't support 103\n // Early Hints over HTTP/1.1. Sending 103 causes nginx to intermittently\n // treat the response as an error and retry after proxy_connect_timeout\n // (~5s stalls on ~23% of requests). Link headers on the 200 response\n // are the safe fallback — Cloudflare and other CDNs convert them to\n // 103 automatically at the edge (over HTTP/2+ to the browser).\n supportsEarlyHints: false,\n runtimeName: 'node-server',\n },\n 'bun': {\n nitroPreset: 'bun',\n outputDir: '.output',\n supportsWaitUntil: true,\n // Disabled for same reason as node-server — reverse proxies choke on 103.\n // Link headers on the 200 response are converted to 103 by CDNs.\n supportsEarlyHints: false,\n runtimeName: 'bun',\n },\n};\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Options for the Nitro adapter. */\nexport interface NitroAdapterOptions {\n /**\n * Deployment preset. Determines the target platform.\n * @default 'node-server'\n */\n preset?: NitroPreset;\n\n /**\n * Enable application-level gzip compression for HTML and RSC responses.\n *\n * When `true` (default), the origin compresses responses using the Web\n * `CompressionStream` API. This is useful for self-hosted deployments\n * where no reverse proxy or CDN handles compression.\n *\n * Set to `false` when deploying behind a reverse proxy (nginx, caddy)\n * or CDN (Cloudflare, Fastly, Vercel) that compresses at the edge.\n * Disabling origin compression saves CPU on the Node.js event loop —\n * compressing 1MB+ streaming HTML responses takes 10-15ms of main\n * thread time per request, directly reducing throughput under load.\n *\n * @default true\n */\n compress?: boolean;\n\n /**\n * Additional Nitro configuration to merge into the generated config.\n * Overrides default values for the selected preset.\n */\n nitroConfig?: Record<string, unknown>;\n}\n\n// ─── Adapter ─────────────────────────────────────────────────────────────────\n\n/**\n * Create a Nitro-based adapter for multi-platform deployment.\n *\n * Nitro abstracts deployment targets — the same timber.js app can deploy\n * to Vercel, Netlify, AWS, Deno Deploy, or Azure by changing the preset.\n *\n * @example\n * ```ts\n * import { nitro } from '@timber-js/app/adapters/nitro'\n *\n * export default {\n * output: 'server',\n * adapter: nitro({ preset: 'vercel' }),\n * }\n * ```\n */\nexport function nitro(options: NitroAdapterOptions = {}): TimberPlatformAdapter {\n const preset = options.preset ?? 'node-server';\n const compress = options.compress ?? true;\n const presetConfig = PRESET_CONFIGS[preset];\n const pendingPromises: Promise<unknown>[] = [];\n\n return {\n name: `nitro-${preset}`,\n\n async buildOutput(config: TimberConfig, buildDir: string) {\n const outDir = join(buildDir, 'nitro');\n\n // Steps 1–5: shared across all adapters (mkdir, copy client/rsc/ssr,\n // write _headers, write manifest-init).\n await runSharedBuildSteps({\n config,\n buildDir,\n outDir,\n publicDirName: 'public',\n });\n\n // Write the compression helper module for runtime use.\n // See design/25-production-deployments.md — self-hosted deployments\n // need application-level compression (Cloudflare handles it at the edge).\n await writeFile(join(outDir, '_compress.mjs'), generateCompressModule());\n\n // Prepend the manifest assignment directly into the RSC entry so\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set before any module reads it.\n // This must be top-level code, not an import, because rollup tree-shakes\n // side-effect-only globalThis assignments from imported modules.\n if (config.manifestInit) {\n const rscEntry = join(outDir, 'rsc', 'index.js');\n const rscContent = await readFile(rscEntry, 'utf-8');\n await writeFile(rscEntry, `${config.manifestInit}\\n${rscContent}`);\n }\n\n // Generate the Nitro entry point (imports from ./rsc/ within nitro dir)\n const entry = generateNitroEntry(buildDir, outDir, preset, compress);\n await writeFile(join(outDir, 'entry.ts'), entry);\n\n // Run the Nitro build to produce a production-ready server bundle.\n // The output goes to dist/nitro/.output/server/index.mjs (for node-server preset).\n // Config is passed programmatically — no nitro.config.ts file needed.\n await runNitroBuild(outDir, preset, options.nitroConfig);\n },\n\n // Only presets that produce a locally-runnable server get preview().\n // Serverless presets (vercel, netlify, aws-lambda, etc.) have no\n // local runtime — Vite's built-in preview is the fallback.\n preview: LOCALLY_PREVIEWABLE.has(preset)\n ? async (_config: TimberConfig, buildDir: string) => {\n // Generate a standalone preview server that uses Node's built-in\n // HTTP server. The Nitro entry.ts can't be run directly because\n // it imports h3 (a Nitro dependency not available at runtime).\n const previewScript = generatePreviewScript(buildDir, preset);\n const scriptPath = join(buildDir, 'nitro', '_preview-server.mjs');\n await writeFile(scriptPath, previewScript);\n\n const command = preset === 'bun' ? 'bun' : 'node';\n await spawnNitroPreview(command, [scriptPath], join(buildDir, 'nitro'));\n }\n : undefined,\n\n waitUntil: presetConfig.supportsWaitUntil\n ? (promise: Promise<unknown>) => {\n const tracked = promise.catch((err) => {\n console.error('[timber] waitUntil promise rejected:', err);\n });\n pendingPromises.push(tracked);\n }\n : undefined,\n };\n}\n\n// ─── Entry Generation ────────────────────────────────────────────────────────\n\n/** @internal Exported for testing. */\nexport function generateNitroEntry(\n buildDir: string,\n outDir: string,\n preset: NitroPreset,\n compress = true,\n hasManifestInit = false\n): string {\n // The RSC entry is the main request handler — it exports the fetch handler as default.\n // rsc/ is copied into the nitro dir so the import is local.\n // The manifest init is prepended to rsc/index.js before the nitro build,\n // so globalThis.__TIMBER_BUILD_MANIFEST__ is set before any code reads it.\n const serverEntryRelative = './rsc/index.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n const earlyHints = PRESET_CONFIGS[preset].supportsEarlyHints;\n const supportsWaitUntil = PRESET_CONFIGS[preset].supportsWaitUntil;\n\n // On node-server and bun, wrap the handler with ALS so the pipeline\n // can send 103 Early Hints via res.writeEarlyHints(). Other presets\n // either don't support 103 or handle it at the CDN level.\n //\n // For presets that support waitUntil, bridge h3's event.waitUntil()\n // to timber's waitUntil() primitive via the ALS bridge.\n // See design/11-platform.md §\"waitUntil()\".\n let handlerCall: string;\n if (earlyHints && supportsWaitUntil) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const callHandler = () => handler(webRequest)\n let wrappedHandler = earlyHintsSender\n ? () => runWithEarlyHintsSender(earlyHintsSender, callHandler)\n : callHandler\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, wrappedHandler)\n : await wrappedHandler()`;\n } else if (earlyHints) {\n handlerCall = ` const nodeRes = event.node?.res\n const earlyHintsSender = (typeof nodeRes?.writeEarlyHints === 'function')\n ? (links) => { try { nodeRes.writeEarlyHints({ link: links }) } catch {} }\n : undefined\n\n const webResponse = earlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest)`;\n } else if (supportsWaitUntil) {\n handlerCall = ` const waitUntilFn = (typeof event.waitUntil === 'function')\n ? (p) => event.waitUntil(p)\n : undefined\n\n const webResponse = waitUntilFn\n ? await runWithWaitUntil(waitUntilFn, () => handler(webRequest))\n : await handler(webRequest)`;\n } else {\n handlerCall = ` const webResponse = await handler(webRequest)`;\n }\n\n // Build manifest init must be imported before the handler so that\n // globalThis.__TIMBER_BUILD_MANIFEST__ is set when the virtual module evaluates.\n // ESM guarantees imports are evaluated in order.\n const manifestImport = hasManifestInit ? \"import './_timber-manifest-init.js'\\n\" : '';\n\n // Import runWithWaitUntil only when the preset supports it.\n const waitUntilImport = supportsWaitUntil ? ', runWithWaitUntil' : '';\n\n const compressImport = compress ? \"import { compressResponse } from './_compress.mjs'\\n\" : '';\n const compressCall = compress ? 'compressResponse(webRequest, webResponse)' : 'webResponse';\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\n${manifestImport}import handler, { runWithEarlyHintsSender${waitUntilImport} } from '${serverEntryRelative}'\n${compressImport}\n// Set TIMBER_RUNTIME for instrumentation.ts conditional SDK initialization.\n// See design/25-production-deployments.md §\"TIMBER_RUNTIME\".\nprocess.env.TIMBER_RUNTIME = '${runtimeName}'\n\n// Nitro's index.mjs wraps this import with defineLazyEventHandler, which\n// already handles the event handler protocol. We export a plain async\n// function — no defineEventHandler wrapper needed.\n// Nitro bundles h3 into its internal _libs/ directory but doesn't make\n// it available as a bare specifier in the output's node_modules.\nexport default async function timberHandler(event) {\n // h3 v2: event.req is the Web Request\n const webRequest = event.req\n${handlerCall}\n return ${compressCall}\n}\n`;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroConfig(\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): string {\n const presetConfig = PRESET_CONFIGS[preset];\n\n const config: Record<string, unknown> = {\n preset: presetConfig.nitroPreset,\n entry: './entry.ts',\n output: { dir: presetConfig.outputDir },\n // Static asset cache headers — hashed assets are immutable, others get 1h.\n // See design/25-production-deployments.md §\"CDN / Edge Cache\"\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n };\n\n const configJson = JSON.stringify(config, null, 2);\n\n return `// Generated by @timber-js/app/adapters/nitro\n// Do not edit — this file is regenerated on each build.\n\nimport { defineNitroConfig } from 'nitro/config'\n\nexport default defineNitroConfig(${configJson})\n`;\n}\n\n// ─── Preview ─────────────────────────────────────────────────────────────────\n\n/** Presets that produce a locally-runnable server entry. */\nconst LOCALLY_PREVIEWABLE = new Set<NitroPreset>(['node-server', 'bun']);\n\n/**\n * Generate a standalone preview server script that uses Node's built-in\n * HTTP server. This bypasses Nitro entirely — the Nitro entry.ts imports\n * h3 which isn't available outside a Nitro build. For local preview we\n * just need to serve static files and route requests to the RSC handler.\n *\n * @internal Exported for testing.\n */\nexport function generatePreviewScript(buildDir: string, preset: NitroPreset): string {\n const rscEntryRelative = relative(join(buildDir, 'nitro'), join(buildDir, 'rsc', 'index.js'));\n const rscEntry = rscEntryRelative.startsWith('.') ? rscEntryRelative : './' + rscEntryRelative;\n const publicDir = './public';\n const manifestInitPath = './_timber-manifest-init.js';\n const runtimeName = PRESET_CONFIGS[preset].runtimeName;\n\n return `// Generated by @timber-js/app — standalone preview server.\n// Uses Node's built-in HTTP server to serve static assets and route\n// dynamic requests through the RSC handler. No Nitro/h3 dependency.\n\nimport { createServer } from 'node:http';\nimport { readFile, stat } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { existsSync } from 'node:fs';\n\n// Set runtime before importing the handler.\nprocess.env.TIMBER_RUNTIME = '${runtimeName}';\n\n// Load the build manifest if it exists.\nconst __dirname = fileURLToPath(new URL('.', import.meta.url));\nconst manifestPath = join(__dirname, '${manifestInitPath}');\nif (existsSync(manifestPath)) {\n await import('${manifestInitPath}');\n}\n\n// Import the RSC handler (default export is the fetch-like handler).\nconst { default: handler, runWithEarlyHintsSender } = await import('${rscEntry}');\n\n// Import compression helper for self-hosted response compression.\nconst { compressResponse } = await import('./_compress.mjs');\n\nconst MIME_TYPES = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.otf': 'font/otf',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.webm': 'video/webm',\n '.mp4': 'video/mp4',\n '.txt': 'text/plain',\n '.xml': 'application/xml',\n '.wasm': 'application/wasm',\n};\n\nconst publicDir = join(__dirname, '${publicDir}');\n\n// Port resolution (TIM-842):\n// - Default to 3000\n// - If PORT env var is set, honor it strictly (fail loudly on conflict)\n// - Otherwise auto-bump from 3000 until a free port is found\n// Mirrors the dev server behavior so timber dev/preview/production all\n// behave the same way around port selection.\nconst envPort = process.env.PORT ? parseInt(process.env.PORT, 10) : null;\nconst portIsExplicit = envPort != null && Number.isFinite(envPort) && envPort > 0;\nconst startPort = portIsExplicit ? envPort : 3000;\nconst host = process.env.HOST || process.env.HOSTNAME || 'localhost';\n\n// Set after listenWithBump() resolves so request handlers can build\n// absolute URLs from the actual bound port (which may differ from\n// startPort after an auto-bump).\nlet boundPort = startPort;\n\nconst server = createServer(async (req, res) => {\n const url = new URL(req.url || '/', \\`http://\\${host}:\\${boundPort}\\`);\n\n // Try serving static files from the public directory first.\n const filePath = join(publicDir, url.pathname);\n // Prevent path traversal.\n if (filePath.startsWith(publicDir)) {\n try {\n const fileStat = await stat(filePath);\n if (fileStat.isFile()) {\n const ext = extname(filePath);\n const contentType = MIME_TYPES[ext] || 'application/octet-stream';\n const body = await readFile(filePath);\n // Hashed assets get immutable cache, others get short cache.\n const cacheControl = url.pathname.startsWith('/assets/')\n ? 'public, max-age=31536000, immutable'\n : 'public, max-age=3600, must-revalidate';\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': body.length,\n 'Cache-Control': cacheControl,\n });\n res.end(body);\n return;\n }\n } catch {\n // File not found — fall through to the RSC handler.\n }\n }\n\n // Convert Node request to Web Request.\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value) {\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n }\n\n let body = undefined;\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n body = await new Promise((resolve) => {\n const chunks = [];\n req.on('data', (chunk) => chunks.push(chunk));\n req.on('end', () => resolve(Buffer.concat(chunks)));\n });\n }\n\n const webRequest = new Request(url.href, {\n method: req.method,\n headers,\n body,\n duplex: body ? 'half' : undefined,\n });\n\n try {\n // Support 103 Early Hints when available.\n const earlyHintsSender = (typeof res.writeEarlyHints === 'function')\n ? (links) => { try { res.writeEarlyHints({ link: links }); } catch {} }\n : undefined;\n\n const rawResponse = earlyHintsSender && runWithEarlyHintsSender\n ? await runWithEarlyHintsSender(earlyHintsSender, () => handler(webRequest))\n : await handler(webRequest);\n\n // Compress the response for self-hosted deployments.\n const webResponse = compressResponse(webRequest, rawResponse);\n\n // Write the response back to the Node response.\n //\n // Set-Cookie needs special handling: Headers.entries() joins multiple\n // Set-Cookie values with \", \" into a single entry, but each cookie must\n // be its own header per RFC 6265 §4.1. Object.fromEntries() would then\n // collapse them into one malformed Set-Cookie header that browsers reject\n // (or only honor partially). Use getSetCookie() to preserve individual\n // values, and pass them as an array — Node's writeHead accepts\n // Record<string, string | string[]> and emits one header per array entry.\n //\n // Without this, EVERY cookie set by the framework on Node—/Nitro deployments\n // is silently dropped: defineCookie().setCookie() in actions, middleware\n // cookie writes, the framework's own session cookies, all of it. See\n // LOCAL-741.\n const responseHeaders: Record<string, string | string[]> = {};\n webResponse.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n responseHeaders[key] = value;\n }\n });\n const setCookies = webResponse.headers.getSetCookie();\n if (setCookies.length > 0) {\n responseHeaders['set-cookie'] = setCookies;\n }\n res.writeHead(webResponse.status, responseHeaders);\n\n if (webResponse.body) {\n const reader = webResponse.body.getReader();\n\n // Cancel the reader when the client disconnects. This causes any\n // pending reader.read() to reject, breaking the pump loop. Critical\n // for SSE and other infinite streams — without this, disconnected\n // clients leak readers.\n let clientDisconnected = false;\n const onClose = () => {\n clientDisconnected = true;\n reader.cancel('Client disconnected').catch(() => {});\n };\n res.on('close', onClose);\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n res.write(value);\n }\n } catch (err) {\n // reader.cancel() from the close handler causes read() to reject.\n // This is expected on client disconnect — not an error.\n if (!clientDisconnected) {\n throw err;\n }\n } finally {\n res.off('close', onClose);\n reader.releaseLock();\n if (!res.writableEnded) {\n res.end();\n }\n }\n } else {\n res.end();\n }\n } catch (err) {\n console.error('[timber preview] Request error:', err);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/plain' });\n }\n res.end('Internal Server Error');\n }\n});\n\nfunction listenWithBump(port, attempt = 0) {\n return new Promise((resolveListen, rejectListen) => {\n const onError = (err) => {\n server.removeListener('listening', onListening);\n if (err && err.code === 'EADDRINUSE' && !portIsExplicit && attempt < 100) {\n if (attempt === 0) {\n console.log(\\` [timber] Port \\${port} in use, trying \\${port + 1}...\\`);\n }\n listenWithBump(port + 1, attempt + 1).then(resolveListen, rejectListen);\n return;\n }\n rejectListen(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n resolveListen(port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port, host);\n });\n}\n\ntry {\n boundPort = await listenWithBump(startPort);\n if (boundPort !== startPort) {\n console.log();\n console.log(\\` [timber] Port \\${startPort} in use, using \\${boundPort}\\`);\n }\n console.log();\n console.log(' ⚡ timber preview server running at:');\n console.log();\n console.log(\\` ➜ http://\\${host}:\\${boundPort}\\`);\n console.log();\n} catch (err) {\n if (err && err.code === 'EADDRINUSE') {\n console.error(\\`[timber] Port \\${startPort} is already in use. \\` +\n 'Set PORT to a free port, or unset PORT to auto-pick.');\n } else {\n console.error('[timber] Failed to start preview server:', err);\n }\n process.exit(1);\n}\n`;\n}\n\n/** Command descriptor for Nitro preview — testable without spawning. */\nexport interface NitroPreviewCommand {\n command: string;\n args: string[];\n cwd: string;\n}\n\n/** @internal Exported for testing. */\nexport function generateNitroPreviewCommand(\n buildDir: string,\n preset: NitroPreset\n): NitroPreviewCommand | null {\n if (!LOCALLY_PREVIEWABLE.has(preset)) return null;\n\n const nitroDir = join(buildDir, 'nitro');\n const entryPath = join(nitroDir, 'entry.ts');\n\n const command = preset === 'bun' ? 'bun' : 'node';\n return {\n command,\n args: [entryPath],\n cwd: nitroDir,\n };\n}\n\n/**\n * Run the Nitro production build using the programmatic API.\n * Uses dynamic import so nitro is only loaded at build time.\n * Externalizes the timber RSC/SSR output — those files are pre-built\n * by timber and have internal references that nitro's bundler can't follow.\n */\nasync function runNitroBuild(\n nitroDir: string,\n preset: NitroPreset,\n userConfig?: Record<string, unknown>\n): Promise<void> {\n const presetConfig = PRESET_CONFIGS[preset];\n const {\n createNitro,\n build: nitroBuild,\n prepare,\n copyPublicAssets,\n } = await import('nitro/builder');\n\n const nitro = await createNitro({\n rootDir: nitroDir,\n preset: presetConfig.nitroPreset,\n // Use renderer.entry so Nitro wraps our handler with its server runtime\n // (HTTP server, static file serving, graceful shutdown, etc.).\n // Using `entry` directly would bypass the Nitro server runtime.\n renderer: { handler: join(nitroDir, 'entry.ts') },\n output: { dir: join(nitroDir, presetConfig.outputDir) },\n routeRules: {\n '/assets/**': { headers: { 'Cache-Control': IMMUTABLE_CACHE } },\n },\n // Don't bundle the timber RSC/SSR build output — it has its own\n // internal file references that nitro's bundler can't follow.\n // Mark them as external so rollup leaves the imports as-is.\n rollupConfig: {\n external: [/\\.\\.\\/rsc\\//],\n },\n ...presetConfig.extraConfig,\n ...userConfig,\n });\n\n await prepare(nitro);\n await copyPublicAssets(nitro);\n await nitroBuild(nitro);\n await nitro.close();\n}\n\n/** Spawn a Nitro preview process and pipe stdio. */\nfunction spawnNitroPreview(command: string, args: string[], cwd: string): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const child = execFile(command, args, { cwd }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n child.stdout?.pipe(process.stdout);\n child.stderr?.pipe(process.stderr);\n });\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/**\n * Get the preset configuration for a given preset name.\n * @internal Exported for testing.\n */\nexport function getPresetConfig(preset: NitroPreset): PresetConfig {\n return PRESET_CONFIGS[preset];\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,SAAgB,yBAAiC;CAC/C,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC4BT,IAAM,iBAAoD;CACxD,UAAU;EACR,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,aAAa,EAAE,QAAQ,EAAE,WAAW,EAAE,aAAa,IAAI,EAAE,EAAE;EAC5D;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,WAAW;EACT,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,gBAAgB;EACd,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,cAAc;EACZ,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,mBAAmB;EACjB,aAAa;EACb,WAAW;EACX,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACd;CACD,eAAe;EACb,aAAa;EACb,WAAW;EACX,mBAAmB;EAQnB,oBAAoB;EACpB,aAAa;EACd;CACD,OAAO;EACL,aAAa;EACb,WAAW;EACX,mBAAmB;EAGnB,oBAAoB;EACpB,aAAa;EACd;CACF;;;;;;;;;;;;;;;;;AAsDD,SAAgB,MAAM,UAA+B,EAAE,EAAyB;CAC9E,MAAM,SAAS,QAAQ,UAAU;CACjC,MAAM,WAAW,QAAQ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names":[],"sources":["../../src/cache/sizeof.ts","../../src/cache/redis-handler.ts","../../src/cache/stable-stringify.ts","../../src/cache/singleflight.ts","../../src/cache/fast-hash.ts","../../src/cache/timber-cache.ts","../../src/cache/cache-api.ts","../../src/cache/index.ts"],"sourcesContent":["/**\n * Lightweight byte-size estimation for cache entries.\n *\n * Estimates the in-memory byte cost of a JavaScript value using\n * JSON.stringify().length * 2 (UTF-16 char width). This is a rough\n * approximation — it doesn't account for V8 object overhead, Map\n * metadata, or non-serializable values — but it's fast and good\n * enough for cache budget enforcement.\n *\n * Values that fail JSON serialization (circular references, BigInt,\n * etc.) return 0, allowing the entry to be cached without counting\n * toward the byte budget. This is a conservative choice: it's better\n * to cache and undercount than to reject the entry.\n */\n\n/**\n * Estimate the byte size of a value.\n *\n * Uses `JSON.stringify(value).length * 2` to approximate UTF-16\n * in-memory size. Returns 0 if the value is not serializable.\n */\nexport function estimateByteSize(value: unknown): number {\n try {\n const json = JSON.stringify(value);\n if (json === undefined) return 0;\n // Each JS string character is 2 bytes (UTF-16)\n return json.length * 2;\n } catch (e) {\n // Circular reference or non-serializable value\n console.debug('[timber] sizeof estimation failed:', e instanceof Error ? e.message : e);\n return 0;\n }\n}\n","import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client interface — compatible with ioredis, node-redis, and\n * Cloudflare Workers Redis bindings. We depend on the interface, not the\n * implementation, so users bring their own Redis client.\n */\nexport interface RedisClient {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ...args: unknown[]): Promise<unknown>;\n del(key: string | string[]): Promise<number>;\n sadd(key: string, ...members: string[]): Promise<number>;\n smembers(key: string): Promise<string[]>;\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 — any client implementing the RedisClient\n * interface works (ioredis, node-redis, @upstash/redis, etc.).\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(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void> {\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n const payload = JSON.stringify({ value, expiresAt });\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 await this.client.set(ck, payload, 'EX', redisTtlSeconds);\n\n // Track key membership in each tag set\n for (const tag of opts.tags) {\n await this.client.sadd(this.tagKey(tag), key);\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\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 if (keys.length > 0) {\n const cacheKeys = keys.map((k) => this.cacheKey(k));\n await this.client.del(cacheKeys);\n }\n\n // Clean up the tag set itself\n await this.client.del(tk);\n }\n }\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 */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).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 pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n return '{' + pairs.join(',') + '}';\n}\n","/**\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: () => Promise<T>): Promise<T>;\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: () => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\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 promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new SingleflightTimeoutError(key, timeoutMs)),\n timeoutMs\n );\n // Wrap in try/catch so a synchronous throw from fn()\n // (e.g. argument validation) still clears the timer.\n // Without this, the timer leaks until expiry.\n try {\n fn().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();\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 };\n}\n","/**\n * Fast non-cryptographic hash for cache keys.\n *\n * FNV-1a 64-bit produces a well-distributed hash with a collision\n * probability of ~1 in 5 billion at 77k keys (birthday paradox).\n * Not suitable for security, but ideal for cache key generation\n * where we need speed over crypto strength.\n *\n * Uses BigInt for 64-bit arithmetic — supported in all modern runtimes\n * including Cloudflare Workers. No node:crypto dependency.\n *\n * See TIM-370.\n */\n\n// FNV-1a constants for 64-bit hash\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\n/**\n * Compute a 64-bit FNV-1a hash of a string, returned as a 16-char hex string.\n *\n * 64 bits gives ~5 billion keys before a 50% collision probability\n * (birthday paradox), making accidental collisions effectively impossible\n * for cache key use cases.\n */\nexport function fnv1aHash(input: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * FNV_PRIME) & MASK_64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n","import type { CacheHandler, CacheOptions } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { addSpanEventSync } from '../server/tracing.js';\nimport { logSwrRefetchFailed } from '../server/logger.js';\nimport { fnv1aHash } from './fast-hash.js';\n\nconst defaultSingleflight = createSingleflight();\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// Counter for generating unique function IDs when no explicit key is provided.\nlet fnIdCounter = 0;\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - SHA-256 default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - No ALS dependency\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 handler: CacheHandler\n): Fn {\n const fnId = `timber-cache:${fnIdCounter++}`;\n const sf = opts.timeoutMs\n ? createSingleflight({ timeoutMs: opts.timeoutMs })\n : defaultSingleflight;\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 key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId, args);\n\n const cacheStart = performance.now();\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span).\n // Fire-and-forget — no microtask overhead on the cache hot path.\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n 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 sf.do(`swr:${key}`, async () => {\n try {\n const fresh = await fn(...args);\n const tags = resolveTags(opts, args);\n await handler.set(key, fresh, { ttl: opts.ttl, tags });\n } catch (err) {\n // Failed refetch — stale entry continues to be served.\n logSwrRefetchFailed({ cacheKey: key, error: err });\n }\n }).catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight\n const result = await sf.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n\n // Record cache miss as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result as Awaited<ReturnType<Fn>>;\n }) as unknown as Fn;\n}\n\n/**\n * Invalidate cache entries by tag or key.\n */\ncreateCache.invalidate = async function invalidate(\n handler: CacheHandler,\n opts: { key?: string; tag?: string }\n): Promise<void> {\n await handler.invalidate(opts);\n};\n","import type { CacheOptions } from './index';\nimport { createCache } from './timber-cache';\nimport { getCacheHandler } from './handler-store';\n\n/**\n * Public caching API: `cache(fn, opts)`.\n *\n * Wraps an async function with cross-request caching. Uses the configured\n * cache handler (defaults to MemoryCacheHandler, overridable via timber.config.ts).\n *\n * ```ts\n * import { cache } from '@timber-js/app/cache';\n *\n * const getUser = cache(\n * async (id: string) => db.users.findUnique({ where: { id } }),\n * { ttl: 60, tags: (id) => [`user:${id}`] }\n * );\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function cache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>\n): Fn {\n return createCache(fn, opts, getCacheHandler());\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 */\ncache.invalidate = async function invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n await getCacheHandler().invalidate(opts);\n};\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.js';\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\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 maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\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 }\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(key: string, value: unknown, opts: { ttl: number; tags: string[] }) {\n const byteSize = estimateByteSize(value);\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 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 }\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 }\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. */\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 }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { cache } from './cache-api';\nexport { setCacheHandler, getCacheHandler } from './handler-store';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof';\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAiB,OAAwB;AACvD,KAAI;EACF,MAAM,OAAO,KAAK,UAAU,MAAM;AAClC,MAAI,SAAS,KAAA,EAAW,QAAO;AAE/B,SAAO,KAAK,SAAS;UACd,GAAG;AAEV,UAAQ,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,EAAE;AACvF,SAAO;;;;;ACfX,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;AAYnB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;AAC3D,OAAK,SAAS;AACd,OAAK,SAAS,MAAM,UAAU;;CAGhC,SAAiB,KAAqB;AACpC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,OAAe,KAAqB;AAClC,SAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,MAAM,IAAI,KAAiE;EACzE,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,IAAI,CAAC;AACrD,MAAI,QAAQ,KAAM,QAAO;EAEzB,MAAM,QAAQ,KAAK,MAAM,IAAI;EAC7B,MAAM,QAAQ,KAAK,KAAK,GAAG,MAAM;AACjC,SAAO;GAAE,OAAO,MAAM;GAAO;GAAO;;CAGtC,MAAM,IAAI,KAAa,OAAgB,MAAsD;EAC3F,MAAM,KAAK,KAAK,SAAS,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AIxB,SAAO,KAAK,MAAM,QAAQ,KAAK,WAC7B,MAAK,aAAa;AAIpB,MAAI,KAAK,aAAa,KAAA,GAAW;AAC/B,UAAO,KAAK,eAAe,WAAW,KAAK,YAAY,KAAK,MAAM,OAAO,EACvE,MAAK,aAAa;AAGpB,OAAI,KAAK,eAAe,WAAW,KAAK,SACtC;;AAIJ,OAAK,MAAM,IAAI,KAAK;GAClB;GACA,WAAW,KAAK,KAAK,GAAG,KAAK,MAAM;GACnC,MAAM,KAAK;GACX;GACD,CAAC;AACF,OAAK,gBAAgB;;CAGvB,MAAM,WAAW,MAAsC;AACrD,MAAI,KAAK,KAAK;GACZ,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,IAAI;AACtC,OAAI,OAAO;AACT,SAAK,gBAAgB,MAAM;AAC3B,SAAK,MAAM,OAAO,KAAK,IAAI;;;AAG/B,MAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,MAC9B,KAAI,MAAM,KAAK,SAAS,KAAK,IAAI,EAAE;AACjC,SAAK,gBAAgB,MAAM;AAC3B,SAAK,MAAM,OAAO,IAAI;;;;;CAO9B,IAAI,OAAe;AACjB,SAAO,KAAK,MAAM;;;CAIpB,IAAI,QAAgB;AAClB,SAAO,KAAK;;;CAId,cAA4B;EAC1B,MAAM,SAAS,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC;AACxC,MAAI,WAAW,KAAA,GAAW;GACxB,MAAM,QAAQ,KAAK,MAAM,IAAI,OAAO;AACpC,QAAK,gBAAgB,MAAM;AAC3B,QAAK,MAAM,OAAO,OAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cache/sizeof.ts","../../src/cache/redis-handler.ts","../../src/cache/stable-stringify.ts","../../src/cache/singleflight.ts","../../src/cache/fast-hash.ts","../../src/cache/timber-cache.ts","../../src/cache/cache-api.ts","../../src/cache/index.ts"],"sourcesContent":["/**\n * Lightweight byte-size estimation for cache entries.\n *\n * Estimates the in-memory byte cost of a JavaScript value using\n * JSON.stringify().length * 2 (UTF-16 char width). This is a rough\n * approximation — it doesn't account for V8 object overhead, Map\n * metadata, or non-serializable values — but it's fast and good\n * enough for cache budget enforcement.\n *\n * Values that fail JSON serialization (circular references, BigInt,\n * etc.) return 0, allowing the entry to be cached without counting\n * toward the byte budget. This is a conservative choice: it's better\n * to cache and undercount than to reject the entry.\n */\n\n/**\n * Estimate the byte size of a value.\n *\n * Uses `JSON.stringify(value).length * 2` to approximate UTF-16\n * in-memory size. Returns 0 if the value is not serializable.\n */\nexport function estimateByteSize(value: unknown): number {\n try {\n const json = JSON.stringify(value);\n if (json === undefined) return 0;\n // Each JS string character is 2 bytes (UTF-16)\n return json.length * 2;\n } catch (e) {\n // Circular reference or non-serializable value\n console.debug('[timber] sizeof estimation failed:', e instanceof Error ? e.message : e);\n return 0;\n }\n}\n","import type { CacheHandler } from './index';\n\n/**\n * Minimal Redis client interface — compatible with ioredis, node-redis, and\n * Cloudflare Workers Redis bindings. We depend on the interface, not the\n * implementation, so users bring their own Redis client.\n */\nexport interface RedisClient {\n get(key: string): Promise<string | null>;\n set(key: string, value: string, ...args: unknown[]): Promise<unknown>;\n del(key: string | string[]): Promise<number>;\n sadd(key: string, ...members: string[]): Promise<number>;\n smembers(key: string): Promise<string[]>;\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 — any client implementing the RedisClient\n * interface works (ioredis, node-redis, @upstash/redis, etc.).\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(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void> {\n const ck = this.cacheKey(key);\n const expiresAt = Date.now() + opts.ttl * 1000;\n const payload = JSON.stringify({ value, expiresAt });\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 await this.client.set(ck, payload, 'EX', redisTtlSeconds);\n\n // Track key membership in each tag set\n for (const tag of opts.tags) {\n await this.client.sadd(this.tagKey(tag), key);\n }\n }\n\n async invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n if (opts.key) {\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 if (keys.length > 0) {\n const cacheKeys = keys.map((k) => this.cacheKey(k));\n await this.client.del(cacheKeys);\n }\n\n // Clean up the tag set itself\n await this.client.del(tk);\n }\n }\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 */\nexport function stableStringify(value: unknown): string {\n if (value === null || value === undefined) return JSON.stringify(value);\n if (typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) {\n return '[' + value.map((item) => stableStringify(item)).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 pairs.push(JSON.stringify(key) + ':' + stableStringify(obj[key]));\n }\n return '{' + pairs.join(',') + '}';\n}\n","/**\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: () => Promise<T>): Promise<T>;\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: () => Promise<T>): Promise<T> {\n const existing = inflight.get(key);\n if (existing) return existing as Promise<T>;\n\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 promise = new Promise<T>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new SingleflightTimeoutError(key, timeoutMs)),\n timeoutMs\n );\n // Wrap in try/catch so a synchronous throw from fn()\n // (e.g. argument validation) still clears the timer.\n // Without this, the timer leaks until expiry.\n try {\n fn().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();\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 };\n}\n","/**\n * Fast non-cryptographic hash for cache keys.\n *\n * FNV-1a 64-bit produces a well-distributed hash with a collision\n * probability of ~1 in 5 billion at 77k keys (birthday paradox).\n * Not suitable for security, but ideal for cache key generation\n * where we need speed over crypto strength.\n *\n * Uses BigInt for 64-bit arithmetic — supported in all modern runtimes\n * including Cloudflare Workers. No node:crypto dependency.\n *\n * See TIM-370.\n */\n\n// FNV-1a constants for 64-bit hash\nconst FNV_OFFSET_BASIS = 0xcbf29ce484222325n;\nconst FNV_PRIME = 0x100000001b3n;\nconst MASK_64 = 0xffffffffffffffffn;\n\n/**\n * Compute a 64-bit FNV-1a hash of a string, returned as a 16-char hex string.\n *\n * 64 bits gives ~5 billion keys before a 50% collision probability\n * (birthday paradox), making accidental collisions effectively impossible\n * for cache key use cases.\n */\nexport function fnv1aHash(input: string): string {\n let hash = FNV_OFFSET_BASIS;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * FNV_PRIME) & MASK_64;\n }\n return hash.toString(16).padStart(16, '0');\n}\n","import type { CacheHandler, CacheOptions } from './index';\nimport { stableStringify } from './stable-stringify';\nimport { createSingleflight } from './singleflight';\nimport { addSpanEventSync } from '../server/tracing.js';\nimport { logSwrRefetchFailed } from '../server/logger.js';\nimport { fnv1aHash } from './fast-hash.js';\n\nconst defaultSingleflight = createSingleflight();\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// Counter for generating unique function IDs when no explicit key is provided.\nlet fnIdCounter = 0;\n\n/**\n * Creates a cached wrapper around an async function.\n *\n * - SHA-256 default keys with normalized JSON args\n * - Singleflight: concurrent misses → single execution\n * - SWR: serve stale immediately, background refetch\n * - Tags as string[] or function of args\n * - No ALS dependency\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 handler: CacheHandler\n): Fn {\n const fnId = `timber-cache:${fnIdCounter++}`;\n const sf = opts.timeoutMs\n ? createSingleflight({ timeoutMs: opts.timeoutMs })\n : defaultSingleflight;\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 key = opts.key ? opts.key(...args) : defaultKeyGenerator(fnId, args);\n\n const cacheStart = performance.now();\n const cached = await handler.get(key);\n\n if (cached && !cached.stale) {\n // Record as OTEL span event on enclosing span (not a child span).\n // Fire-and-forget — no microtask overhead on the cache hot path.\n addSpanEventSync('timber.cache.hit', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n 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 sf.do(`swr:${key}`, async () => {\n try {\n const fresh = await fn(...args);\n const tags = resolveTags(opts, args);\n await handler.set(key, fresh, { ttl: opts.ttl, tags });\n } catch (err) {\n // Failed refetch — stale entry continues to be served.\n logSwrRefetchFailed({ cacheKey: key, error: err });\n }\n }).catch(() => {\n // Singleflight promise rejection handled — stale continues.\n });\n return cached.value as Awaited<ReturnType<Fn>>;\n }\n\n // Cache miss (or stale without SWR) — execute with singleflight\n const result = await sf.do(key, () => fn(...args));\n const tags = resolveTags(opts, args);\n await handler.set(key, result, { ttl: opts.ttl, tags });\n\n // Record cache miss as OTEL span event (fire-and-forget).\n addSpanEventSync('timber.cache.miss', {\n key,\n duration_ms: Math.round(performance.now() - cacheStart),\n });\n\n return result as Awaited<ReturnType<Fn>>;\n }) as unknown as Fn;\n}\n\n/**\n * Invalidate cache entries by tag or key.\n */\ncreateCache.invalidate = async function invalidate(\n handler: CacheHandler,\n opts: { key?: string; tag?: string }\n): Promise<void> {\n await handler.invalidate(opts);\n};\n","import type { CacheOptions } from './index';\nimport { createCache } from './timber-cache';\nimport { getCacheHandler } from './handler-store';\n\n/**\n * Public caching API: `cache(fn, opts)`.\n *\n * Wraps an async function with cross-request caching. Uses the configured\n * cache handler (defaults to MemoryCacheHandler, overridable via timber.config.ts).\n *\n * ```ts\n * import { cache } from '@timber-js/app/cache';\n *\n * const getUser = cache(\n * async (id: string) => db.users.findUnique({ where: { id } }),\n * { ttl: 60, tags: (id) => [`user:${id}`] }\n * );\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function cache<Fn extends (...args: any[]) => Promise<any>>(\n fn: Fn,\n opts: CacheOptions<Fn>\n): Fn {\n return createCache(fn, opts, getCacheHandler());\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 */\ncache.invalidate = async function invalidate(opts: { key?: string; tag?: string }): Promise<void> {\n await getCacheHandler().invalidate(opts);\n};\n","// @timber-js/app/cache — Caching primitives\n\nimport { estimateByteSize } from './sizeof.js';\n\nexport interface CacheHandler {\n get(key: string): Promise<{ value: unknown; stale: boolean } | null>;\n set(key: string, value: unknown, opts: { ttl: number; tags: string[] }): Promise<void>;\n invalidate(opts: { key?: string; tag?: string }): Promise<void>;\n}\n\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 maxEntries: number;\n private maxBytes: number | undefined;\n private maxEntryBytes: number | undefined;\n private currentBytes = 0;\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 }\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(key: string, value: unknown, opts: { ttl: number; tags: string[] }) {\n const byteSize = estimateByteSize(value);\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 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 }\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 }\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. */\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 }\n }\n}\n\nexport { RedisCacheHandler } from './redis-handler';\nexport type { RedisClient } from './redis-handler';\nexport { cache } from './cache-api';\nexport { setCacheHandler, getCacheHandler } from './handler-store';\n// NOTE: registerCachedFunction (runtime for 'use cache' directive) removed.\n// Future feature pending design doc. See design/06-caching.md.\nexport { estimateByteSize } from './sizeof';\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,iBAAiB,OAAwB;CACvD,IAAI;EACF,MAAM,OAAO,KAAK,UAAU,MAAM;EAClC,IAAI,SAAS,KAAA,GAAW,OAAO;EAE/B,OAAO,KAAK,SAAS;UACd,GAAG;EAEV,QAAQ,MAAM,sCAAsC,aAAa,QAAQ,EAAE,UAAU,EAAE;EACvF,OAAO;;;;;ACfX,IAAM,aAAa;AACnB,IAAM,aAAa;;;;;;;;;;;AAYnB,IAAa,oBAAb,MAAuD;CACrD;CACA;CAEA,YAAY,QAAqB,MAA4B;EAC3D,KAAK,SAAS;EACd,KAAK,SAAS,MAAM,UAAU;;CAGhC,SAAiB,KAAqB;EACpC,OAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,OAAe,KAAqB;EAClC,OAAO,GAAG,KAAK,SAAS,aAAa;;CAGvC,MAAM,IAAI,KAAiE;EACzE,MAAM,MAAM,MAAM,KAAK,OAAO,IAAI,KAAK,SAAS,IAAI,CAAC;EACrD,IAAI,QAAQ,MAAM,OAAO;EAEzB,MAAM,QAAQ,KAAK,MAAM,IAAI;EAC7B,MAAM,QAAQ,KAAK,KAAK,GAAG,MAAM;EACjC,OAAO;GAAE,OAAO,MAAM;GAAO;GAAO;;CAGtC,MAAM,IAAI,KAAa,OAAgB,MAAsD;EAC3F,MAAM,KAAK,KAAK,SAAS,IAAI;EAC7B,MAAM,YAAY,KAAK,KAAK,GAAG,KAAK,MAAM;EAC1C,MAAM,UAAU,KAAK,UAAU;GAAE;GAAO;GAAW,CAAC;EAMpD,MAAM,kBAAkB,KAAK,IAAI,KAAK,MAAM,IAAI,IAAI,IAAI;EACxD,MAAM,KAAK,OAAO,IAAI,IAAI,SAAS,MAAM,g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AK,MAAM,IAAI,KAAK;GAClB;GACA,WAAW,KAAK,KAAK,GAAG,KAAK,MAAM;GACnC,MAAM,KAAK;GACX;GACD,CAAC;EACF,KAAK,gBAAgB;;CAGvB,MAAM,WAAW,MAAsC;EACrD,IAAI,KAAK,KAAK;GACZ,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,IAAI;GACtC,IAAI,OAAO;IACT,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,KAAK,IAAI;;;EAG/B,IAAI,KAAK;QACF,MAAM,CAAC,KAAK,UAAU,KAAK,OAC9B,IAAI,MAAM,KAAK,SAAS,KAAK,IAAI,EAAE;IACjC,KAAK,gBAAgB,MAAM;IAC3B,KAAK,MAAM,OAAO,IAAI;;;;;CAO9B,IAAI,OAAe;EACjB,OAAO,KAAK,MAAM;;;CAIpB,IAAI,QAAgB;EAClB,OAAO,KAAK;;;CAId,cAA4B;EAC1B,MAAM,SAAS,KAAK,MAAM,MAAM,CAAC,MAAM,CAAC;EACxC,IAAI,WAAW,KAAA,GAAW;GACxB,MAAM,QAAQ,KAAK,MAAM,IAAI,OAAO;GACpC,KAAK,gBAAgB,MAAM;GAC3B,KAAK,MAAM,OAAO,OAAO"}
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check', 'schema'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n}\n\nexport interface CommandOptions {\n config?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>]\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check|schema> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--config' || args[i] === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n }\n }\n\n return { command: command as Command, config };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/** @internal Dependency injection for testing. */\nexport interface ViteDeps {\n createServer?: typeof import('vite').createServer;\n createBuilder?: typeof import('vite').createBuilder;\n preview?: typeof import('vite').preview;\n}\n\n/**\n * Start the Vite dev server.\n *\n * The timber plugin binds the port immediately with a holding page\n * (in rootSync's config hook) so browsers see a \"starting...\" page\n * instead of ERR_CONNECTION_REFUSED during initialization.\n *\n * See design/21-dev-server.md, TIM-665.\n */\nexport async function runDev(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createServer = _deps?.createServer ?? (await import('vite')).createServer;\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createBuilder = _deps?.createBuilder ?? (await import('vite')).createBuilder;\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Determine whether to use the adapter's preview or Vite's built-in preview.\n * Exported for testing — the actual runPreview function uses this internally.\n */\nexport function resolvePreviewStrategy(\n adapter: import('./adapters/types').TimberPlatformAdapter | undefined\n): 'adapter' | 'vite' {\n if (adapter && typeof adapter.preview === 'function') {\n return 'adapter';\n }\n return 'vite';\n}\n\n/**\n * Load timber.config.ts from the project root.\n * Returns the config object with adapter, output, etc.\n * Returns null if no config file is found.\n */\nasync function loadTimberConfig(root: string): Promise<{\n adapter?: import('./adapters/types').TimberPlatformAdapter;\n output?: string;\n buildDir?: string;\n} | null> {\n const { existsSync } = await import('node:fs');\n const { join } = await import('node:path');\n const { pathToFileURL } = await import('node:url');\n\n const configNames = ['timber.config.ts', 'timber.config.js', 'timber.config.mjs'];\n\n for (const name of configNames) {\n const configPath = join(root, name);\n if (existsSync(configPath)) {\n // Use Vite's built-in config loading to handle TypeScript\n const mod = await import(pathToFileURL(configPath).href);\n return mod.default ?? mod;\n }\n }\n return null;\n}\n\n/**\n * Serve the production build for local testing.\n * If the adapter provides a preview() method, it takes priority.\n * Otherwise falls back to Vite's built-in preview server.\n */\nexport async function runPreview(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const { join, resolve } = await import('node:path');\n\n // Try to load timber config for adapter-specific preview\n const root = process.cwd();\n const config = await loadTimberConfig(root).catch(() => null);\n const adapter = config?.adapter as import('./adapters/types').TimberPlatformAdapter | undefined;\n\n if (resolvePreviewStrategy(adapter) === 'adapter') {\n // Resolve build directory: timber config > default .timber/dist\n const buildDir = config?.buildDir\n ? resolve(root, config.buildDir)\n : join(root, '.timber', 'dist');\n const timberConfig = { output: (config?.output ?? 'server') as 'server' | 'static' };\n await adapter!.preview!(timberConfig, buildDir);\n return;\n }\n\n // Fallback: Vite's built-in preview server\n const preview = _deps?.preview ?? (await import('vite')).preview;\n const server = await preview({\n configFile: options.config,\n });\n server.printUrls();\n}\n\n/**\n * Validate types and routes without producing build output.\n * Runs tsgo --noEmit for type checking.\n */\nexport async function runCheck(options: CommandOptions): Promise<void> {\n const { execFile } = await import('node:child_process');\n\n await new Promise<void>((resolve, reject) => {\n const configArgs = options.config ? ['--project', options.config] : [];\n execFile('tsgo', ['--noEmit', ...configArgs], (err, stdout, stderr) => {\n if (stdout) process.stdout.write(stdout);\n if (stderr) process.stderr.write(stderr);\n if (err) {\n reject(new Error(`Type check failed with exit code ${err.code}`));\n } else {\n resolve();\n }\n });\n });\n}\n\n// ─── Schema Subcommand ───────────────────────────────────────────────────────\n\n/**\n * `timber schema sync` — scan filesystem for dynamic segments, diff against\n * app/schema.ts, and append missing entries with type-appropriate codec defaults.\n *\n * See design/41-global-params.md §Auto-Scaffolding\n */\nexport async function runSchema(args: string[]): Promise<void> {\n const subcommand = args[0];\n\n if (subcommand !== 'sync') {\n throw new Error(\n `Unknown schema subcommand: ${subcommand ?? '(none)'}. Usage: timber schema sync`\n );\n }\n\n const { runSchemaSync, defaultCodecForSegment } = await import('./cli-schema-sync.js');\n const result = runSchemaSync(process.cwd());\n\n if (result.filesystemSegments.length === 0) {\n console.log('[timber] No dynamic segments found in app/.');\n return;\n }\n\n if (result.created) {\n console.log(`[timber] Created app/schema.ts with ${result.addedSegments.length} segment(s):`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n return;\n }\n\n if (result.addedSegments.length === 0 && result.removedSegments.length === 0) {\n console.log('[timber] Schema is up to date — all segments are registered.');\n return;\n }\n\n if (result.addedSegments.length > 0) {\n console.log(`[timber] Added ${result.addedSegments.length} segment(s) to app/schema.ts:`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n }\n\n if (result.removedSegments.length > 0) {\n console.log(\n `[timber] Removed ${result.removedSegments.length} stale segment(s) from app/schema.ts:`\n );\n for (const seg of result.removedSegments) {\n console.log(` - ${seg}`);\n }\n }\n}\n\n// ─── Main Entry Point ────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const parsed = parseArgs(process.argv.slice(2));\n const options: CommandOptions = { config: parsed.config };\n\n switch (parsed.command) {\n case 'dev':\n await runDev(options);\n break;\n case 'build':\n await runBuild(options);\n break;\n case 'preview':\n await runPreview(options);\n break;\n case 'check':\n await runCheck(options);\n break;\n case 'schema':\n await runSchema(process.argv.slice(3));\n break;\n }\n}\n\n// Run main when executed as a CLI (not imported in tests).\n// The bin shim (bin/timber.mjs) does `import '../dist/cli.js'`, so\n// process.argv[1] points to the shim, not this file. We check both:\n// direct execution AND being imported by the timber bin shim.\nconst isDirectExecution =\n typeof process !== 'undefined' &&\n process.argv[1] &&\n (import.meta.url.endsWith(process.argv[1]) ||\n process.argv[1].endsWith('bin/timber.mjs') ||\n process.argv[1].endsWith('bin/timber'));\n\nif (isDirectExecution) {\n main().catch((err) => {\n console.error(err.message);\n process.exit(1);\n });\n}\n"],"mappings":";;AAaA,IAAM,WAAW;CAAC;CAAO;CAAS;CAAW;CAAS;CAAS;;;;;AAgB/D,SAAgB,UAAU,MAA4B;AACpD,KAAI,KAAK,WAAW,EAClB,OAAM,IAAI,MACR,wFACD;CAGH,MAAM,UAAU,KAAK;AACrB,KAAI,CAAC,SAAS,SAAS,QAAmB,CACxC,OAAM,IAAI,MAAM,oBAAoB,QAAQ,wBAAwB,SAAS,KAAK,KAAK,GAAG;CAG5F,IAAI;AACJ,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,IAC/B,KAAI,KAAK,OAAO,cAAc,KAAK,OAAO,MAAM;AAC9C,WAAS,KAAK,EAAE;AAChB,MAAI,CAAC,OACH,OAAM,IAAI,MAAM,oCAAoC;;AAK1D,QAAO;EAAW;EAAoB;EAAQ;;;;;;;;;;;AAqBhD,eAAsB,OAAO,SAAyB,OAAiC;CAErF,MAAM,SAAS,OADM,OAAO,iBAAiB,MAAM,OAAO,SAAS,cACjC,EAChC,YAAY,QAAQ,QACrB,CAAC;AACF,OAAM,OAAO,QAAQ;AACrB,QAAO,WAAW;;;;;;;AAQpB,eAAsB,SAAS,SAAyB,OAAiC;AAKvF,QAHgB,OADM,OAAO,kBAAkB,MAAM,OAAO,SAAS,eACjC,EAClC,YAAY,QAAQ,QACrB,CAAC,EACY,UAAU;;;;;;AAO1B,SAAgB,uBACd,SACoB;AACpB,KAAI,WAAW,OAAO,QAAQ,YAAY,WAC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AAW,QAAQ;AACzB;EACF,KAAK;AACH,SAAM,SAAS,QAAQ;AACvB;EACF,KAAK;AACH,SAAM,UAAU,QAAQ,KAAK,MAAM,EAAE,CAAC;AACtC;;;AAeN,IANE,OAAO,YAAY,eACnB,QAAQ,KAAK,OACZ,OAAO,KAAK,IAAI,SAAS,QAAQ,KAAK,GAAG,IACxC,QAAQ,KAAK,GAAG,SAAS,iBAAiB,IAC1C,QAAQ,KAAK,GAAG,SAAS,aAAa,EAGxC,OAAM,CAAC,OAAO,QAAQ;AACpB,SAAQ,MAAM,IAAI,QAAQ;AAC1B,SAAQ,KAAK,EAAE;EACf"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// timber.js CLI\n//\n// Wraps Vite commands with timber-specific behavior.\n// See design/18-build-system.md §\"CLI\".\n//\n// Commands:\n// timber dev — Start Vite dev server with HMR\n// timber build — Run multi-environment build via createBuilder/buildApp\n// timber preview — Serve the production build\n// timber check — Validate types + routes without building\n\nconst COMMANDS = ['dev', 'build', 'preview', 'check', 'schema'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nexport interface ParsedArgs {\n command: Command;\n config: string | undefined;\n}\n\nexport interface CommandOptions {\n config?: string;\n}\n\n/**\n * Parse CLI arguments into a structured command + options.\n * Accepts: timber <command> [--config|-c <path>]\n */\nexport function parseArgs(args: string[]): ParsedArgs {\n if (args.length === 0) {\n throw new Error(\n 'No command provided. Usage: timber <dev|build|preview|check|schema> [--config <path>]'\n );\n }\n\n const command = args[0];\n if (!COMMANDS.includes(command as Command)) {\n throw new Error(`Unknown command: ${command}. Available commands: ${COMMANDS.join(', ')}`);\n }\n\n let config: string | undefined;\n for (let i = 1; i < args.length; i++) {\n if (args[i] === '--config' || args[i] === '-c') {\n config = args[++i];\n if (!config) {\n throw new Error('--config requires a path argument');\n }\n }\n }\n\n return { command: command as Command, config };\n}\n\n// ─── Command Implementations ─────────────────────────────────────────────────\n\n/** @internal Dependency injection for testing. */\nexport interface ViteDeps {\n createServer?: typeof import('vite').createServer;\n createBuilder?: typeof import('vite').createBuilder;\n preview?: typeof import('vite').preview;\n}\n\n/**\n * Start the Vite dev server.\n *\n * The timber plugin binds the port immediately with a holding page\n * (in rootSync's config hook) so browsers see a \"starting...\" page\n * instead of ERR_CONNECTION_REFUSED during initialization.\n *\n * See design/21-dev-server.md, TIM-665.\n */\nexport async function runDev(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createServer = _deps?.createServer ?? (await import('vite')).createServer;\n const server = await createServer({\n configFile: options.config,\n });\n await server.listen();\n server.printUrls();\n}\n\n/**\n * Run the production build using createBuilder + buildApp.\n * Direct build() calls do NOT trigger the RSC plugin's multi-environment\n * pipeline — createBuilder/buildApp is required.\n */\nexport async function runBuild(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const createBuilder = _deps?.createBuilder ?? (await import('vite')).createBuilder;\n const builder = await createBuilder({\n configFile: options.config,\n });\n await builder.buildApp();\n}\n\n/**\n * Determine whether to use the adapter's preview or Vite's built-in preview.\n * Exported for testing — the actual runPreview function uses this internally.\n */\nexport function resolvePreviewStrategy(\n adapter: import('./adapters/types').TimberPlatformAdapter | undefined\n): 'adapter' | 'vite' {\n if (adapter && typeof adapter.preview === 'function') {\n return 'adapter';\n }\n return 'vite';\n}\n\n/**\n * Load timber.config.ts from the project root.\n * Returns the config object with adapter, output, etc.\n * Returns null if no config file is found.\n */\nasync function loadTimberConfig(root: string): Promise<{\n adapter?: import('./adapters/types').TimberPlatformAdapter;\n output?: string;\n buildDir?: string;\n} | null> {\n const { existsSync } = await import('node:fs');\n const { join } = await import('node:path');\n const { pathToFileURL } = await import('node:url');\n\n const configNames = ['timber.config.ts', 'timber.config.js', 'timber.config.mjs'];\n\n for (const name of configNames) {\n const configPath = join(root, name);\n if (existsSync(configPath)) {\n // Use Vite's built-in config loading to handle TypeScript\n const mod = await import(pathToFileURL(configPath).href);\n return mod.default ?? mod;\n }\n }\n return null;\n}\n\n/**\n * Serve the production build for local testing.\n * If the adapter provides a preview() method, it takes priority.\n * Otherwise falls back to Vite's built-in preview server.\n */\nexport async function runPreview(options: CommandOptions, _deps?: ViteDeps): Promise<void> {\n const { join, resolve } = await import('node:path');\n\n // Try to load timber config for adapter-specific preview\n const root = process.cwd();\n const config = await loadTimberConfig(root).catch(() => null);\n const adapter = config?.adapter as import('./adapters/types').TimberPlatformAdapter | undefined;\n\n if (resolvePreviewStrategy(adapter) === 'adapter') {\n // Resolve build directory: timber config > default .timber/dist\n const buildDir = config?.buildDir\n ? resolve(root, config.buildDir)\n : join(root, '.timber', 'dist');\n const timberConfig = { output: (config?.output ?? 'server') as 'server' | 'static' };\n await adapter!.preview!(timberConfig, buildDir);\n return;\n }\n\n // Fallback: Vite's built-in preview server\n const preview = _deps?.preview ?? (await import('vite')).preview;\n const server = await preview({\n configFile: options.config,\n });\n server.printUrls();\n}\n\n/**\n * Validate types and routes without producing build output.\n * Runs tsgo --noEmit for type checking.\n */\nexport async function runCheck(options: CommandOptions): Promise<void> {\n const { execFile } = await import('node:child_process');\n\n await new Promise<void>((resolve, reject) => {\n const configArgs = options.config ? ['--project', options.config] : [];\n execFile('tsgo', ['--noEmit', ...configArgs], (err, stdout, stderr) => {\n if (stdout) process.stdout.write(stdout);\n if (stderr) process.stderr.write(stderr);\n if (err) {\n reject(new Error(`Type check failed with exit code ${err.code}`));\n } else {\n resolve();\n }\n });\n });\n}\n\n// ─── Schema Subcommand ───────────────────────────────────────────────────────\n\n/**\n * `timber schema sync` — scan filesystem for dynamic segments, diff against\n * app/schema.ts, and append missing entries with type-appropriate codec defaults.\n *\n * See design/41-global-params.md §Auto-Scaffolding\n */\nexport async function runSchema(args: string[]): Promise<void> {\n const subcommand = args[0];\n\n if (subcommand !== 'sync') {\n throw new Error(\n `Unknown schema subcommand: ${subcommand ?? '(none)'}. Usage: timber schema sync`\n );\n }\n\n const { runSchemaSync, defaultCodecForSegment } = await import('./cli-schema-sync.js');\n const result = runSchemaSync(process.cwd());\n\n if (result.filesystemSegments.length === 0) {\n console.log('[timber] No dynamic segments found in app/.');\n return;\n }\n\n if (result.created) {\n console.log(`[timber] Created app/schema.ts with ${result.addedSegments.length} segment(s):`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n return;\n }\n\n if (result.addedSegments.length === 0 && result.removedSegments.length === 0) {\n console.log('[timber] Schema is up to date — all segments are registered.');\n return;\n }\n\n if (result.addedSegments.length > 0) {\n console.log(`[timber] Added ${result.addedSegments.length} segment(s) to app/schema.ts:`);\n for (const seg of result.addedSegments) {\n console.log(` + ${seg}: ${defaultCodecForSegment(seg)}`);\n }\n }\n\n if (result.removedSegments.length > 0) {\n console.log(\n `[timber] Removed ${result.removedSegments.length} stale segment(s) from app/schema.ts:`\n );\n for (const seg of result.removedSegments) {\n console.log(` - ${seg}`);\n }\n }\n}\n\n// ─── Main Entry Point ────────────────────────────────────────────────────────\n\nasync function main(): Promise<void> {\n const parsed = parseArgs(process.argv.slice(2));\n const options: CommandOptions = { config: parsed.config };\n\n switch (parsed.command) {\n case 'dev':\n await runDev(options);\n break;\n case 'build':\n await runBuild(options);\n break;\n case 'preview':\n await runPreview(options);\n break;\n case 'check':\n await runCheck(options);\n break;\n case 'schema':\n await runSchema(process.argv.slice(3));\n break;\n }\n}\n\n// Run main when executed as a CLI (not imported in tests).\n// The bin shim (bin/timber.mjs) does `import '../dist/cli.js'`, so\n// process.argv[1] points to the shim, not this file. We check both:\n// direct execution AND being imported by the timber bin shim.\nconst isDirectExecution =\n typeof process !== 'undefined' &&\n process.argv[1] &&\n (import.meta.url.endsWith(process.argv[1]) ||\n process.argv[1].endsWith('bin/timber.mjs') ||\n process.argv[1].endsWith('bin/timber'));\n\nif (isDirectExecution) {\n main().catch((err) => {\n console.error(err.message);\n process.exit(1);\n });\n}\n"],"mappings":";;AAaA,IAAM,WAAW;CAAC;CAAO;CAAS;CAAW;CAAS;CAAS;;;;;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