@timber-js/app 0.2.0-alpha.226 → 0.2.0-alpha.228

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 (101) hide show
  1. package/dist/_chunks/{actions-B1xSIv32.js → actions-DprvPi7O.js} +3 -3
  2. package/dist/_chunks/{actions-B1xSIv32.js.map → actions-DprvPi7O.js.map} +1 -1
  3. package/dist/_chunks/{build-output-helper-B7wWGTfR.js → build-output-helper-5UsltK-S.js} +29 -2
  4. package/dist/_chunks/build-output-helper-5UsltK-S.js.map +1 -0
  5. package/dist/_chunks/{cache-api-DsSXA4Sp.js → cache-api-BjE-nNC0.js} +4 -4
  6. package/dist/_chunks/{cache-api-DsSXA4Sp.js.map → cache-api-BjE-nNC0.js.map} +1 -1
  7. package/dist/_chunks/chains-BS8fQYao.js +1 -0
  8. package/dist/_chunks/{chains-Dgm3PrMe.js → chains-DaDEXv0c.js} +2 -2
  9. package/dist/_chunks/{chains-Dgm3PrMe.js.map → chains-DaDEXv0c.js.map} +1 -1
  10. package/dist/_chunks/{classify--_kINHQV.js → classify-BuIifN5v.js} +2 -2
  11. package/dist/_chunks/{classify--_kINHQV.js.map → classify-BuIifN5v.js.map} +1 -1
  12. package/dist/_chunks/{cli-check-B33yhAPa.js → cli-check-B_fDvxhs.js} +3 -3
  13. package/dist/_chunks/{cli-check-B33yhAPa.js.map → cli-check-B_fDvxhs.js.map} +1 -1
  14. package/dist/_chunks/{cli-schema-sync-uq72EZmD.js → cli-schema-sync-CUIk0G2X.js} +1 -1
  15. package/dist/_chunks/{cli-schema-sync-DIPurq7X.js → cli-schema-sync-D9OLUUFv.js} +2 -2
  16. package/dist/_chunks/{cli-schema-sync-DIPurq7X.js.map → cli-schema-sync-D9OLUUFv.js.map} +1 -1
  17. package/dist/_chunks/{client-dep-entries-CP7AkMCM.js → client-dep-entries-COuyF8-c.js} +2 -2
  18. package/dist/_chunks/{client-dep-entries-CP7AkMCM.js.map → client-dep-entries-COuyF8-c.js.map} +1 -1
  19. package/dist/_chunks/{cloudflare-B75X6u4O.js → cloudflare-_2fhxQE8.js} +4 -20
  20. package/dist/_chunks/{cloudflare-B75X6u4O.js.map → cloudflare-_2fhxQE8.js.map} +1 -1
  21. package/dist/_chunks/{convention-lint-hZwz5wd4.js → convention-lint-BHY0d5AQ.js} +4 -13
  22. package/dist/_chunks/convention-lint-BHY0d5AQ.js.map +1 -0
  23. package/dist/_chunks/{dev-server-B7o4As0l.js → dev-server-BaM7q3pr.js} +2 -2
  24. package/dist/_chunks/{dev-server-B7o4As0l.js.map → dev-server-BaM7q3pr.js.map} +1 -1
  25. package/dist/_chunks/dev-server-NnGosJ06.js +1 -0
  26. package/dist/_chunks/{flight-source-node-0Tp6evlz.js → flight-source-node-CZJ9Drb7.js} +2 -2
  27. package/dist/_chunks/{flight-source-node-0Tp6evlz.js.map → flight-source-node-CZJ9Drb7.js.map} +1 -1
  28. package/dist/_chunks/{json-lossy-check-DVkLUlfC.js → json-lossy-check-BNwKrm2R.js} +2 -2
  29. package/dist/_chunks/{json-lossy-check-DVkLUlfC.js.map → json-lossy-check-BNwKrm2R.js.map} +1 -1
  30. package/dist/_chunks/{live-graph-BcVjQ1Te.js → live-graph-DiRVmRrC.js} +4 -4
  31. package/dist/_chunks/{live-graph-BcVjQ1Te.js.map → live-graph-DiRVmRrC.js.map} +1 -1
  32. package/dist/_chunks/{logger-CWk44DLp.js → logger-DRMij51J.js} +4 -4
  33. package/dist/_chunks/logger-DRMij51J.js.map +1 -0
  34. package/dist/_chunks/{node-response-B9aviPDa.js → node-response-C-dQn-0N.js} +2 -2
  35. package/dist/_chunks/{node-response-B9aviPDa.js.map → node-response-C-dQn-0N.js.map} +1 -1
  36. package/dist/_chunks/{poison-scan-DJYxZc_7.js → poison-scan-CqPGN0ru.js} +2 -2
  37. package/dist/_chunks/{poison-scan-DJYxZc_7.js.map → poison-scan-CqPGN0ru.js.map} +1 -1
  38. package/dist/_chunks/route-methods-Dk2kZc0n.js +36 -0
  39. package/dist/_chunks/route-methods-Dk2kZc0n.js.map +1 -0
  40. package/dist/_chunks/{scanner-CJC-ScJU.js → scanner-C__vsQ8d.js} +2 -2
  41. package/dist/_chunks/{scanner-CJC-ScJU.js.map → scanner-C__vsQ8d.js.map} +1 -1
  42. package/dist/_chunks/{sizeof-DG4W40lv.js → sizeof-DcEcQaSL.js} +2 -2
  43. package/dist/_chunks/{sizeof-DG4W40lv.js.map → sizeof-DcEcQaSL.js.map} +1 -1
  44. package/dist/_chunks/{walkers-DIE203ir.js → walkers-D6KY4jyS.js} +3 -3
  45. package/dist/_chunks/{walkers-DIE203ir.js.map → walkers-D6KY4jyS.js.map} +1 -1
  46. package/dist/adapters/cloudflare-dev.js +1 -1
  47. package/dist/adapters/cloudflare-kv-cache.js +2 -2
  48. package/dist/adapters/cloudflare.d.ts +0 -7
  49. package/dist/adapters/cloudflare.d.ts.map +1 -1
  50. package/dist/adapters/cloudflare.js +1 -1
  51. package/dist/adapters/nitro.d.ts.map +1 -1
  52. package/dist/adapters/nitro.js +6 -5
  53. package/dist/adapters/nitro.js.map +1 -1
  54. package/dist/adapters/shared.d.ts +18 -0
  55. package/dist/adapters/shared.d.ts.map +1 -1
  56. package/dist/analyze/crawl-entry.js +3 -3
  57. package/dist/analyze/graph-command.js +2 -2
  58. package/dist/cache/index.js +2 -2
  59. package/dist/cache/stores/memory.js +1 -1
  60. package/dist/cli.js +3 -3
  61. package/dist/index.js +7 -7
  62. package/dist/routing/convention-lint.d.ts.map +1 -1
  63. package/dist/routing/index.js +2 -2
  64. package/dist/rsc-runtime/rsc.d.ts +2 -2
  65. package/dist/rsc-runtime/rsc.d.ts.map +1 -1
  66. package/dist/rsc-runtime/server-reference-load-error.d.ts +14 -0
  67. package/dist/rsc-runtime/server-reference-load-error.d.ts.map +1 -0
  68. package/dist/rsc-runtime/server-references.d.ts +11 -0
  69. package/dist/rsc-runtime/server-references.d.ts.map +1 -1
  70. package/dist/server/action-handler.d.ts +7 -5
  71. package/dist/server/action-handler.d.ts.map +1 -1
  72. package/dist/server/csrf.d.ts +1 -1
  73. package/dist/server/csrf.d.ts.map +1 -1
  74. package/dist/server/index.js +2 -2
  75. package/dist/server/internal.d.ts +2 -1
  76. package/dist/server/internal.d.ts.map +1 -1
  77. package/dist/server/internal.js +22 -24
  78. package/dist/server/internal.js.map +1 -1
  79. package/dist/server/route-handler.d.ts +1 -2
  80. package/dist/server/route-handler.d.ts.map +1 -1
  81. package/dist/server/route-methods.d.ts +23 -0
  82. package/dist/server/route-methods.d.ts.map +1 -0
  83. package/package.json +2 -2
  84. package/src/adapters/cloudflare.ts +7 -19
  85. package/src/adapters/nitro.ts +12 -5
  86. package/src/adapters/shared.ts +31 -0
  87. package/src/routing/convention-lint.ts +1 -3
  88. package/src/rsc-runtime/rsc.ts +8 -7
  89. package/src/rsc-runtime/server-reference-load-error.ts +16 -0
  90. package/src/rsc-runtime/server-references.ts +63 -1
  91. package/src/server/action-handler.ts +36 -17
  92. package/src/server/csrf.ts +11 -3
  93. package/src/server/internal.ts +2 -1
  94. package/src/server/route-handler.ts +8 -19
  95. package/src/server/route-methods.ts +37 -0
  96. package/src/server/tracing.ts +3 -3
  97. package/dist/_chunks/build-output-helper-B7wWGTfR.js.map +0 -1
  98. package/dist/_chunks/chains-CwOr3Myj.js +0 -1
  99. package/dist/_chunks/convention-lint-hZwz5wd4.js.map +0 -1
  100. package/dist/_chunks/dev-server-hZzmbMvK.js +0 -1
  101. package/dist/_chunks/logger-CWk44DLp.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"node-response-B9aviPDa.js","names":[],"sources":["../../src/server/abort-scope.ts","../../src/server/render-utils.ts","../../src/server/stream-utils.ts","../../src/server/node-response.ts"],"sourcesContent":["/**\n * Abort listeners scoped to the work they guard.\n *\n * A request's signal outlives the render, stream, or timer that listens to\n * it, and a listener left on it keeps everything its closure holds reachable\n * from the request. In production that only delays collection until the\n * request is garbage. In dev it pins the request forever: React's dev Flight\n * server tracks every live promise in an async-hook Map whose debug chains\n * reach the request, so any promise reachable from the request is never\n * collected and never leaves that Map (TIM-1589).\n *\n * So server code never calls `signal.addEventListener('abort', …)` itself\n * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}\n * takes the end of the listener's scope as a required argument, which makes\n * a listener without a removal unwritable.\n */\n\n/**\n * Call `onAbort` if `signal` aborts before the scope `until` ends. If\n * `signal` has already aborted, `onAbort` runs now.\n *\n * `until` is the scope: a promise (the listener is removed when it fulfills\n * or rejects, a microtask later) or an `AbortSignal` (removed synchronously\n * when it aborts; use one when an abort later in the same tick must not\n * fire, as after a timeout's `cancel()`).\n */\nexport function onAbortUntil(\n signal: AbortSignal | undefined,\n onAbort: () => void,\n until: PromiseLike<unknown> | AbortSignal\n): void {\n if (!signal) return;\n if (signal.aborted) {\n onAbort();\n return;\n }\n let scope: AbortSignal;\n if (until instanceof AbortSignal) {\n scope = until;\n } else {\n const ended = new AbortController();\n const end = (): void => ended.abort();\n until.then(end, end);\n scope = ended.signal;\n }\n // addEventListener's own `signal` option removes the listener when the\n // scope aborts: the platform's one-step removal, no handle to keep.\n signal.addEventListener('abort', onAbort, { once: true, signal: scope });\n}\n","/**\n * Shared render-phase utilities — used by both the Node.js and Web\n * stream wrappers. Pure functions only; no stream-shape dependencies.\n *\n * Consolidated from duplicated copies in node-stream-transforms.ts,\n * ssr-render.ts, and rsc-entry/helpers.ts. See TIM-1071 item 1.\n */\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` in csp-nonce.ts and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n\n/**\n * The reason to abort a render with when its consumer releases it.\n *\n * The framework releases a Flight render it no longer needs — the renderer\n * once a deny or redirect is captured, a tee once either branch is done —\n * usually without a reason. React then reports the abort to the render's\n * `onError` as a plain `Error(\"The render was aborted by the server without a\n * reason.\")`, which reads as an application failure: a `metadata()` that\n * denies while the page is still fetching logged an unhandled render error\n * (TIM-1597). An `AbortError` is what {@link isAbortError} already treats as\n * not-an-error. A reason the caller did pass (a timeout, the tee's divergence\n * guard) is kept, so those still reach the log.\n */\nexport function releaseReason(reason: unknown): unknown {\n return reason ?? new DOMException('The render was released by its consumer.', 'AbortError');\n}\n\n/**\n * Check if an error is an abort error (connection closed by client).\n *\n * When the browser aborts a request (page refresh, navigation away),\n * the AbortSignal fires and React/streams throw an AbortError. This\n * is not an application error — suppress it from error boundaries and logs.\n *\n * A native `ReadableStream.tee()` cancels its source with an array of both\n * branches' reasons (Streams spec, ReadableStreamDefaultTee), so a Web\n * render released through a tee is aborted with `[reason1, reason2]`. That is\n * an abort when every entry is — a tee whose branches were both released\n * ({@link releaseReason}) — and an error when any entry is, such as the\n * divergence guard's.\n */\nexport function isAbortError(error: unknown): boolean {\n if (Array.isArray(error)) return error.length > 0 && error.every(isAbortError);\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n/**\n * Inline script that adds `<meta name=\"robots\" content=\"noindex\">` to the\n * document head. Injected when a render-phase error replaces the shell so\n * search engines don't index error pages.\n *\n * MUST be byte-identical across all stream wrappers (Node and Web) for a\n * given nonce to ensure consistent Content-Length headers — which is why\n * both wrappers call this one function rather than inlining the string.\n */\nexport function noindexScript(nonce?: string): string {\n return `<script${nonceAttr(nonce)}>document.head.appendChild(Object.assign(document.createElement(\"meta\"),{name:\"robots\",content:\"noindex\"}))</script>`;\n}\n","/**\n * Stream utilities for the RSC rendering pipeline.\n *\n * teeWithErrorPropagation — wraps native ReadableStream.tee() with:\n * 1. Cross-branch error propagation (error on one branch cancels the other)\n * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)\n *\n * This prevents two classes of bugs:\n * - Silent stalls when one tee branch errors and the other hangs indefinitely\n * - Unbounded memory growth when one consumer (SSR) is much slower than the other\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\"\n */\n\nimport { getLogger } from './logger.ts';\n\n/** Default maximum buffer divergence before cancellation (5MB). */\nexport const DEFAULT_MAX_BUFFER_BYTES = 5 * 1024 * 1024;\n\nexport interface TeeOptions {\n /**\n * Maximum byte divergence between the two branches before both are\n * cancelled. When one branch has consumed this many more bytes than\n * the other, the tee's internal buffer is at least this large.\n *\n * Default: 5MB.\n */\n maxBufferBytes?: number;\n}\n\n/**\n * Tee a ReadableStream with error propagation and buffer monitoring.\n *\n * Delegates to the native `stream.tee()` for the actual forking, then wraps\n * each branch in a ReadableStream that:\n * - Tracks bytes consumed per branch\n * - Cancels both branches if byte divergence exceeds `maxBufferBytes`\n * - Cancels the other branch if either branch is cancelled or errors\n *\n * The returned streams are drop-in replacements for the native tee branches.\n */\nexport function teeWithErrorPropagation(\n stream: ReadableStream<Uint8Array>,\n options?: TeeOptions\n): [ReadableStream<Uint8Array>, ReadableStream<Uint8Array>] {\n const maxBuffer = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n const [rawBranch1, rawBranch2] = stream.tee();\n\n // Shared state for cross-branch coordination\n let consumed1 = 0;\n let consumed2 = 0;\n let cancelled = false;\n\n // Readers and controllers are assigned when wrapBranch creates the wrapped\n // streams. We store them so cancelBoth can cancel raw tee branches AND\n // error the wrapped stream controllers for cross-branch propagation.\n let rawReader1: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rawReader2: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let controller1: ReadableStreamDefaultController<Uint8Array> | undefined;\n let controller2: ReadableStreamDefaultController<Uint8Array> | undefined;\n\n /**\n * Cancel both tee branches. `initiator` is the branch index (0 or 1)\n * that triggered the cancellation — its controller is already being\n * closed/errored by the pull/cancel that triggered this, so we skip it.\n * Pass -1 to cancel+error both (e.g., from the buffer divergence guard).\n *\n * Both raw readers are always canceled regardless of initiator, because\n * the tee source stream is only released when both branches are canceled.\n * ReadableStreamDefaultReader.cancel() is idempotent, so double-cancel\n * is safe.\n */\n function cancelBoth(reason: unknown, initiator: number = -1): void {\n if (cancelled) return;\n cancelled = true;\n // Cancel both raw readers — tee source requires both branches canceled.\n rawReader1?.cancel(reason).catch(() => {});\n rawReader2?.cancel(reason).catch(() => {});\n // Error wrapped controllers so consumers see the failure.\n // Skip the initiator's controller — it's already being closed/errored.\n if (initiator !== 0) {\n try {\n controller1?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n if (initiator !== 1) {\n try {\n controller2?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n }\n\n function wrapBranch(\n branchIndex: number,\n rawBranch: ReadableStream<Uint8Array>,\n assignReader: (r: ReadableStreamDefaultReader<Uint8Array>) => void,\n assignController: (c: ReadableStreamDefaultController<Uint8Array>) => void,\n addConsumed: (n: number) => void,\n getSelfConsumed: () => number,\n getOtherConsumed: () => number\n ): ReadableStream<Uint8Array> {\n const reader = rawBranch.getReader();\n assignReader(reader);\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n assignController(controller);\n },\n\n async pull(controller) {\n if (cancelled) {\n return;\n }\n\n try {\n const { done, value } = await reader.read();\n\n // Re-check after await — cancelBoth may have fired while we\n // were waiting on the raw reader.\n if (cancelled) return;\n\n if (done) {\n try {\n controller.close();\n } catch {\n /* controller already errored by cancelBoth */\n }\n return;\n }\n\n addConsumed(value.byteLength);\n\n // Check buffer divergence: the difference in consumed bytes\n // approximates the tee's internal buffer size.\n const divergence = getSelfConsumed() - getOtherConsumed();\n if (divergence > maxBuffer) {\n cancelBoth(teeBufferExceeded(maxBuffer, divergence));\n return;\n }\n\n controller.enqueue(value);\n } catch (err) {\n if (!cancelled) {\n // Source stream errored — propagate to both branches.\n // cancelBoth with initiator skips our own controller,\n // so we error it explicitly here.\n cancelBoth(err, branchIndex);\n try {\n controller.error(err);\n } catch {\n /* already closed/errored */\n }\n }\n }\n },\n\n cancel(reason) {\n // Consumer cancelled this branch — propagate to the other\n cancelBoth(reason, branchIndex);\n },\n });\n }\n\n const wrapped1 = wrapBranch(\n 0,\n rawBranch1,\n (r) => {\n rawReader1 = r;\n },\n (c) => {\n controller1 = c;\n },\n (n) => {\n consumed1 += n;\n },\n () => consumed1,\n () => consumed2\n );\n\n const wrapped2 = wrapBranch(\n 1,\n rawBranch2,\n (r) => {\n rawReader2 = r;\n },\n (c) => {\n controller2 = c;\n },\n (n) => {\n consumed2 += n;\n },\n () => consumed2,\n () => consumed1\n );\n\n return [wrapped1, wrapped2];\n}\n\n/**\n * Stream-lifecycle timing for one response body: firstChunk, lastChunk,\n * close, maxGap (largest inter-chunk gap), chunk count, and byte count,\n * logged once when the stream terminates (clean close OR\n * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`. The\n * Web body wrapper below and the Node body (`node-body-response.ts`) feed\n * the same recorder, so the two report identically.\n */\nexport interface StreamTimingRecorder {\n chunk(byteLength: number): void;\n end(cancelled: boolean): void;\n}\n\nexport function createStreamTimingRecorder(startTime: number): StreamTimingRecorder {\n let firstChunkMs = 0;\n let lastChunkMs = 0;\n let maxGapMs = 0;\n let prevChunkTime = 0;\n let chunks = 0;\n let bytes = 0;\n let ended = false;\n\n return {\n chunk(byteLength) {\n const now = performance.now();\n const relativeMs = Math.round(now - startTime);\n if (chunks === 0) {\n firstChunkMs = relativeMs;\n } else {\n const gap = Math.round(now - prevChunkTime);\n if (gap > maxGapMs) maxGapMs = gap;\n }\n prevChunkTime = now;\n lastChunkMs = relativeMs;\n chunks++;\n bytes += byteLength;\n },\n end(cancelled) {\n if (ended) return;\n ended = true;\n const closeMs = Math.round(performance.now() - startTime);\n getLogger().debug('stream-lifecycle', {\n firstChunkMs,\n lastChunkMs,\n closeMs,\n maxGapMs,\n chunks,\n bytes,\n ...(cancelled ? { cancelled: true } : {}),\n });\n },\n };\n}\n\n/**\n * Wrap a Web response body with stream-lifecycle timing instrumentation\n * ({@link createStreamTimingRecorder}).\n *\n * Uses a manual reader pump to guarantee logging on all termination\n * paths — TransformStream.flush() is not called on cancellation.\n */\nexport function wrapResponseWithStreamTiming(\n body: ReadableStream<Uint8Array>,\n startTime: number\n): ReadableStream<Uint8Array> {\n const timing = createStreamTimingRecorder(startTime);\n const reader = body.getReader();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n timing.end(false);\n controller.close();\n return;\n }\n timing.chunk(value.byteLength);\n controller.enqueue(value);\n } catch (err) {\n timing.end(false);\n controller.error(err);\n }\n },\n\n cancel(reason) {\n timing.end(true);\n reader.cancel(reason).catch(() => {});\n },\n });\n}\n\n/** Format bytes as human-readable string (e.g., \"5.00 MB\"). */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n}\n\n/**\n * The error both tee implementations (this Web one and the Node one in\n * `flight-source-node.ts`) cancel with when one branch lags the other by more\n * than `maxBuffer` bytes. Warns once, here, so the two cannot drift.\n */\nexport function teeBufferExceeded(maxBuffer: number, divergence: number): Error {\n const error = new Error(\n `RSC stream tee buffer exceeded ${formatBytes(maxBuffer)} ` +\n `(divergence: ${formatBytes(divergence)}). ` +\n `This usually means SSR is much slower than the inline stream consumer. ` +\n `Consider reducing RSC payload size or increasing the tee buffer limit.`\n );\n console.warn(`[timber] ${error.message}`);\n return error;\n}\n\n/**\n * A pull reader over any chunk stream: a Web reader, or the Flight reader in\n * `flight-source.ts`, which reads a Node or Web Flight source.\n */\nexport interface ChunkReader<T> {\n read(): Promise<ReadableStreamReadResult<T>>;\n cancel(reason?: unknown): void;\n}\n\n/**\n * Read a chunk stream to completion under one overall deadline. Every read\n * is raced against the time remaining, and the reader is cancelled on every\n * exit, so a stalled upstream never outlives the deadline. See\n * design/02-rendering-pipeline.md §\"Always Timeout-Guard Stream Reads\".\n *\n * @param label - Prefix for the timeout error message. Both ways the deadline\n * can pass (between reads, or while a read is pending) reject with the same\n * `${label} did not complete within ${timeoutMs}ms`.\n */\nexport async function drainWithDeadline<T>(\n reader: ChunkReader<T>,\n timeoutMs: number,\n label: string\n): Promise<T[]> {\n const chunks: T[] = [];\n const deadline = Date.now() + timeoutMs;\n const deadlineError = () => new Error(`${label} did not complete within ${timeoutMs}ms`);\n try {\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw deadlineError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(deadlineError()), remaining);\n });\n let result: Awaited<ReturnType<ChunkReader<T>['read']>>;\n try {\n result = await Promise.race([reader.read(), timeout]);\n } finally {\n clearTimeout(timer);\n }\n if (result.done) return chunks;\n chunks.push(result.value);\n }\n } finally {\n reader.cancel();\n }\n}\n\n/** Concatenate byte chunks into one array. */\nexport function concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Read a byte stream to completion under one overall deadline and return\n * the concatenated bytes ({@link drainWithDeadline}). The static generator's\n * body drain uses it; Flight renders use `collectFlightBytes`\n * (`flight-source.ts`), which reads either source kind the same way.\n */\nexport async function readAllBytesWithDeadline(\n stream: ReadableStream<Uint8Array>,\n timeoutMs: number,\n label: string\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks = await drainWithDeadline(\n { read: () => reader.read(), cancel: (reason) => void reader.cancel(reason).catch(() => {}) },\n timeoutMs,\n label\n );\n return concatBytes(chunks);\n}\n","/**\n * Responses with a Node body — the platform-neutral half.\n *\n * On Node, SSR's HTML and Flight payload bodies are Node `Readable`s. They\n * travel the pipeline as a `NodeBodyResponse` (`node-body-response.ts`, Node\n * only): a real `Response` whose body stays a Node stream until the adapter\n * pipes it to the socket, so a response is never converted Node → Web → Node\n * (LOCAL-1475). srvx (nitro, the dev server) and nitro-preview's sender take\n * the Node body through `_toNodeResponse()`. Any code that reads the body\n * through the Web API still works: the response then converts once.\n *\n * Pipeline code shared with Workers re-wraps, strips, or times a response\n * through the helpers here, which ask the response itself to do the Node\n * work, so this module never imports `node:stream`. A response is recognised\n * by a `Symbol.for` brand, not `instanceof`: the RSC and SSR environments\n * load separate copies of the class.\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport type { Duplex } from 'node:stream';\n\n/** The brand a Node-body response carries, keyed by a registry symbol. */\nexport const NODE_BODY = Symbol.for('timber.response.nodeBody');\n\n/**\n * What a Node-body response can do with its body, for code that cannot import\n * the class: platform-neutral modules, and the standalone `_compress.mjs`,\n * which reaches these through the same registry symbol. Each one takes the\n * body: the response it was called on no longer has one.\n */\nexport interface NodeBodyOps {\n /**\n * Whether the response still owns a body. False for a null-body status\n * (204, 205, 304, …) and once the body was taken. Being branded says\n * nothing about this — ask here instead of reading `.body`, which would\n * convert it.\n */\n readonly hasBody: boolean;\n /** The same body under a new status and headers. */\n rewrap(init: ResponseInit): Response;\n /** Release the body unread (HEAD, a discarded document), aborting its producer. */\n discard(): void;\n /** The same body, reporting stream timing when it ends (detailed Server-Timing). */\n timed(startTime: number): Response;\n /**\n * The body piped through `stream` (gzip), as a Node-body response under\n * `init`. An error or destroy on either end tears down both.\n */\n through(stream: Duplex, init: ResponseInit): Response;\n}\n\ninterface NodeBodyBranded {\n [NODE_BODY]: NodeBodyOps;\n}\n\nfunction isNodeBodyBranded(response: Response): response is Response & NodeBodyBranded {\n return NODE_BODY in response;\n}\n\n/** The Node-body operations of `response`, or `null` for a Web-body response. */\nexport function nodeBodyOps(response: Response): NodeBodyOps | null {\n return isNodeBodyBranded(response) ? response[NODE_BODY] : null;\n}\n\n/**\n * `response`'s body under a new status and headers. A Node body moves to the\n * new response without converting; a Web body is reused as is.\n */\nexport function withResponseInit(response: Response, init: ResponseInit): Response {\n return nodeBodyOps(response)?.rewrap(init) ?? new Response(response.body, init);\n}\n\n/**\n * Release a response's body unread. A live producer (an SSR render, a Flight\n * render) is behind it; dropping the reference without this leaks it for the\n * lifetime of the render (design/13-security.md A4).\n */\nexport function discardResponseBody(response: Response): void {\n const ops = nodeBodyOps(response);\n if (ops) {\n ops.discard();\n return;\n }\n // `cancel()` rejects if the stream is already errored and throws\n // synchronously if it is locked — neither is actionable, the body is being\n // discarded either way.\n try {\n response.body?.cancel().catch(() => {});\n } catch {\n /* stream already locked or disturbed */\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aACd,QACA,SACA,OACM;CACN,IAAI,CAAC,QAAQ;CACb,IAAI,OAAO,SAAS;EAClB,QAAQ;EACR;CACF;CACA,IAAI;CACJ,IAAI,iBAAiB,aACnB,QAAQ;MACH;EACL,MAAM,QAAQ,IAAI,gBAAgB;EAClC,MAAM,YAAkB,MAAM,MAAM;EACpC,MAAM,KAAK,KAAK,GAAG;EACnB,QAAQ,MAAM;CAChB;CAGA,OAAO,iBAAiB,SAAS,SAAS;EAAE,MAAM;EAAM,QAAQ;CAAM,CAAC;AACzE;;;;;;;;;;;;;;;ACfA,SAAgB,cAAc,QAA0B;CACtD,OAAO,UAAU,IAAI,aAAa,4CAA4C,YAAY;AAC5F;;;;;;;;;;;;;;;AAgBA,SAAgB,aAAa,OAAyB;CACpD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,MAAM,SAAS,KAAK,MAAM,MAAM,YAAY;CAC7E,IAAI,iBAAiB,gBAAgB,MAAM,SAAS,cAAc,OAAO;CACzE,IAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc,OAAO;CAClE,OAAO;AACT;;;;;;;;;;;;;;;;ACvCA,IAAa,2BAA2B;AAsMxC,SAAgB,2BAA2B,WAAyC;CAClF,IAAI,eAAe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S,kBAAkB,UAA4D;CACrF,OAAO,aAAa;AACtB;;AAGA,SAAgB,YAAY,UAAwC;CAClE,OAAO,kBAAkB,QAAQ,IAAI,SAAS,aAAa;AAC7D;;;;;AAMA,SAAgB,iBAAiB,UAAoB,MAA8B;CACjF,OAAO,YAAY,QAAQ,CAAC,EAAE,OAAO,IAAI,KAAK,IAAI,SAAS,SAAS,MAAM,IAAI;AAChF;;;;;;AAOA,SAAgB,oBAAoB,UAA0B;CAC5D,MAAM,MAAM,YAAY,QAAQ;CAChC,IAAI,KAAK;EACP,IAAI,QAAQ;EACZ;CACF;CAIA,IAAI;EACF,SAAS,MAAM,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACxC,QAAQ,CAER;AACF"}
1
+ {"version":3,"file":"node-response-C-dQn-0N.js","names":[],"sources":["../../src/server/abort-scope.ts","../../src/server/render-utils.ts","../../src/server/stream-utils.ts","../../src/server/node-response.ts"],"sourcesContent":["/**\n * Abort listeners scoped to the work they guard.\n *\n * A request's signal outlives the render, stream, or timer that listens to\n * it, and a listener left on it keeps everything its closure holds reachable\n * from the request. In production that only delays collection until the\n * request is garbage. In dev it pins the request forever: React's dev Flight\n * server tracks every live promise in an async-hook Map whose debug chains\n * reach the request, so any promise reachable from the request is never\n * collected and never leaves that Map (TIM-1589).\n *\n * So server code never calls `signal.addEventListener('abort', …)` itself\n * (tests/abort-listener-discipline.test.ts enforces it): {@link onAbortUntil}\n * takes the end of the listener's scope as a required argument, which makes\n * a listener without a removal unwritable.\n */\n\n/**\n * Call `onAbort` if `signal` aborts before the scope `until` ends. If\n * `signal` has already aborted, `onAbort` runs now.\n *\n * `until` is the scope: a promise (the listener is removed when it fulfills\n * or rejects, a microtask later) or an `AbortSignal` (removed synchronously\n * when it aborts; use one when an abort later in the same tick must not\n * fire, as after a timeout's `cancel()`).\n */\nexport function onAbortUntil(\n signal: AbortSignal | undefined,\n onAbort: () => void,\n until: PromiseLike<unknown> | AbortSignal\n): void {\n if (!signal) return;\n if (signal.aborted) {\n onAbort();\n return;\n }\n let scope: AbortSignal;\n if (until instanceof AbortSignal) {\n scope = until;\n } else {\n const ended = new AbortController();\n const end = (): void => ended.abort();\n until.then(end, end);\n scope = ended.signal;\n }\n // addEventListener's own `signal` option removes the listener when the\n // scope aborts: the platform's one-step removal, no handle to keep.\n signal.addEventListener('abort', onAbort, { once: true, signal: scope });\n}\n","/**\n * Shared render-phase utilities — used by both the Node.js and Web\n * stream wrappers. Pure functions only; no stream-shape dependencies.\n *\n * Consolidated from duplicated copies in node-stream-transforms.ts,\n * ssr-render.ts, and rsc-entry/helpers.ts. See TIM-1071 item 1.\n */\n\n/**\n * The ` nonce=\"…\"` attribute fragment for a timber-generated `<script>` tag,\n * or `''` when the request has no nonce. Callers interpolate it directly\n * after the tag name: `` `<script${nonceAttr(nonce)}>` ``.\n *\n * The value comes from `generateNonce` in csp-nonce.ts and is base64, so no attribute\n * escaping is required.\n */\nexport function nonceAttr(nonce: string | undefined): string {\n return nonce ? ` nonce=\"${nonce}\"` : '';\n}\n\n/**\n * The reason to abort a render with when its consumer releases it.\n *\n * The framework releases a Flight render it no longer needs — the renderer\n * once a deny or redirect is captured, a tee once either branch is done —\n * usually without a reason. React then reports the abort to the render's\n * `onError` as a plain `Error(\"The render was aborted by the server without a\n * reason.\")`, which reads as an application failure: a `metadata()` that\n * denies while the page is still fetching logged an unhandled render error\n * (TIM-1597). An `AbortError` is what {@link isAbortError} already treats as\n * not-an-error. A reason the caller did pass (a timeout, the tee's divergence\n * guard) is kept, so those still reach the log.\n */\nexport function releaseReason(reason: unknown): unknown {\n return reason ?? new DOMException('The render was released by its consumer.', 'AbortError');\n}\n\n/**\n * Check if an error is an abort error (connection closed by client).\n *\n * When the browser aborts a request (page refresh, navigation away),\n * the AbortSignal fires and React/streams throw an AbortError. This\n * is not an application error — suppress it from error boundaries and logs.\n *\n * A native `ReadableStream.tee()` cancels its source with an array of both\n * branches' reasons (Streams spec, ReadableStreamDefaultTee), so a Web\n * render released through a tee is aborted with `[reason1, reason2]`. That is\n * an abort when every entry is — a tee whose branches were both released\n * ({@link releaseReason}) — and an error when any entry is, such as the\n * divergence guard's.\n */\nexport function isAbortError(error: unknown): boolean {\n if (Array.isArray(error)) return error.length > 0 && error.every(isAbortError);\n if (error instanceof DOMException && error.name === 'AbortError') return true;\n if (error instanceof Error && error.name === 'AbortError') return true;\n return false;\n}\n\n/**\n * Inline script that adds `<meta name=\"robots\" content=\"noindex\">` to the\n * document head. Injected when a render-phase error replaces the shell so\n * search engines don't index error pages.\n *\n * MUST be byte-identical across all stream wrappers (Node and Web) for a\n * given nonce to ensure consistent Content-Length headers — which is why\n * both wrappers call this one function rather than inlining the string.\n */\nexport function noindexScript(nonce?: string): string {\n return `<script${nonceAttr(nonce)}>document.head.appendChild(Object.assign(document.createElement(\"meta\"),{name:\"robots\",content:\"noindex\"}))</script>`;\n}\n","/**\n * Stream utilities for the RSC rendering pipeline.\n *\n * teeWithErrorPropagation — wraps native ReadableStream.tee() with:\n * 1. Cross-branch error propagation (error on one branch cancels the other)\n * 2. Buffer divergence monitoring (warns + cancels when threshold exceeded)\n *\n * This prevents two classes of bugs:\n * - Silent stalls when one tee branch errors and the other hangs indefinitely\n * - Unbounded memory growth when one consumer (SSR) is much slower than the other\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\"\n */\n\nimport { getLogger } from './logger.ts';\n\n/** Default maximum buffer divergence before cancellation (5MB). */\nexport const DEFAULT_MAX_BUFFER_BYTES = 5 * 1024 * 1024;\n\nexport interface TeeOptions {\n /**\n * Maximum byte divergence between the two branches before both are\n * cancelled. When one branch has consumed this many more bytes than\n * the other, the tee's internal buffer is at least this large.\n *\n * Default: 5MB.\n */\n maxBufferBytes?: number;\n}\n\n/**\n * Tee a ReadableStream with error propagation and buffer monitoring.\n *\n * Delegates to the native `stream.tee()` for the actual forking, then wraps\n * each branch in a ReadableStream that:\n * - Tracks bytes consumed per branch\n * - Cancels both branches if byte divergence exceeds `maxBufferBytes`\n * - Cancels the other branch if either branch is cancelled or errors\n *\n * The returned streams are drop-in replacements for the native tee branches.\n */\nexport function teeWithErrorPropagation(\n stream: ReadableStream<Uint8Array>,\n options?: TeeOptions\n): [ReadableStream<Uint8Array>, ReadableStream<Uint8Array>] {\n const maxBuffer = options?.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;\n const [rawBranch1, rawBranch2] = stream.tee();\n\n // Shared state for cross-branch coordination\n let consumed1 = 0;\n let consumed2 = 0;\n let cancelled = false;\n\n // Readers and controllers are assigned when wrapBranch creates the wrapped\n // streams. We store them so cancelBoth can cancel raw tee branches AND\n // error the wrapped stream controllers for cross-branch propagation.\n let rawReader1: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let rawReader2: ReadableStreamDefaultReader<Uint8Array> | undefined;\n let controller1: ReadableStreamDefaultController<Uint8Array> | undefined;\n let controller2: ReadableStreamDefaultController<Uint8Array> | undefined;\n\n /**\n * Cancel both tee branches. `initiator` is the branch index (0 or 1)\n * that triggered the cancellation — its controller is already being\n * closed/errored by the pull/cancel that triggered this, so we skip it.\n * Pass -1 to cancel+error both (e.g., from the buffer divergence guard).\n *\n * Both raw readers are always canceled regardless of initiator, because\n * the tee source stream is only released when both branches are canceled.\n * ReadableStreamDefaultReader.cancel() is idempotent, so double-cancel\n * is safe.\n */\n function cancelBoth(reason: unknown, initiator: number = -1): void {\n if (cancelled) return;\n cancelled = true;\n // Cancel both raw readers — tee source requires both branches canceled.\n rawReader1?.cancel(reason).catch(() => {});\n rawReader2?.cancel(reason).catch(() => {});\n // Error wrapped controllers so consumers see the failure.\n // Skip the initiator's controller — it's already being closed/errored.\n if (initiator !== 0) {\n try {\n controller1?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n if (initiator !== 1) {\n try {\n controller2?.error(reason);\n } catch {\n /* already closed/errored */\n }\n }\n }\n\n function wrapBranch(\n branchIndex: number,\n rawBranch: ReadableStream<Uint8Array>,\n assignReader: (r: ReadableStreamDefaultReader<Uint8Array>) => void,\n assignController: (c: ReadableStreamDefaultController<Uint8Array>) => void,\n addConsumed: (n: number) => void,\n getSelfConsumed: () => number,\n getOtherConsumed: () => number\n ): ReadableStream<Uint8Array> {\n const reader = rawBranch.getReader();\n assignReader(reader);\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n assignController(controller);\n },\n\n async pull(controller) {\n if (cancelled) {\n return;\n }\n\n try {\n const { done, value } = await reader.read();\n\n // Re-check after await — cancelBoth may have fired while we\n // were waiting on the raw reader.\n if (cancelled) return;\n\n if (done) {\n try {\n controller.close();\n } catch {\n /* controller already errored by cancelBoth */\n }\n return;\n }\n\n addConsumed(value.byteLength);\n\n // Check buffer divergence: the difference in consumed bytes\n // approximates the tee's internal buffer size.\n const divergence = getSelfConsumed() - getOtherConsumed();\n if (divergence > maxBuffer) {\n cancelBoth(teeBufferExceeded(maxBuffer, divergence));\n return;\n }\n\n controller.enqueue(value);\n } catch (err) {\n if (!cancelled) {\n // Source stream errored — propagate to both branches.\n // cancelBoth with initiator skips our own controller,\n // so we error it explicitly here.\n cancelBoth(err, branchIndex);\n try {\n controller.error(err);\n } catch {\n /* already closed/errored */\n }\n }\n }\n },\n\n cancel(reason) {\n // Consumer cancelled this branch — propagate to the other\n cancelBoth(reason, branchIndex);\n },\n });\n }\n\n const wrapped1 = wrapBranch(\n 0,\n rawBranch1,\n (r) => {\n rawReader1 = r;\n },\n (c) => {\n controller1 = c;\n },\n (n) => {\n consumed1 += n;\n },\n () => consumed1,\n () => consumed2\n );\n\n const wrapped2 = wrapBranch(\n 1,\n rawBranch2,\n (r) => {\n rawReader2 = r;\n },\n (c) => {\n controller2 = c;\n },\n (n) => {\n consumed2 += n;\n },\n () => consumed2,\n () => consumed1\n );\n\n return [wrapped1, wrapped2];\n}\n\n/**\n * Stream-lifecycle timing for one response body: firstChunk, lastChunk,\n * close, maxGap (largest inter-chunk gap), chunk count, and byte count,\n * logged once when the stream terminates (clean close OR\n * cancellation/disconnect). Gated behind `serverTiming: 'detailed'`. The\n * Web body wrapper below and the Node body (`node-body-response.ts`) feed\n * the same recorder, so the two report identically.\n */\nexport interface StreamTimingRecorder {\n chunk(byteLength: number): void;\n end(cancelled: boolean): void;\n}\n\nexport function createStreamTimingRecorder(startTime: number): StreamTimingRecorder {\n let firstChunkMs = 0;\n let lastChunkMs = 0;\n let maxGapMs = 0;\n let prevChunkTime = 0;\n let chunks = 0;\n let bytes = 0;\n let ended = false;\n\n return {\n chunk(byteLength) {\n const now = performance.now();\n const relativeMs = Math.round(now - startTime);\n if (chunks === 0) {\n firstChunkMs = relativeMs;\n } else {\n const gap = Math.round(now - prevChunkTime);\n if (gap > maxGapMs) maxGapMs = gap;\n }\n prevChunkTime = now;\n lastChunkMs = relativeMs;\n chunks++;\n bytes += byteLength;\n },\n end(cancelled) {\n if (ended) return;\n ended = true;\n const closeMs = Math.round(performance.now() - startTime);\n getLogger().debug('stream-lifecycle', {\n firstChunkMs,\n lastChunkMs,\n closeMs,\n maxGapMs,\n chunks,\n bytes,\n ...(cancelled ? { cancelled: true } : {}),\n });\n },\n };\n}\n\n/**\n * Wrap a Web response body with stream-lifecycle timing instrumentation\n * ({@link createStreamTimingRecorder}).\n *\n * Uses a manual reader pump to guarantee logging on all termination\n * paths — TransformStream.flush() is not called on cancellation.\n */\nexport function wrapResponseWithStreamTiming(\n body: ReadableStream<Uint8Array>,\n startTime: number\n): ReadableStream<Uint8Array> {\n const timing = createStreamTimingRecorder(startTime);\n const reader = body.getReader();\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n timing.end(false);\n controller.close();\n return;\n }\n timing.chunk(value.byteLength);\n controller.enqueue(value);\n } catch (err) {\n timing.end(false);\n controller.error(err);\n }\n },\n\n cancel(reason) {\n timing.end(true);\n reader.cancel(reason).catch(() => {});\n },\n });\n}\n\n/** Format bytes as human-readable string (e.g., \"5.00 MB\"). */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;\n}\n\n/**\n * The error both tee implementations (this Web one and the Node one in\n * `flight-source-node.ts`) cancel with when one branch lags the other by more\n * than `maxBuffer` bytes. Warns once, here, so the two cannot drift.\n */\nexport function teeBufferExceeded(maxBuffer: number, divergence: number): Error {\n const error = new Error(\n `RSC stream tee buffer exceeded ${formatBytes(maxBuffer)} ` +\n `(divergence: ${formatBytes(divergence)}). ` +\n `This usually means SSR is much slower than the inline stream consumer. ` +\n `Consider reducing RSC payload size or increasing the tee buffer limit.`\n );\n console.warn(`[timber] ${error.message}`);\n return error;\n}\n\n/**\n * A pull reader over any chunk stream: a Web reader, or the Flight reader in\n * `flight-source.ts`, which reads a Node or Web Flight source.\n */\nexport interface ChunkReader<T> {\n read(): Promise<ReadableStreamReadResult<T>>;\n cancel(reason?: unknown): void;\n}\n\n/**\n * Read a chunk stream to completion under one overall deadline. Every read\n * is raced against the time remaining, and the reader is cancelled on every\n * exit, so a stalled upstream never outlives the deadline. See\n * design/02-rendering-pipeline.md §\"Always Timeout-Guard Stream Reads\".\n *\n * @param label - Prefix for the timeout error message. Both ways the deadline\n * can pass (between reads, or while a read is pending) reject with the same\n * `${label} did not complete within ${timeoutMs}ms`.\n */\nexport async function drainWithDeadline<T>(\n reader: ChunkReader<T>,\n timeoutMs: number,\n label: string\n): Promise<T[]> {\n const chunks: T[] = [];\n const deadline = Date.now() + timeoutMs;\n const deadlineError = () => new Error(`${label} did not complete within ${timeoutMs}ms`);\n try {\n for (;;) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) throw deadlineError();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(deadlineError()), remaining);\n });\n let result: Awaited<ReturnType<ChunkReader<T>['read']>>;\n try {\n result = await Promise.race([reader.read(), timeout]);\n } finally {\n clearTimeout(timer);\n }\n if (result.done) return chunks;\n chunks.push(result.value);\n }\n } finally {\n reader.cancel();\n }\n}\n\n/** Concatenate byte chunks into one array. */\nexport function concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n let total = 0;\n for (const chunk of chunks) total += chunk.byteLength;\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return bytes;\n}\n\n/**\n * Read a byte stream to completion under one overall deadline and return\n * the concatenated bytes ({@link drainWithDeadline}). The static generator's\n * body drain uses it; Flight renders use `collectFlightBytes`\n * (`flight-source.ts`), which reads either source kind the same way.\n */\nexport async function readAllBytesWithDeadline(\n stream: ReadableStream<Uint8Array>,\n timeoutMs: number,\n label: string\n): Promise<Uint8Array> {\n const reader = stream.getReader();\n const chunks = await drainWithDeadline(\n { read: () => reader.read(), cancel: (reason) => void reader.cancel(reason).catch(() => {}) },\n timeoutMs,\n label\n );\n return concatBytes(chunks);\n}\n","/**\n * Responses with a Node body — the platform-neutral half.\n *\n * On Node, SSR's HTML and Flight payload bodies are Node `Readable`s. They\n * travel the pipeline as a `NodeBodyResponse` (`node-body-response.ts`, Node\n * only): a real `Response` whose body stays a Node stream until the adapter\n * pipes it to the socket, so a response is never converted Node → Web → Node\n * (LOCAL-1475). srvx (nitro, the dev server) and nitro-preview's sender take\n * the Node body through `_toNodeResponse()`. Any code that reads the body\n * through the Web API still works: the response then converts once.\n *\n * Pipeline code shared with Workers re-wraps, strips, or times a response\n * through the helpers here, which ask the response itself to do the Node\n * work, so this module never imports `node:stream`. A response is recognised\n * by a `Symbol.for` brand, not `instanceof`: the RSC and SSR environments\n * load separate copies of the class.\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport type { Duplex } from 'node:stream';\n\n/** The brand a Node-body response carries, keyed by a registry symbol. */\nexport const NODE_BODY = Symbol.for('timber.response.nodeBody');\n\n/**\n * What a Node-body response can do with its body, for code that cannot import\n * the class: platform-neutral modules, and the standalone `_compress.mjs`,\n * which reaches these through the same registry symbol. Each one takes the\n * body: the response it was called on no longer has one.\n */\nexport interface NodeBodyOps {\n /**\n * Whether the response still owns a body. False for a null-body status\n * (204, 205, 304, …) and once the body was taken. Being branded says\n * nothing about this — ask here instead of reading `.body`, which would\n * convert it.\n */\n readonly hasBody: boolean;\n /** The same body under a new status and headers. */\n rewrap(init: ResponseInit): Response;\n /** Release the body unread (HEAD, a discarded document), aborting its producer. */\n discard(): void;\n /** The same body, reporting stream timing when it ends (detailed Server-Timing). */\n timed(startTime: number): Response;\n /**\n * The body piped through `stream` (gzip), as a Node-body response under\n * `init`. An error or destroy on either end tears down both.\n */\n through(stream: Duplex, init: ResponseInit): Response;\n}\n\ninterface NodeBodyBranded {\n [NODE_BODY]: NodeBodyOps;\n}\n\nfunction isNodeBodyBranded(response: Response): response is Response & NodeBodyBranded {\n return NODE_BODY in response;\n}\n\n/** The Node-body operations of `response`, or `null` for a Web-body response. */\nexport function nodeBodyOps(response: Response): NodeBodyOps | null {\n return isNodeBodyBranded(response) ? response[NODE_BODY] : null;\n}\n\n/**\n * `response`'s body under a new status and headers. A Node body moves to the\n * new response without converting; a Web body is reused as is.\n */\nexport function withResponseInit(response: Response, init: ResponseInit): Response {\n return nodeBodyOps(response)?.rewrap(init) ?? new Response(response.body, init);\n}\n\n/**\n * Release a response's body unread. A live producer (an SSR render, a Flight\n * render) is behind it; dropping the reference without this leaks it for the\n * lifetime of the render (design/13-security.md A4).\n */\nexport function discardResponseBody(response: Response): void {\n const ops = nodeBodyOps(response);\n if (ops) {\n ops.discard();\n return;\n }\n // `cancel()` rejects if the stream is already errored and throws\n // synchronously if it is locked — neither is actionable, the body is being\n // discarded either way.\n try {\n response.body?.cancel().catch(() => {});\n } catch {\n /* stream already locked or disturbed */\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,aACd,QACA,SACA,OACM;CACN,IAAI,CA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as EXPLICIT_MARKERS } from "./poison-rules-Bmz-lCPi.js";
2
- import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify--_kINHQV.js";
2
+ import { o as langForFile, t as PARSEABLE_EXTENSIONS } from "./classify-BuIifN5v.js";
3
3
  import { parseAst } from "vite";
4
4
  // src/analyze/poison-scan.ts
5
5
  /**
@@ -95,4 +95,4 @@ function poisoningsFor(kind, pending, signals) {
95
95
  }
96
96
  export { importSignals as n, poisoningsFor as r, collectImportSpecifiers as t };
97
97
 
98
- //# sourceMappingURL=poison-scan-DJYxZc_7.js.map
98
+ //# sourceMappingURL=poison-scan-CqPGN0ru.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"poison-scan-DJYxZc_7.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,wBACP,YACS;CACT,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,OAAO,WAAW,OAAO,MAAM,EAAE,eAAe,UAAU,EAAE,eAAe,MAAM;AACnF;;;;;;;AAQA,SAAgB,wBAAwB,MAAc,MAAwB;CAC5E,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO,CAAC;CAC9C,IAAI;CACJ,IAAI;EAEF,UAAU,SAAS,MAAM,EAAE,MAAM,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G,OAAO,CAAC;CAC7C,MAAM,kBACJ,SAAS,qBAAqB,SAAS,qBAAqB,SAAS;CACvE,MAAM,kBAAkB,SAAS,YAAY,SAAS,YAAY,SAAS;CAC3E,OAAO,QAAQ,QACZ,WACE,OAAO,YAAY,iBAAiB,mBACpC,OAAO,YAAY,iBAAiB,eACzC;AACF"}
1
+ {"version":3,"file":"poison-scan-CqPGN0ru.js","names":[],"sources":["../../src/analyze/poison-scan.ts"],"sourcesContent":["/**\n * poison-scan — report-only poisoning detection for `timber graph`.\n *\n * Matches a module's static import specifiers against the shared rule\n * lists in poison-rules.ts (the single source of truth — design/47 §3)\n * and reports a poisoning only when the implied exclusivity CONFLICTS\n * with where the module actually runs: a server-only signal in a\n * client-reachable module, or a client-only signal in a server-reachable\n * one. A `node:fs` import in a file only the RSC environment loads is\n * working code, not a finding.\n *\n * Scope: import-specifier signals only (explicit markers + the inferred\n * rules' `matchesImport`). The inferred browser-global identifier rules\n * need shadow-safe allowlisted-position AST matching and are a separate\n * ticket — reporting them from a text scan would flag legitimate code.\n *\n * Design docs: 47-module-environment-tooling.md §3.\n */\n\nimport { parseAst } from 'vite';\nimport { EXPLICIT_MARKERS, INFERRED_RULES } from './poison-rules.ts';\nimport { langForFile, PARSEABLE_EXTENSIONS, type ModuleKind } from './classify.ts';\n\n/** One poisoning finding on a module, in the JSON-contract shape. */\nexport interface Poisoning {\n /** Rule id — an inferred rule's id, or the explicit marker specifier. */\n rule: string;\n /** The import specifier that matched. */\n specifier: string;\n /** Which exclusivity the signal implies for the containing module. */\n implies: 'server-only' | 'client-only';\n /** Human-readable description for reporter output. */\n description: string;\n}\n\n/**\n * A NON-EMPTY specifier list where every entry is type-only. Empty or\n * absent lists return false — a bare `import 'pkg'` is a side-effect\n * import and very much runs.\n */\nfunction isAllSpecifiersTypeOnly(\n specifiers: Array<{ importKind?: string; exportKind?: string }> | undefined\n): boolean {\n if (!specifiers || specifiers.length === 0) return false;\n return specifiers.every((s) => s.importKind === 'type' || s.exportKind === 'type');\n}\n\n/**\n * Collect every static import/export source and string-literal dynamic\n * import from a module's original source. Sources that fail to parse\n * (or are not JS/TS at all) return [] — no specifiers is a safe\n * default for a report-only scan.\n */\nexport function collectImportSpecifiers(code: string, file: string): string[] {\n if (!PARSEABLE_EXTENSIONS.test(file)) return [];\n let program;\n try {\n // Language from the extension, never forced tsx — see langForFile.\n program = parseAst(code, { lang: langForFile(file) });\n } catch {\n return [];\n }\n const specifiers: string[] = [];\n const visit = (node: unknown): void => {\n if (Array.isArray(node)) {\n for (const child of node) visit(child);\n return;\n }\n if (typeof node !== 'object' || node === null) return;\n const record = node as Record<string, unknown> & {\n type?: string;\n importKind?: string;\n exportKind?: string;\n specifiers?: Array<{ importKind?: string; exportKind?: string }>;\n };\n if (\n (record.type === 'ImportDeclaration' ||\n record.type === 'ExportNamedDeclaration' ||\n record.type === 'ExportAllDeclaration') &&\n // Type-only imports/exports are erased at runtime — `import type\n // { Stats } from 'node:fs'` in client code is working code, and\n // flagging it would be a false positive in a report-only scan.\n // Covers both the declaration-level form (`import type {…}`,\n // importKind on the declaration) and the inline form\n // (`import { type Stats }`, where the declaration stays 'value'\n // and each SPECIFIER carries the kind) — a declaration whose\n // specifiers are all type-only is erased just the same.\n record.importKind !== 'type' &&\n record.exportKind !== 'type' &&\n !isAllSpecifiersTypeOnly(record.specifiers) &&\n typeof (record.source as { value?: unknown } | null)?.value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n } else if (\n record.type === 'ImportExpression' &&\n (record.source as { type?: string; value?: unknown })?.type === 'Literal' &&\n typeof (record.source as { value?: unknown }).value === 'string'\n ) {\n specifiers.push((record.source as { value: string }).value);\n }\n for (const key of Object.keys(record)) {\n if (key === 'type') continue;\n visit(record[key]);\n }\n };\n visit(program.body);\n return specifiers;\n}\n\n/** Exclusivity signals a module's import specifiers carry. */\nexport function importSignals(specifiers: string[]): Poisoning[] {\n const signals: Poisoning[] = [];\n for (const specifier of specifiers) {\n for (const marker of EXPLICIT_MARKERS) {\n if (specifier === marker.specifier) {\n signals.push({\n rule: marker.specifier,\n specifier,\n implies: marker.specifier === 'server-only' ? 'server-only' : 'client-only',\n description: `imports the ${marker.specifier} poison-pill marker`,\n });\n }\n }\n for (const rule of INFERRED_RULES) {\n if (rule.matchesImport?.(specifier)) {\n signals.push({\n rule: rule.id,\n specifier,\n implies: rule.implies,\n description: rule.description,\n });\n }\n }\n }\n return signals;\n}\n\n/**\n * Filter a module's signals down to actual conflicts with its\n * classification. Environment reach follows the taxonomy: boundary /\n * client-internal / shared modules run client-side; server / shared /\n * server-action modules run server-side. Pending (provisional) modules\n * run nowhere confirmed, so nothing conflicts yet.\n */\nexport function poisoningsFor(\n kind: ModuleKind,\n pending: boolean,\n signals: Poisoning[]\n): Poisoning[] {\n if (pending || signals.length === 0) return [];\n const clientReachable =\n kind === 'client-boundary' || kind === 'client-internal' || kind === 'shared';\n const serverReachable = kind === 'server' || kind === 'shared' || kind === 'server-action';\n return signals.filter(\n (signal) =>\n (signal.implies === 'server-only' && clientReachable) ||\n (signal.implies === 'client-only' && serverReachable)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,wBACP,YACS;CACT,IAAI,CAAC,cAAc,WAAW,WAAW,GAAG,OAAO;CACnD,OAAO,WAAW,OAAO,MAAM,EAAE,eAAe,UAAU,EAAE,eAAe,MAAM;AACnF;;;;;;;AAQA,SAAgB,wBAAwB,MAAc,MAAwB;CAC5E,IAAI,CAAC,qBAAqB,KAAK,IAAI,GAAG,OAAO,CAAC;CAC9C,IAAI;CACJ,IAAI;EAEF,UAAU,SAAS,MAAM,EAAE,MAAM,YAAY,IAAI,EAAE,CAAC;CACtD,QAAQ;EACN,OAAO,CAAC;CACV;CACA,MAAM,aAAuB,CAAC;CAC9B,MAAM,SAAS,SAAwB;EACrC,IAAI,MAAM,QAAQ,IAAI,GAAG;GACvB,KAAK,MAAM,SAAS,MAAM,MAAM,KAAK;GACrC;EACF;EAC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zC;AACF"}
@@ -0,0 +1,36 @@
1
+ // src/server/route-methods.ts
2
+ /**
3
+ * The HTTP methods a `route.ts` can export as named handlers.
4
+ *
5
+ * A leaf module with no imports, so the build-time convention lint
6
+ * (`routing/convention-lint.ts`) and the runtime dispatcher
7
+ * (`server/route-handler.ts`) read one list without the lint pulling in
8
+ * the request runtime. Adding a method here updates the `RouteModule` type,
9
+ * the `Allow` header on 405 and automatic `OPTIONS` responses, and the
10
+ * `ROUTE_NO_METHODS` lint together.
11
+ *
12
+ * `QUERY` is RFC 10008's safe, idempotent method with a request body.
13
+ * See design/07-routing.md §"Supported Methods".
14
+ */
15
+ var HTTP_METHODS = [
16
+ "GET",
17
+ "QUERY",
18
+ "POST",
19
+ "PUT",
20
+ "PATCH",
21
+ "DELETE",
22
+ "HEAD",
23
+ "OPTIONS"
24
+ ];
25
+ var METHOD_SET = new Set(HTTP_METHODS);
26
+ /**
27
+ * Whether a request method names a route.ts handler. Exact case: method
28
+ * names are case-sensitive (RFC 9110 §9.1), and the CSRF gate compares them
29
+ * exactly, so `query` is not `QUERY` here either.
30
+ */
31
+ function isHttpMethod(method) {
32
+ return METHOD_SET.has(method);
33
+ }
34
+ export { isHttpMethod as n, HTTP_METHODS as t };
35
+
36
+ //# sourceMappingURL=route-methods-Dk2kZc0n.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-methods-Dk2kZc0n.js","names":[],"sources":["../../src/server/route-methods.ts"],"sourcesContent":["/**\n * The HTTP methods a `route.ts` can export as named handlers.\n *\n * A leaf module with no imports, so the build-time convention lint\n * (`routing/convention-lint.ts`) and the runtime dispatcher\n * (`server/route-handler.ts`) read one list without the lint pulling in\n * the request runtime. Adding a method here updates the `RouteModule` type,\n * the `Allow` header on 405 and automatic `OPTIONS` responses, and the\n * `ROUTE_NO_METHODS` lint together.\n *\n * `QUERY` is RFC 10008's safe, idempotent method with a request body.\n * See design/07-routing.md §\"Supported Methods\".\n */\nexport const HTTP_METHODS = [\n 'GET',\n 'QUERY',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'HEAD',\n 'OPTIONS',\n] as const;\n\n/** HTTP methods that route.ts can export as named handlers. */\nexport type HttpMethod = (typeof HTTP_METHODS)[number];\n\nconst METHOD_SET: ReadonlySet<string> = new Set(HTTP_METHODS);\n\n/**\n * Whether a request method names a route.ts handler. Exact case: method\n * names are case-sensitive (RFC 9110 §9.1), and the CSRF gate compares them\n * exactly, so `query` is not `QUERY` here either.\n */\nexport function isHttpMethod(method: string): method is HttpMethod {\n return METHOD_SET.has(method);\n}\n"],"mappings":";;;;;;;;;;;;;;AAaA,IAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAKA,IAAM,aAAkC,IAAI,IAAI,YAAY;;;;;;AAO5D,SAAgB,aAAa,QAAsC;CACjE,OAAO,WAAW,IAAI,MAAM;AAC9B"}
@@ -3,7 +3,7 @@ import { n as NULL_BYTE_RE, t as ENCODED_SEPARATOR_RE } from "./canonicalize-CqK
3
3
  import { t as matchUrlParts } from "./tree-match-Bqdr9szG.js";
4
4
  import { i as DEFAULT_PAGE_EXTENSIONS, n as classifyUrlSegment, r as effectiveUrlSegment, t as classifySegment } from "./segment-classify-Ho8jXWeC.js";
5
5
  import { n as treePathDepth, t as computeSegmentTreePaths } from "./segment-keys-Y60KNc8C.js";
6
- import { b as swallow } from "./logger-CWk44DLp.js";
6
+ import { b as swallow } from "./logger-DRMij51J.js";
7
7
  import { parseAst } from "vite";
8
8
  import { basename, extname, join } from "node:path";
9
9
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
@@ -2045,4 +2045,4 @@ function findScriptExtFile(dirPath, name) {
2045
2045
  }
2046
2046
  export { fileHasDefaultExport as a, getCsrfExport as c, collectInterceptionRewrites as d, fileHasAnyExport as i, getPrerenderExport as l, scanRoutes as n, fileHasDirective as o, fileDefaultExportIsLocalValue as r, fileHasStarExport as s, isRouteConventionFile as t, readFileCached as u };
2047
2047
 
2048
- //# sourceMappingURL=scanner-CJC-ScJU.js.map
2048
+ //# sourceMappingURL=scanner-C__vsQ8d.js.map