@timber-js/app 0.2.0-alpha.228 → 0.2.0-alpha.229
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent-skill.md +9 -0
- package/dist/_chunks/{actions-DprvPi7O.js → actions-DHum77eH.js} +3 -3
- package/dist/_chunks/{actions-DprvPi7O.js.map → actions-DHum77eH.js.map} +1 -1
- package/dist/_chunks/{cache-api-BjE-nNC0.js → cache-api-BZJNt01a.js} +4 -4
- package/dist/_chunks/{cache-api-BjE-nNC0.js.map → cache-api-BZJNt01a.js.map} +1 -1
- package/dist/_chunks/{chains-DaDEXv0c.js → chains-D-RRc7CM.js} +2 -2
- package/dist/_chunks/{chains-DaDEXv0c.js.map → chains-D-RRc7CM.js.map} +1 -1
- package/dist/_chunks/chains-KblEfYzm.js +1 -0
- package/dist/_chunks/{classify-BuIifN5v.js → classify-_W0RWa5w.js} +2 -2
- package/dist/_chunks/{classify-BuIifN5v.js.map → classify-_W0RWa5w.js.map} +1 -1
- package/dist/_chunks/{cli-check-B_fDvxhs.js → cli-check-B-JZkpBD.js} +3 -3
- package/dist/_chunks/{cli-check-B_fDvxhs.js.map → cli-check-B-JZkpBD.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-D9OLUUFv.js → cli-schema-sync-CAllbqRB.js} +2 -2
- package/dist/_chunks/{cli-schema-sync-D9OLUUFv.js.map → cli-schema-sync-CAllbqRB.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CUIk0G2X.js → cli-schema-sync-y_8ijmzO.js} +1 -1
- package/dist/_chunks/{client-dep-entries-COuyF8-c.js → client-dep-entries-C9hv-3k9.js} +2 -2
- package/dist/_chunks/{client-dep-entries-COuyF8-c.js.map → client-dep-entries-C9hv-3k9.js.map} +1 -1
- package/dist/_chunks/{convention-lint-BHY0d5AQ.js → convention-lint-CrDKERHg.js} +3 -3
- package/dist/_chunks/{convention-lint-BHY0d5AQ.js.map → convention-lint-CrDKERHg.js.map} +1 -1
- package/dist/_chunks/dev-server-L8biS7Az.js +1 -0
- package/dist/_chunks/{dev-server-BaM7q3pr.js → dev-server-Rq659RR1.js} +8 -2
- package/dist/_chunks/dev-server-Rq659RR1.js.map +1 -0
- package/dist/_chunks/{build-manifest-Y4jl7nwU.js → dev-span-_NzMX-au.js} +25 -2
- package/dist/_chunks/dev-span-_NzMX-au.js.map +1 -0
- package/dist/_chunks/{error-boundary-D3YyVVuP.js → error-boundary-OHK1mI99.js} +3 -3
- package/dist/_chunks/{error-boundary-D3YyVVuP.js.map → error-boundary-OHK1mI99.js.map} +1 -1
- package/dist/_chunks/{flight-source-node-CZJ9Drb7.js → flight-source-node-BGanuoSS.js} +2 -2
- package/dist/_chunks/{flight-source-node-CZJ9Drb7.js.map → flight-source-node-BGanuoSS.js.map} +1 -1
- package/dist/_chunks/{global-context-DbxNWeBP.js → global-context-CFSSysdJ.js} +32 -2
- package/dist/_chunks/global-context-CFSSysdJ.js.map +1 -0
- package/dist/_chunks/{json-lossy-check-BNwKrm2R.js → json-lossy-check-BXM45k8p.js} +2 -2
- package/dist/_chunks/{json-lossy-check-BNwKrm2R.js.map → json-lossy-check-BXM45k8p.js.map} +1 -1
- package/dist/_chunks/{live-graph-DiRVmRrC.js → live-graph-C7-yA8W9.js} +4 -4
- package/dist/_chunks/{live-graph-DiRVmRrC.js.map → live-graph-C7-yA8W9.js.map} +1 -1
- package/dist/_chunks/{logger-DRMij51J.js → logger-YtMSKfft.js} +100 -57
- package/dist/_chunks/logger-YtMSKfft.js.map +1 -0
- package/dist/_chunks/navigation-root-CoGHIMiE.js +239 -0
- package/dist/_chunks/navigation-root-CoGHIMiE.js.map +1 -0
- package/dist/_chunks/{node-response-C-dQn-0N.js → node-response-D3hXWb8y.js} +2 -2
- package/dist/_chunks/{node-response-C-dQn-0N.js.map → node-response-D3hXWb8y.js.map} +1 -1
- package/dist/_chunks/{poison-scan-CqPGN0ru.js → poison-scan-CRSP06Es.js} +2 -2
- package/dist/_chunks/{poison-scan-CqPGN0ru.js.map → poison-scan-CRSP06Es.js.map} +1 -1
- package/dist/_chunks/{scanner-C__vsQ8d.js → scanner-BNQ4qnLX.js} +2 -2
- package/dist/_chunks/{scanner-C__vsQ8d.js.map → scanner-BNQ4qnLX.js.map} +1 -1
- package/dist/_chunks/segment-context-GAyTjjtS.js +33 -0
- package/dist/_chunks/segment-context-GAyTjjtS.js.map +1 -0
- package/dist/_chunks/{sizeof-DcEcQaSL.js → sizeof-Cmx6Fs-Y.js} +2 -2
- package/dist/_chunks/{sizeof-DcEcQaSL.js.map → sizeof-Cmx6Fs-Y.js.map} +1 -1
- package/dist/_chunks/{status-page-marker-C8POawuF.js → status-page-marker-U6B1aFMb.js} +3 -32
- package/dist/_chunks/status-page-marker-U6B1aFMb.js.map +1 -0
- package/dist/_chunks/{walkers-D6KY4jyS.js → walkers-D_QHR_nf.js} +3 -3
- package/dist/_chunks/{walkers-D6KY4jyS.js.map → walkers-D_QHR_nf.js.map} +1 -1
- package/dist/adapters/cloudflare-kv-cache.js +1 -1
- package/dist/analyze/crawl-entry.js +3 -3
- package/dist/analyze/graph-command.js +2 -2
- package/dist/cache/index.js +2 -2
- package/dist/cache/stores/memory.js +1 -1
- package/dist/cli.js +3 -3
- package/dist/client/browser-entry/hmr.d.ts +7 -1
- package/dist/client/browser-entry/hmr.d.ts.map +1 -1
- package/dist/client/dev-pill/index.d.ts +32 -0
- package/dist/client/dev-pill/index.d.ts.map +1 -0
- package/dist/client/dev-pill/store.d.ts +96 -0
- package/dist/client/dev-pill/store.d.ts.map +1 -0
- package/dist/client/dev-pill/view.d.ts +9 -0
- package/dist/client/dev-pill/view.d.ts.map +1 -0
- package/dist/client/error-boundary.js +1 -1
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +3 -3
- package/dist/client/internal.js +16 -7
- package/dist/client/internal.js.map +1 -1
- package/dist/client/navigation-context.d.ts +20 -0
- package/dist/client/navigation-context.d.ts.map +1 -1
- package/dist/client/router-lifecycle.d.ts +4 -1
- package/dist/client/router-lifecycle.d.ts.map +1 -1
- package/dist/client/use-pending-navigation.d.ts +33 -9
- package/dist/client/use-pending-navigation.d.ts.map +1 -1
- package/dist/config-types.d.ts +10 -0
- package/dist/config-types.d.ts.map +1 -1
- package/dist/config-validation.d.ts.map +1 -1
- package/dist/dev-tools/await-span.d.ts +17 -0
- package/dist/dev-tools/await-span.d.ts.map +1 -0
- package/dist/dev-tools/instrumentation.d.ts.map +1 -1
- package/dist/dev-tools/logger.d.ts.map +1 -1
- package/dist/dev-tools/logs.d.ts.map +1 -1
- package/dist/dev-tools/span-sink.d.ts +42 -0
- package/dist/dev-tools/span-sink.d.ts.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +282 -9
- package/dist/index.js.map +1 -1
- package/dist/plugins/dev-await.d.ts +40 -0
- package/dist/plugins/dev-await.d.ts.map +1 -0
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/routing/index.js +2 -2
- package/dist/server/index.js +2 -2
- package/dist/server/internal.js +9 -8
- package/dist/server/internal.js.map +1 -1
- package/dist/server/pipeline.d.ts +8 -0
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/slot-resolver.d.ts.map +1 -1
- package/dist/server/tracing.d.ts +18 -8
- package/dist/server/tracing.d.ts.map +1 -1
- package/dist/shared/dev-span.d.ts +97 -0
- package/dist/shared/dev-span.d.ts.map +1 -0
- package/docs/api/31-api-client.mdx +27 -1
- package/docs/api/34-api-config.mdx +21 -1
- package/docs/learn/09-streaming.mdx +7 -1
- package/package.json +3 -3
- package/src/client/browser-entry/hmr.ts +13 -1
- package/src/client/browser-entry/index.ts +4 -1
- package/src/client/dev-pill/index.ts +128 -0
- package/src/client/dev-pill/store.ts +231 -0
- package/src/client/dev-pill/view.ts +278 -0
- package/src/client/index.ts +1 -0
- package/src/client/navigation-context.ts +5 -2
- package/src/client/router-lifecycle.ts +23 -3
- package/src/client/use-pending-navigation.ts +93 -14
- package/src/config-types.ts +10 -0
- package/src/config-validation.ts +10 -0
- package/src/dev-tools/await-span.ts +40 -0
- package/src/dev-tools/instrumentation.ts +20 -0
- package/src/dev-tools/logger.ts +3 -37
- package/src/dev-tools/logs.ts +10 -1
- package/src/dev-tools/span-sink.ts +132 -0
- package/src/index.ts +2 -0
- package/src/plugins/dev-await.ts +268 -0
- package/src/plugins/entries.ts +2 -0
- package/src/server/pipeline.ts +14 -0
- package/src/server/rsc-entry/index.ts +7 -1
- package/src/server/slot-resolver.ts +45 -5
- package/src/server/tracing.ts +121 -87
- package/src/shared/dev-span.ts +182 -0
- package/dist/_chunks/build-manifest-Y4jl7nwU.js.map +0 -1
- package/dist/_chunks/chains-BS8fQYao.js +0 -1
- package/dist/_chunks/dev-server-BaM7q3pr.js.map +0 -1
- package/dist/_chunks/dev-server-NnGosJ06.js +0 -1
- package/dist/_chunks/global-context-DbxNWeBP.js.map +0 -1
- package/dist/_chunks/logger-DRMij51J.js.map +0 -1
- package/dist/_chunks/navigation-root-M3B2ZrdO.js +0 -122
- package/dist/_chunks/navigation-root-M3B2ZrdO.js.map +0 -1
- package/dist/_chunks/segment-context-CYiGTi3K.js +0 -131
- package/dist/_chunks/segment-context-CYiGTi3K.js.map +0 -1
- package/dist/_chunks/status-page-marker-C8POawuF.js.map +0 -1
package/dist/_chunks/{flight-source-node-CZJ9Drb7.js.map → flight-source-node-BGanuoSS.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flight-source-node-CZJ9Drb7.js","names":["ignoreError"],"sources":["../../src/server/node-body-response.ts","../../src/server/flight-source-node.ts"],"sourcesContent":["/**\n * `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a\n * response built on Node streams reaches the socket without a Web Streams\n * round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.\n *\n * The status and headers are an ordinary `Response`'s. The body stays a Node\n * stream until one of two things takes it:\n *\n * - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and\n * the dev server send with srvx; nitro-preview's sender speaks it too). The\n * stream is piped straight into `ServerResponse`.\n * - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …\n * The response then converts its body once, with `Readable.toWeb`, and\n * behaves as a native `Response` from then on. Correct anywhere, so code\n * that does not know about Node bodies keeps working; pipeline code on the\n * hot path goes through `node-response.ts` instead, which never converts.\n *\n * Pattern from srvx's `NodeResponse` (`FastResponse`).\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport { Readable, Transform, pipeline, type Duplex } from 'node:stream';\nimport { NODE_BODY, type NodeBodyOps } from './node-response.ts';\nimport { createStreamTimingRecorder, wrapResponseWithStreamTiming } from './stream-utils.ts';\n\n/** Statuses whose responses carry no body (Fetch \"null body status\"). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);\n\nfunction ignoreError(): void {}\n\n/** Destroy a body nothing will read, without an unhandled `'error'`. */\nfunction destroyBody(body: Readable): void {\n if (!body.listeners('error').includes(ignoreError)) body.on('error', ignoreError);\n body.destroy();\n}\n\nexport class NodeBodyResponse extends Response {\n #body: Readable | null;\n #native: Response | null = null;\n /** An adapter or a pipeline op took the body: it is used, as a read one is. */\n #taken = false;\n\n constructor(body: Readable, init?: ResponseInit) {\n super(null, init);\n if (NULL_BODY_STATUSES.has(this.status)) {\n destroyBody(body);\n this.#body = null;\n } else {\n this.#body = body;\n }\n }\n\n /** Take the Node body; this response no longer has it. */\n #take(): Readable | null {\n const body = this.#body;\n if (body) this.#taken = true;\n this.#body = null;\n return body;\n }\n\n /**\n * This response as a native one, converting the Node body once. Throws, as\n * a native Response whose body was read does, if something already took\n * the body (an adapter, a re-wrap), rather than reading as empty.\n */\n #toNative(): Response {\n if (!this.#native) {\n if (this.#taken) throw new TypeError('Body is unusable: Body has already been read');\n const body = this.#body;\n this.#body = null;\n this.#native = new Response(\n body ? (Readable.toWeb(body) as ReadableStream<Uint8Array>) : null,\n {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n }\n );\n }\n return this.#native;\n }\n\n get [NODE_BODY](): NodeBodyOps {\n return {\n hasBody: this.#native ? this.#native.body !== null : this.#body !== null,\n rewrap: (init) => {\n if (this.#native) return new Response(this.#native.body, init);\n const body = this.#take();\n return body ? new NodeBodyResponse(body, init) : new Response(null, init);\n },\n discard: () => {\n if (this.#native) {\n this.#native.body?.cancel().catch(() => {});\n return;\n }\n const body = this.#take();\n if (body) destroyBody(body);\n },\n through: (stream, init) => {\n const body = this.#native\n ? this.#native.body && webToNode(this.#native.body)\n : this.#take();\n return body\n ? new NodeBodyResponse(pipeThrough(body, stream), init)\n : new Response(null, init);\n },\n timed: (startTime) => {\n const init = { status: this.status, statusText: this.statusText, headers: this.headers };\n if (this.#native) {\n const native = this.#native.body;\n return new Response(\n native ? wrapResponseWithStreamTiming(native, startTime) : null,\n init\n );\n }\n const body = this.#take();\n return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;\n },\n };\n }\n\n /**\n * srvx's protocol for a response with a Node body: srvx pipes `body` into\n * `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`\n * list, as srvx's own `NodeResponse` returns them.\n */\n _toNodeResponse(): {\n status: number;\n statusText: string;\n headers: string[];\n body: Readable | ReadableStream<Uint8Array> | null;\n } {\n const headers: string[] = [];\n for (const [name, value] of this.headers) headers.push(name, value);\n return {\n status: this.status,\n statusText: this.statusText,\n headers,\n body: this.#native ? this.#native.body : this.#take(),\n };\n }\n\n // ─── Web API: convert once, then behave natively ─────────────────────────\n\n get body(): Response['body'] {\n return this.#toNative().body;\n }\n\n get bodyUsed(): boolean {\n return this.#native ? this.#native.bodyUsed : this.#taken;\n }\n\n /**\n * The other half of srvx's protocol: srvx/bun and srvx/deno send\n * `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),\n * and their runtimes stream Web bodies natively. Converts once.\n */\n get _response(): Response {\n return this.#toNative();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.#toNative().arrayBuffer();\n }\n\n blob(): Promise<Blob> {\n return this.#toNative().blob();\n }\n\n // Built from arrayBuffer(): its type satisfies both lib.dom's `bytes()` and\n // the Workers types', which some importers (the website) merge in.\n bytes(): Promise<Uint8Array<ArrayBuffer>> {\n return this.#toNative()\n .arrayBuffer()\n .then((buffer) => new Uint8Array(buffer));\n }\n\n formData(): Promise<FormData> {\n return this.#toNative().formData();\n }\n\n json(): Promise<unknown> {\n return this.#toNative().json();\n }\n\n text(): Promise<string> {\n return this.#toNative().text();\n }\n\n clone(): Response {\n return this.#toNative().clone();\n }\n}\n\n/** `body` piped through `stream`; an error or destroy on either end tears down both. */\nfunction pipeThrough(body: Readable, stream: Duplex): Duplex {\n stream.on('error', ignoreError);\n pipeline(body, stream, ignoreError);\n return stream;\n}\n\n/** A Web body already taken out of this response, back as a Node stream. */\nfunction webToNode(body: ReadableStream<Uint8Array>): Readable {\n return Readable.fromWeb(body as import('node:stream/web').ReadableStream<Uint8Array>);\n}\n\n/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */\nfunction timeBody(body: Readable, startTime: number): Readable {\n const timing = createStreamTimingRecorder(startTime);\n const timed = new Transform({\n transform(chunk: Uint8Array, _encoding, callback) {\n timing.chunk(chunk.byteLength);\n callback(null, chunk);\n },\n flush(callback) {\n timing.end(false);\n callback();\n },\n // Reached by the consumer leaving early (a cancellation) and by the\n // producer failing; the producer path records itself first, below, so a\n // render error is not logged as a disconnect — as the Web wrapper logs it.\n destroy(error, callback) {\n timing.end(true);\n body.destroy(error ?? undefined);\n callback(error);\n },\n });\n timed.on('error', ignoreError);\n body.on('error', (error) => {\n timing.end(false);\n timed.destroy(error);\n });\n body.pipe(timed);\n return timed;\n}\n","/**\n * Node halves of the Flight source helpers in `flight-source.ts`.\n *\n * Only loaded on Node (`flight-source.ts` imports it behind\n * `nodeStreamsPlatform`), so Workers never evaluate it.\n *\n * A Node Flight source is an object-mode `Readable` whose chunks are exactly\n * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short\n * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.\n * The Node Flight client (`createFromNodeStream`) requires every string chunk\n * in its original shape — it throws \"String chunks need to be passed in their\n * original shape\" if one is split or merged — so nothing here splits or\n * concatenates a chunk on its way to a consumer.\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\",\n * §\"Stream Tee\"\n */\n\nimport { Readable, Transform } from 'node:stream';\nimport { NodeBodyResponse } from './node-body-response.ts';\nimport { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';\nimport { onAbortUntil } from './abort-scope.ts';\nimport { RenderTimeoutError } from './render-timeout.ts';\nimport { releaseReason } from './render-utils.ts';\n\n// `String.prototype.toWellFormed` ships in every Node timber supports\n// (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file\n// only runs on Node.\ndeclare global {\n interface String {\n toWellFormed(): string;\n }\n}\n\n/** A chunk of a Node Flight source. */\nexport type NodeFlightChunk = string | Uint8Array;\n\n/** The part of React's `PipeableStream` a Flight render hands us. */\nexport interface PipeableFlight {\n pipe<T extends NodeJS.WritableStream>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\n/**\n * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits\n * `'error'`, and a stream whose consumer already detached (an iterator that\n * returned, a pipeline that finished) or has not attached yet would otherwise\n * turn a cancel into an uncaught exception. Real consumers attach their own\n * listeners, which still see every error.\n */\nfunction ignoreError(): void {}\n\n/**\n * Release a Node Flight source: destroy it with `reason`, which aborts the\n * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web\n * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws\n * and never leaves an unhandled `'error'` event, whoever is listening.\n */\nexport function destroyNodeFlight(stream: Readable, reason: unknown): void {\n if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);\n const error =\n reason === undefined || reason === null\n ? undefined\n : reason instanceof Error\n ? reason\n : new Error(String(reason));\n stream.destroy(error);\n}\n\n/** When a Node Flight render is aborted, besides its consumer cancelling. */\nexport interface NodeFlightAbort {\n /** The request's signal (client disconnect). */\n signal?: AbortSignal;\n /** Abort with a `RenderTimeoutError` after this long, if still rendering. */\n timeoutMs?: number;\n}\n\n/**\n * Pipe a Flight render into an object-mode Node source.\n *\n * - Strings pass through `toWellFormed()`, as Next does\n * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline\n * copy round-trips through JSON + `TextEncoder`, which turns a lone\n * surrogate into U+FFFD, so without it SSR and hydration see different\n * text. Length in UTF-16 units is unchanged, so a text row's length header\n * still holds.\n * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the\n * request signal fires, when `timeoutMs` passes (design/02 §\"Always Wire\n * abort() to Both Request Signal AND Timeout\"), and when the source is\n * destroyed (a consumer cancelling), with the destroy reason — the reason a\n * Web `cancel(reason)` hands Flight. The listener and the timer are\n * released when the source closes.\n */\nexport function pipeFlightToNode(\n flight: PipeableFlight,\n { signal, timeoutMs }: NodeFlightAbort\n): Readable {\n const scope = new AbortController();\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),\n timeoutMs\n );\n const stream = new Transform({\n objectMode: true,\n transform(chunk: NodeFlightChunk, _encoding, callback) {\n callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);\n },\n destroy(error, callback) {\n scope.abort();\n clearTimeout(timer);\n // A no-op once Flight has finished (it ignores abort after close). A\n // release without a reason aborts with an AbortError, so the render's\n // onError does not log the abort (releaseReason, TIM-1597).\n flight.abort(releaseReason(error));\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n // The listener lasts until the stream is destroyed (server/abort-scope.ts).\n onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);\n flight.pipe(stream);\n return stream;\n}\n\n/** Bytes a chunk occupies, for the tee's divergence guard. */\nfunction chunkByteLength(chunk: NodeFlightChunk): number {\n return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n}\n\n/**\n * Tee a Node Flight source into two object-mode branches, with the contract\n * of `teeWithErrorPropagation` (`stream-utils.ts`):\n *\n * - Each branch has its own queue, so the lagging branch buffers without\n * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted\n * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:\n * the inline branch is not read until Fizz emits its first HTML chunk, and\n * Fizz needs SSR to consume Flight first, so a `pipe()` into two\n * PassThroughs would deadlock once the inline one filled.\n * - The source is read at the pace of the faster branch (paused only while\n * neither branch wants data), like a Web `tee()`.\n * - An error on the source, or a branch destroyed before it ended, destroys\n * the other branch with an error and destroys the source — which aborts the\n * render — so neither consumer hangs and both are released.\n */\nexport function teeNodeFlight(\n source: Readable,\n maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES\n): [Readable, Readable] {\n interface Branch {\n readable: Readable;\n queue: Array<NodeFlightChunk | null>;\n /**\n * Bytes this branch holds that its consumer has not read: the queue, plus\n * chunks pushed into the readable and still in its buffer.\n */\n heldBytes: number;\n /**\n * Sizes of the chunks pushed into the readable, oldest first, until the\n * consumer reads them. In object mode `readableLength` counts buffered\n * chunks, so any beyond it at the front have been consumed.\n */\n pushedSizes: number[];\n /** `_read` was called and nothing has been pushed since. */\n wanting: boolean;\n }\n\n let tornDown = false;\n const branches: [Branch, Branch] = [createBranch(), createBranch()];\n\n function createBranch(): Branch {\n const branch: Branch = {\n readable: new Readable({\n objectMode: true,\n read() {\n settle(branch);\n branch.wanting = true;\n drain(branch);\n },\n destroy(error, callback) {\n // A branch that ended normally releases nothing; one destroyed\n // early (its consumer cancelled, or teardown) takes the rest down.\n if (!branch.readable.readableEnded) {\n teardown(error ?? new Error('RSC stream tee branch cancelled'), error);\n }\n callback(error);\n },\n }),\n queue: [],\n heldBytes: 0,\n pushedSizes: [],\n wanting: false,\n };\n branch.readable.on('error', ignoreError);\n return branch;\n }\n\n /** Stop counting the pushed chunks the consumer has read. */\n function settle(branch: Branch): void {\n while (branch.pushedSizes.length > branch.readable.readableLength) {\n branch.heldBytes -= branch.pushedSizes.shift() ?? 0;\n }\n }\n\n function drain(branch: Branch): void {\n while (branch.wanting) {\n const chunk = branch.queue.shift();\n if (chunk === undefined) break;\n if (chunk === null) {\n branch.wanting = false;\n branch.readable.push(null);\n return;\n }\n branch.pushedSizes.push(chunkByteLength(chunk));\n branch.wanting = branch.readable.push(chunk);\n }\n if (branch.wanting && source.isPaused()) source.resume();\n }\n\n /**\n * Destroy both branches and the source. `branchError` is what the branches'\n * consumers see; `sourceReason` is what Flight is aborted with — the\n * consumer's own cancel reason, which may be `undefined`, as with a Web tee.\n */\n function teardown(branchError: Error, sourceReason: Error | null | undefined): void {\n if (tornDown) return;\n tornDown = true;\n source.off('data', onData);\n for (const branch of branches) {\n branch.queue.length = 0;\n branch.heldBytes = 0;\n branch.pushedSizes.length = 0;\n if (!branch.readable.destroyed) branch.readable.destroy(branchError);\n }\n source.destroy(sourceReason ?? undefined);\n }\n\n function onData(chunk: NodeFlightChunk): void {\n const bytes = chunkByteLength(chunk);\n for (const branch of branches) {\n branch.queue.push(chunk);\n branch.heldBytes += bytes;\n drain(branch);\n }\n // What the lagging branch holds is the divergence between the two.\n for (const branch of branches) settle(branch);\n const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);\n if (divergence > maxBufferBytes) {\n const error = teeBufferExceeded(maxBufferBytes, divergence);\n teardown(error, error);\n return;\n }\n if (!branches[0].wanting && !branches[1].wanting) source.pause();\n }\n\n const finished = finishedState(source);\n if (finished) {\n if ('error' in finished) teardown(finished.error, finished.error);\n else for (const branch of branches) branch.readable.push(null);\n return [branches[0].readable, branches[1].readable];\n }\n\n source.on('data', onData);\n source.on('end', () => {\n for (const branch of branches) {\n branch.queue.push(null);\n drain(branch);\n }\n });\n source.on('error', (error: Error) => teardown(error, error));\n source.on('close', () => {\n if (!source.readableEnded) {\n teardown(new Error('RSC stream closed before it ended'), undefined);\n }\n });\n\n return [branches[0].readable, branches[1].readable];\n}\n\n/**\n * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a\n * Node stream all the way to the adapter, which pipes it to the socket\n * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.\n *\n * Every chunk that arrives in one tick goes out as one buffer, with string\n * chunks encoded straight into it. React writes a flush synchronously, and\n * its Node build passes each long row as its own string: a heavy payload\n * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays\n * per write. The body pauses the source while the client is slow (a payload\n * never piles up in memory), destroying it early destroys the source (which\n * aborts the render), and an error or early close on the source ends it.\n * Wired by hand rather than with `pipeline()`, which allocates an\n * AbortController and an error on every finish.\n */\nexport function nodeFlightResponse(source: Readable, init: ResponseInit): Response {\n return new NodeBodyResponse(batchFlightBytes(source), init);\n}\n\n/** Largest batch the payload body coalesces before pushing (and checking backpressure). */\nconst MAX_BATCH_BYTES = 64 * 1024;\n\nfunction batchFlightBytes(source: Readable): Readable {\n let batch: NodeFlightChunk[] = [];\n let batchBytes = 0;\n let scheduled = false;\n // Assigned once the source listeners exist; a body destroyed before then\n // (an already-finished source) has none to remove.\n let detach = (): void => {};\n\n // One allocation per batch: strings are encoded straight into it, at their\n // offset, rather than each into its own array and then copied.\n const emit = (): void => {\n scheduled = false;\n if (batch.length === 0 || bytes.destroyed) return;\n const merged = Buffer.allocUnsafe(batchBytes);\n let offset = 0;\n for (const chunk of batch) {\n if (typeof chunk === 'string') {\n offset += merged.write(chunk, offset);\n } else {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n }\n batch = [];\n batchBytes = 0;\n // Backpressure: a slow client stops the render's output here instead of\n // the whole payload piling up in memory. read() resumes it.\n if (!bytes.push(merged)) source.pause();\n };\n\n const bytes = new Readable({\n read() {\n if (source.isPaused()) source.resume();\n },\n destroy(error, callback) {\n // A batch still queued is dropped, so its microtask pushes nothing.\n batch = [];\n batchBytes = 0;\n detach();\n // The client left early: release the render.\n if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);\n callback(error);\n },\n });\n bytes.on('error', ignoreError);\n\n const finished = finishedState(source);\n if (finished) {\n // A finished source emits no more events for the wiring below to see.\n if ('error' in finished) bytes.destroy(finished.error);\n else bytes.push(null);\n return bytes;\n }\n\n const onData = (chunk: NodeFlightChunk): void => {\n batch.push(chunk);\n batchBytes += chunkByteLength(chunk);\n // A flush that writes a lot in one tick goes out in capped batches, so\n // backpressure can pause the source mid-flush instead of after it.\n if (batchBytes >= MAX_BATCH_BYTES) {\n emit();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(emit);\n }\n };\n const onEnd = (): void => {\n emit();\n bytes.push(null);\n };\n const onError = (error: Error): void => {\n bytes.destroy(error);\n };\n const onClose = (): void => {\n if (!source.readableEnded) {\n bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));\n }\n };\n detach = (): void => {\n source.off('data', onData);\n source.off('end', onEnd);\n source.off('error', onError);\n source.off('close', onClose);\n };\n source.on('data', onData);\n source.on('end', onEnd);\n source.on('error', onError);\n source.on('close', onClose);\n return bytes;\n}\n\n/**\n * Why `source` will never emit again, if it was destroyed or ended before a\n * consumer attached: `'end'`, `'error'` and `'close'` have already fired,\n * so a consumer that only listens would wait forever. `null` while live.\n */\nfunction finishedState(source: Readable): { ended: true } | { error: Error } | null {\n if (source.readableEnded) return { ended: true };\n if (!source.destroyed) return null;\n return { error: source.errored ?? new Error('RSC stream closed before it ended') };\n}\n\n/**\n * Settles once a chunk (or the end) can be read from `source`, without\n * consuming it: the chunk stays in the source for whatever reads it next.\n * Rejects if the source errors first.\n *\n * The `'readable'` listener is removed on settle; Node restores the stream's\n * flowing state on the next tick, so a consumer attached afterwards (a pipe,\n * a `'data'` listener) still starts it.\n */\nexport function whenNodeFlightReadable(source: Readable): Promise<void> {\n if (source.readableLength > 0) return Promise.resolve();\n const finished = finishedState(source);\n if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const settle = (error?: Error): void => {\n source.off('readable', onReadable);\n source.off('error', settle);\n source.off('close', onClose);\n if (error) reject(error);\n else resolve();\n };\n const onReadable = (): void => settle();\n const onClose = (): void => settle(source.errored ?? undefined);\n source.on('readable', onReadable);\n source.on('error', settle);\n source.on('close', onClose);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAE5D,SAASA,gBAAoB,CAAC;;AAG9B,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,KAAK,UAAU,OAAO,CAAC,CAAC,SAASA,aAAW,GAAG,KAAK,GAAG,SAASA,aAAW;CAChF,KAAK,QAAQ;AACf;AAEA,IAAa,mBAAb,MAAa,yBAAyB,SAAS;CAC7C;CACA,UAA2B;;CAE3B,SAAS;CAET,YAAY,MAAgB,MAAqB;EAC/C,MAAM,MAAM,IAAI;EAChB,IAAI,mBAAmB,IAAI,KAAK,MAAM,GAAG;GACvC,YAAY,IAAI;GAChB,KAAK,QAAQ;EACf,OACE,KAAK,QAAQ;CAEjB;;CAGA,QAAyB;EACvB,MAAM,OAAO,KAAK;EAClB,IAAI,MAAM,KAAK,SAAS;EACxB,KAAK,QAAQ;EACb,OAAO;CACT;;;;;;CAOA,YAAsB;EACpB,IAAI,CAAC,KAAK,SAAS;GACjB,IAAI,KAAK,QAAQ,MAAM,IAAI,UAAU,8CAA8C;GACnF,MAAM,OAAO,KAAK;GAClB,KAAK,QAAQ;GACb,KAAK,UAAU,IAAI,SACjB,OAAQ,SAAS,MAAM,IAAI,IAAmC,MAC9D;IACE,QAAQ,KAAK;IACb,YAAY,KAAK;IACjB,SAAS,KAAK;GAChB,CACF;EACF;EACA,OAAO,KAAK;CACd;CAEA,KAAK,aAA0B;EAC7B,OAAO;GACL,SAAS,KAAK,UAAU,KAAK,QAAQ,SAAS,OAAO,KAAK,UAAU;GACpE,SAAS,SAA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AAI,MAAM,mCAAmC,CAAC;CAElF;CACA,eAAqB;EACnB,OAAO,IAAI,QAAQ,MAAM;EACzB,OAAO,IAAI,OAAO,KAAK;EACvB,OAAO,IAAI,SAAS,OAAO;EAC3B,OAAO,IAAI,SAAS,OAAO;CAC7B;CACA,OAAO,GAAG,QAAQ,MAAM;CACxB,OAAO,GAAG,OAAO,KAAK;CACtB,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO,GAAG,SAAS,OAAO;CAC1B,OAAO;AACT;;;;;;AAOA,SAAS,cAAc,QAA6D;CAClF,IAAI,OAAO,eAAe,OAAO,EAAE,OAAO,KAAK;CAC/C,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,OAAO,EAAE,OAAO,OAAO,2BAAW,IAAI,MAAM,mCAAmC,EAAE;AACnF;;;;;;;;;;AAWA,SAAgB,uBAAuB,QAAiC;CACtE,IAAI,OAAO,iBAAiB,GAAG,OAAO,QAAQ,QAAQ;CACtD,MAAM,WAAW,cAAc,MAAM;CACrC,IAAI,UAAU,OAAO,WAAW,WAAW,QAAQ,OAAO,SAAS,KAAK,IAAI,QAAQ,QAAQ;CAC5F,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,MAAM,UAAU,UAAwB;GACtC,OAAO,IAAI,YAAY,UAAU;GACjC,OAAO,IAAI,SAAS,MAAM;GAC1B,OAAO,IAAI,SAAS,OAAO;GAC3B,IAAI,OAAO,OAAO,KAAK;QAClB,QAAQ;EACf;EACA,MAAM,mBAAyB,OAAO;EACtC,MAAM,gBAAsB,OAAO,OAAO,WAAW,KAAA,CAAS;EAC9D,OAAO,GAAG,YAAY,UAAU;EAChC,OAAO,GAAG,SAAS,MAAM;EACzB,OAAO,GAAG,SAAS,OAAO;CAC5B,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"flight-source-node-BGanuoSS.js","names":["ignoreError"],"sources":["../../src/server/node-body-response.ts","../../src/server/flight-source-node.ts"],"sourcesContent":["/**\n * `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a\n * response built on Node streams reaches the socket without a Web Streams\n * round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.\n *\n * The status and headers are an ordinary `Response`'s. The body stays a Node\n * stream until one of two things takes it:\n *\n * - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and\n * the dev server send with srvx; nitro-preview's sender speaks it too). The\n * stream is piped straight into `ServerResponse`.\n * - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …\n * The response then converts its body once, with `Readable.toWeb`, and\n * behaves as a native `Response` from then on. Correct anywhere, so code\n * that does not know about Node bodies keeps working; pipeline code on the\n * hot path goes through `node-response.ts` instead, which never converts.\n *\n * Pattern from srvx's `NodeResponse` (`FastResponse`).\n *\n * Design doc: 02-rendering-pipeline.md §\"Response Bodies on Node\"\n */\n\nimport { Readable, Transform, pipeline, type Duplex } from 'node:stream';\nimport { NODE_BODY, type NodeBodyOps } from './node-response.ts';\nimport { createStreamTimingRecorder, wrapResponseWithStreamTiming } from './stream-utils.ts';\n\n/** Statuses whose responses carry no body (Fetch \"null body status\"). */\nconst NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);\n\nfunction ignoreError(): void {}\n\n/** Destroy a body nothing will read, without an unhandled `'error'`. */\nfunction destroyBody(body: Readable): void {\n if (!body.listeners('error').includes(ignoreError)) body.on('error', ignoreError);\n body.destroy();\n}\n\nexport class NodeBodyResponse extends Response {\n #body: Readable | null;\n #native: Response | null = null;\n /** An adapter or a pipeline op took the body: it is used, as a read one is. */\n #taken = false;\n\n constructor(body: Readable, init?: ResponseInit) {\n super(null, init);\n if (NULL_BODY_STATUSES.has(this.status)) {\n destroyBody(body);\n this.#body = null;\n } else {\n this.#body = body;\n }\n }\n\n /** Take the Node body; this response no longer has it. */\n #take(): Readable | null {\n const body = this.#body;\n if (body) this.#taken = true;\n this.#body = null;\n return body;\n }\n\n /**\n * This response as a native one, converting the Node body once. Throws, as\n * a native Response whose body was read does, if something already took\n * the body (an adapter, a re-wrap), rather than reading as empty.\n */\n #toNative(): Response {\n if (!this.#native) {\n if (this.#taken) throw new TypeError('Body is unusable: Body has already been read');\n const body = this.#body;\n this.#body = null;\n this.#native = new Response(\n body ? (Readable.toWeb(body) as ReadableStream<Uint8Array>) : null,\n {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n }\n );\n }\n return this.#native;\n }\n\n get [NODE_BODY](): NodeBodyOps {\n return {\n hasBody: this.#native ? this.#native.body !== null : this.#body !== null,\n rewrap: (init) => {\n if (this.#native) return new Response(this.#native.body, init);\n const body = this.#take();\n return body ? new NodeBodyResponse(body, init) : new Response(null, init);\n },\n discard: () => {\n if (this.#native) {\n this.#native.body?.cancel().catch(() => {});\n return;\n }\n const body = this.#take();\n if (body) destroyBody(body);\n },\n through: (stream, init) => {\n const body = this.#native\n ? this.#native.body && webToNode(this.#native.body)\n : this.#take();\n return body\n ? new NodeBodyResponse(pipeThrough(body, stream), init)\n : new Response(null, init);\n },\n timed: (startTime) => {\n const init = { status: this.status, statusText: this.statusText, headers: this.headers };\n if (this.#native) {\n const native = this.#native.body;\n return new Response(\n native ? wrapResponseWithStreamTiming(native, startTime) : null,\n init\n );\n }\n const body = this.#take();\n return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;\n },\n };\n }\n\n /**\n * srvx's protocol for a response with a Node body: srvx pipes `body` into\n * `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`\n * list, as srvx's own `NodeResponse` returns them.\n */\n _toNodeResponse(): {\n status: number;\n statusText: string;\n headers: string[];\n body: Readable | ReadableStream<Uint8Array> | null;\n } {\n const headers: string[] = [];\n for (const [name, value] of this.headers) headers.push(name, value);\n return {\n status: this.status,\n statusText: this.statusText,\n headers,\n body: this.#native ? this.#native.body : this.#take(),\n };\n }\n\n // ─── Web API: convert once, then behave natively ─────────────────────────\n\n get body(): Response['body'] {\n return this.#toNative().body;\n }\n\n get bodyUsed(): boolean {\n return this.#native ? this.#native.bodyUsed : this.#taken;\n }\n\n /**\n * The other half of srvx's protocol: srvx/bun and srvx/deno send\n * `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),\n * and their runtimes stream Web bodies natively. Converts once.\n */\n get _response(): Response {\n return this.#toNative();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.#toNative().arrayBuffer();\n }\n\n blob(): Promise<Blob> {\n return this.#toNative().blob();\n }\n\n // Built from arrayBuffer(): its type satisfies both lib.dom's `bytes()` and\n // the Workers types', which some importers (the website) merge in.\n bytes(): Promise<Uint8Array<ArrayBuffer>> {\n return this.#toNative()\n .arrayBuffer()\n .then((buffer) => new Uint8Array(buffer));\n }\n\n formData(): Promise<FormData> {\n return this.#toNative().formData();\n }\n\n json(): Promise<unknown> {\n return this.#toNative().json();\n }\n\n text(): Promise<string> {\n return this.#toNative().text();\n }\n\n clone(): Response {\n return this.#toNative().clone();\n }\n}\n\n/** `body` piped through `stream`; an error or destroy on either end tears down both. */\nfunction pipeThrough(body: Readable, stream: Duplex): Duplex {\n stream.on('error', ignoreError);\n pipeline(body, stream, ignoreError);\n return stream;\n}\n\n/** A Web body already taken out of this response, back as a Node stream. */\nfunction webToNode(body: ReadableStream<Uint8Array>): Readable {\n return Readable.fromWeb(body as import('node:stream/web').ReadableStream<Uint8Array>);\n}\n\n/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */\nfunction timeBody(body: Readable, startTime: number): Readable {\n const timing = createStreamTimingRecorder(startTime);\n const timed = new Transform({\n transform(chunk: Uint8Array, _encoding, callback) {\n timing.chunk(chunk.byteLength);\n callback(null, chunk);\n },\n flush(callback) {\n timing.end(false);\n callback();\n },\n // Reached by the consumer leaving early (a cancellation) and by the\n // producer failing; the producer path records itself first, below, so a\n // render error is not logged as a disconnect — as the Web wrapper logs it.\n destroy(error, callback) {\n timing.end(true);\n body.destroy(error ?? undefined);\n callback(error);\n },\n });\n timed.on('error', ignoreError);\n body.on('error', (error) => {\n timing.end(false);\n timed.destroy(error);\n });\n body.pipe(timed);\n return timed;\n}\n","/**\n * Node halves of the Flight source helpers in `flight-source.ts`.\n *\n * Only loaded on Node (`flight-source.ts` imports it behind\n * `nodeStreamsPlatform`), so Workers never evaluate it.\n *\n * A Node Flight source is an object-mode `Readable` whose chunks are exactly\n * what React's `renderToPipeableStream` wrote: `Uint8Array` views for short\n * rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.\n * The Node Flight client (`createFromNodeStream`) requires every string chunk\n * in its original shape — it throws \"String chunks need to be passed in their\n * original shape\" if one is split or merged — so nothing here splits or\n * concatenates a chunk on its way to a consumer.\n *\n * Design doc: 02-rendering-pipeline.md §\"RSC → SSR → Client Hydration\",\n * §\"Stream Tee\"\n */\n\nimport { Readable, Transform } from 'node:stream';\nimport { NodeBodyResponse } from './node-body-response.ts';\nimport { DEFAULT_MAX_BUFFER_BYTES, teeBufferExceeded } from './stream-utils.ts';\nimport { onAbortUntil } from './abort-scope.ts';\nimport { RenderTimeoutError } from './render-timeout.ts';\nimport { releaseReason } from './render-utils.ts';\n\n// `String.prototype.toWellFormed` ships in every Node timber supports\n// (engines: >=22.18) but is ES2024, past the project's ES2022 lib; this file\n// only runs on Node.\ndeclare global {\n interface String {\n toWellFormed(): string;\n }\n}\n\n/** A chunk of a Node Flight source. */\nexport type NodeFlightChunk = string | Uint8Array;\n\n/** The part of React's `PipeableStream` a Flight render hands us. */\nexport interface PipeableFlight {\n pipe<T extends NodeJS.WritableStream>(destination: T): T;\n abort(reason?: unknown): void;\n}\n\n/**\n * Every stream here carries one no-op `'error'` listener. `destroy(err)` emits\n * `'error'`, and a stream whose consumer already detached (an iterator that\n * returned, a pipeline that finished) or has not attached yet would otherwise\n * turn a cancel into an uncaught exception. Real consumers attach their own\n * listeners, which still see every error.\n */\nfunction ignoreError(): void {}\n\n/**\n * Release a Node Flight source: destroy it with `reason`, which aborts the\n * render behind it. Cancellation reasons in the pipeline are `unknown` (a Web\n * `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws\n * and never leaves an unhandled `'error'` event, whoever is listening.\n */\nexport function destroyNodeFlight(stream: Readable, reason: unknown): void {\n if (!stream.listeners('error').includes(ignoreError)) stream.on('error', ignoreError);\n const error =\n reason === undefined || reason === null\n ? undefined\n : reason instanceof Error\n ? reason\n : new Error(String(reason));\n stream.destroy(error);\n}\n\n/** When a Node Flight render is aborted, besides its consumer cancelling. */\nexport interface NodeFlightAbort {\n /** The request's signal (client disconnect). */\n signal?: AbortSignal;\n /** Abort with a `RenderTimeoutError` after this long, if still rendering. */\n timeoutMs?: number;\n}\n\n/**\n * Pipe a Flight render into an object-mode Node source.\n *\n * - Strings pass through `toWellFormed()`, as Next does\n * (`renderToNodeFlightStream`): SSR decodes the raw string while the inline\n * copy round-trips through JSON + `TextEncoder`, which turns a lone\n * surrogate into U+FFFD, so without it SSR and hydration see different\n * text. Length in UTF-16 units is unchanged, so a text row's length header\n * still holds.\n * - `renderToPipeableStream` takes no `signal`. `abort()` is called when the\n * request signal fires, when `timeoutMs` passes (design/02 §\"Always Wire\n * abort() to Both Request Signal AND Timeout\"), and when the source is\n * destroyed (a consumer cancelling), with the destroy reason — the reason a\n * Web `cancel(reason)` hands Flight. The listener and the timer are\n * released when the source closes.\n */\nexport function pipeFlightToNode(\n flight: PipeableFlight,\n { signal, timeoutMs }: NodeFlightAbort\n): Readable {\n const scope = new AbortController();\n const timer =\n timeoutMs === undefined\n ? undefined\n : setTimeout(\n () => flight.abort(new RenderTimeoutError(timeoutMs, 'Flight render')),\n timeoutMs\n );\n const stream = new Transform({\n objectMode: true,\n transform(chunk: NodeFlightChunk, _encoding, callback) {\n callback(null, typeof chunk === 'string' ? chunk.toWellFormed() : chunk);\n },\n destroy(error, callback) {\n scope.abort();\n clearTimeout(timer);\n // A no-op once Flight has finished (it ignores abort after close). A\n // release without a reason aborts with an AbortError, so the render's\n // onError does not log the abort (releaseReason, TIM-1597).\n flight.abort(releaseReason(error));\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n // The listener lasts until the stream is destroyed (server/abort-scope.ts).\n onAbortUntil(signal, () => flight.abort(signal?.reason), scope.signal);\n flight.pipe(stream);\n return stream;\n}\n\n/** Bytes a chunk occupies, for the tee's divergence guard. */\nfunction chunkByteLength(chunk: NodeFlightChunk): number {\n return typeof chunk === 'string' ? Buffer.byteLength(chunk) : chunk.byteLength;\n}\n\n/**\n * Tee a Node Flight source into two object-mode branches, with the contract\n * of `teeWithErrorPropagation` (`stream-utils.ts`):\n *\n * - Each branch has its own queue, so the lagging branch buffers without\n * bound until the divergence guard (`maxBufferBytes`, default 5MB, counted\n * in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:\n * the inline branch is not read until Fizz emits its first HTML chunk, and\n * Fizz needs SSR to consume Flight first, so a `pipe()` into two\n * PassThroughs would deadlock once the inline one filled.\n * - The source is read at the pace of the faster branch (paused only while\n * neither branch wants data), like a Web `tee()`.\n * - An error on the source, or a branch destroyed before it ended, destroys\n * the other branch with an error and destroys the source — which aborts the\n * render — so neither consumer hangs and both are released.\n */\nexport function teeNodeFlight(\n source: Readable,\n maxBufferBytes: number = DEFAULT_MAX_BUFFER_BYTES\n): [Readable, Readable] {\n interface Branch {\n readable: Readable;\n queue: Array<NodeFlightChunk | null>;\n /**\n * Bytes this branch holds that its consumer has not read: the queue, plus\n * chunks pushed into the readable and still in its buffer.\n */\n heldBytes: number;\n /**\n * Sizes of the chunks pushed into the readable, oldest first, until the\n * consumer reads them. In object mode `readableLength` counts buffered\n * chunks, so any beyond it at the front have been consumed.\n */\n pushedSizes: number[];\n /** `_read` was called and nothing has been pushed since. */\n wanting: boolean;\n }\n\n let tornDown = false;\n const branches: [Branch, Branch] = [createBranch(), createBranch()];\n\n function createBranch(): Branch {\n const branch: Branch = {\n readable: new Readable({\n objectMode: true,\n read() {\n settle(branch);\n branch.wanting = true;\n drain(branch);\n },\n destroy(error, callback) {\n // A branch that ended normally releases nothing; one destroyed\n // early (its consumer cancelled, or teardown) takes the rest down.\n if (!branch.readable.readableEnded) {\n teardown(error ?? new Error('RSC stream tee branch cancelled'), error);\n }\n callback(error);\n },\n }),\n queue: [],\n heldBytes: 0,\n pushedSizes: [],\n wanting: false,\n };\n branch.readable.on('error', ignoreError);\n return branch;\n }\n\n /** Stop counting the pushed chunks the consumer has read. */\n function settle(branch: Branch): void {\n while (branch.pushedSizes.length > branch.readable.readableLength) {\n branch.heldBytes -= branch.pushedSizes.shift() ?? 0;\n }\n }\n\n function drain(branch: Branch): void {\n while (branch.wanting) {\n const chunk = branch.queue.shift();\n if (chunk === undefined) break;\n if (chunk === null) {\n branch.wanting = false;\n branch.readable.push(null);\n return;\n }\n branch.pushedSizes.push(chunkByteLength(chunk));\n branch.wanting = branch.readable.push(chunk);\n }\n if (branch.wanting && source.isPaused()) source.resume();\n }\n\n /**\n * Destroy both branches and the source. `branchError` is what the branches'\n * consumers see; `sourceReason` is what Flight is aborted with — the\n * consumer's own cancel reason, which may be `undefined`, as with a Web tee.\n */\n function teardown(branchError: Error, sourceReason: Error | null | undefined): void {\n if (tornDown) return;\n tornDown = true;\n source.off('data', onData);\n for (const branch of branches) {\n branch.queue.length = 0;\n branch.heldBytes = 0;\n branch.pushedSizes.length = 0;\n if (!branch.readable.destroyed) branch.readable.destroy(branchError);\n }\n source.destroy(sourceReason ?? undefined);\n }\n\n function onData(chunk: NodeFlightChunk): void {\n const bytes = chunkByteLength(chunk);\n for (const branch of branches) {\n branch.queue.push(chunk);\n branch.heldBytes += bytes;\n drain(branch);\n }\n // What the lagging branch holds is the divergence between the two.\n for (const branch of branches) settle(branch);\n const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);\n if (divergence > maxBufferBytes) {\n const error = teeBufferExceeded(maxBufferBytes, divergence);\n teardown(error, error);\n return;\n }\n if (!branches[0].wanting && !branches[1].wanting) source.pause();\n }\n\n const finished = finishedState(source);\n if (finished) {\n if ('error' in finished) teardown(finished.error, finished.error);\n else for (const branch of branches) branch.readable.push(null);\n return [branches[0].readable, branches[1].readable];\n }\n\n source.on('data', onData);\n source.on('end', () => {\n for (const branch of branches) {\n branch.queue.push(null);\n drain(branch);\n }\n });\n source.on('error', (error: Error) => teardown(error, error));\n source.on('close', () => {\n if (!source.readableEnded) {\n teardown(new Error('RSC stream closed before it ended'), undefined);\n }\n });\n\n return [branches[0].readable, branches[1].readable];\n}\n\n/**\n * A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a\n * Node stream all the way to the adapter, which pipes it to the socket\n * (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.\n *\n * Every chunk that arrives in one tick goes out as one buffer, with string\n * chunks encoded straight into it. React writes a flush synchronously, and\n * its Node build passes each long row as its own string: a heavy payload\n * arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays\n * per write. The body pauses the source while the client is slow (a payload\n * never piles up in memory), destroying it early destroys the source (which\n * aborts the render), and an error or early close on the source ends it.\n * Wired by hand rather than with `pipeline()`, which allocates an\n * AbortController and an error on every finish.\n */\nexport function nodeFlightResponse(source: Readable, init: ResponseInit): Response {\n return new NodeBodyResponse(batchFlightBytes(source), init);\n}\n\n/** Largest batch the payload body coalesces before pushing (and checking backpressure). */\nconst MAX_BATCH_BYTES = 64 * 1024;\n\nfunction batchFlightBytes(source: Readable): Readable {\n let batch: NodeFlightChunk[] = [];\n let batchBytes = 0;\n let scheduled = false;\n // Assigned once the source listeners exist; a body destroyed before then\n // (an already-finished source) has none to remove.\n let detach = (): void => {};\n\n // One allocation per batch: strings are encoded straight into it, at their\n // offset, rather than each into its own array and then copied.\n const emit = (): void => {\n scheduled = false;\n if (batch.length === 0 || bytes.destroyed) return;\n const merged = Buffer.allocUnsafe(batchBytes);\n let offset = 0;\n for (const chunk of batch) {\n if (typeof chunk === 'string') {\n offset += merged.write(chunk, offset);\n } else {\n merged.set(chunk, offset);\n offset += chunk.byteLength;\n }\n }\n batch = [];\n batchBytes = 0;\n // Backpressure: a slow client stops the render's output here instead of\n // the whole payload piling up in memory. read() resumes it.\n if (!bytes.push(merged)) source.pause();\n };\n\n const bytes = new Readable({\n read() {\n if (source.isPaused()) source.resume();\n },\n destroy(error, callback) {\n // A batch still queued is dropped, so its microtask pushes nothing.\n batch = [];\n batchBytes = 0;\n detach();\n // The client left early: release the render.\n if (!source.readableEnded) destroyNodeFlight(source, error ?? undefined);\n callback(error);\n },\n });\n bytes.on('error', ignoreError);\n\n const finished = finishedState(source);\n if (finished) {\n // A finished source emits no more events for the wiring below to see.\n if ('error' in finished) bytes.destroy(finished.error);\n else bytes.push(null);\n return bytes;\n }\n\n const onData = (chunk: NodeFlightChunk): void => {\n batch.push(chunk);\n batchBytes += chunkByteLength(chunk);\n // A flush that writes a lot in one tick goes out in capped batches, so\n // backpressure can pause the source mid-flush instead of after it.\n if (batchBytes >= MAX_BATCH_BYTES) {\n emit();\n } else if (!scheduled) {\n scheduled = true;\n queueMicrotask(emit);\n }\n };\n const onEnd = (): void => {\n emit();\n bytes.push(null);\n };\n const onError = (error: Error): void => {\n bytes.destroy(error);\n };\n const onClose = (): void => {\n if (!source.readableEnded) {\n bytes.destroy(source.errored ?? new Error('RSC stream closed before it ended'));\n }\n };\n detach = (): void => {\n source.off('data', onData);\n source.off('end', onEnd);\n source.off('error', onError);\n source.off('close', onClose);\n };\n source.on('data', onData);\n source.on('end', onEnd);\n source.on('error', onError);\n source.on('close', onClose);\n return bytes;\n}\n\n/**\n * Why `source` will never emit again, if it was destroyed or ended before a\n * consumer attached: `'end'`, `'error'` and `'close'` have already fired,\n * so a consumer that only listens would wait forever. `null` while live.\n */\nfunction finishedState(source: Readable): { ended: true } | { error: Error } | null {\n if (source.readableEnded) return { ended: true };\n if (!source.destroyed) return null;\n return { error: source.errored ?? new Error('RSC stream closed before it ended') };\n}\n\n/**\n * Settles once a chunk (or the end) can be read from `source`, without\n * consuming it: the chunk stays in the source for whatever reads it next.\n * Rejects if the source errors first.\n *\n * The `'readable'` listener is removed on settle; Node restores the stream's\n * flowing state on the next tick, so a consumer attached afterwards (a pipe,\n * a `'data'` listener) still starts it.\n */\nexport function whenNodeFlightReadable(source: Readable): Promise<void> {\n if (source.readableLength > 0) return Promise.resolve();\n const finished = finishedState(source);\n if (finished) return 'error' in finished ? Promise.reject(finished.error) : Promise.resolve();\n return new Promise<void>((resolve, reject) => {\n const settle = (error?: Error): void => {\n source.off('readable', onReadable);\n source.off('error', settle);\n source.off('close', onClose);\n if (error) reject(error);\n else resolve();\n };\n const onReadable = (): void => settle();\n const onClose = (): void => settle(source.errored ?? undefined);\n source.on('readable', onReadable);\n source.on('error', settle);\n source.on('close', onClose);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,IAAM,qCAAqB,IAAI,IAAI;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG,CAAC;AAE5D,SAASA,gBAAoB,CAAC;;AAG9B,SAAS,YAAY,MAAsB;CACzC,IAAI,CAAC,KAAK,UAAU,OAAO,CAAC,CAAC,SAASA,aAAW,GAAG,KAAK,GAAG,SAASA,aAAW;CAChF,KAAK,QAAQ;AACf;AAEA,IAAa,mBAAb,MAAa,yBAAyB,SAAS;CAC7C;CACA,UAA2B;;CAE3B,SAAS;CAET,YAAY,MAAgB,MAAqB;EAC/C,MAAM,MAAM,IAAI;EAChB,IAAI,mBAAmB,IAAI,KAAK,MAAM,GAAG;GACvC,YAAY,IAAI;GAChB,KAAK,QAAQ;EACf,OACE,KAAK,QAAQ;CAEjB;;CAGA,QAAyB;EACvB,MAAM,OAAO,KAAK;EAClB,IAAI,MAAM,KAAK,SAAS;EACxB,KAAK,QAAQ;EACb,OAAO;CACT;;;;;;CAOA,YAAsB;EACpB,IAAI,CAAC,KAAK,SAAS;GACjB,IAAI,KAAK,QAAQ,MAAM,IAAI,UAAU,8CAA8C;GACnF,MAAM,OAAO,KAAK;GAClB,KAAK,QAAQ;GACb,KAAK,UAAU,IAAI,SACjB,OAAQ,SAAS,MAAM,IAAI,IAAmC,MAC9D;IACE,QAAQ,KAAK;IACb,YAAY,KAAK;IACjB,SAAS,KAAK;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AC;AACH"}
|
|
@@ -1,4 +1,34 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
+
// src/client/router-url.ts
|
|
3
|
+
/**
|
|
4
|
+
* How the client router reads the URLs it is handed.
|
|
5
|
+
*
|
|
6
|
+
* One parser, so the places that key or compare by URL — the history stack,
|
|
7
|
+
* the navigation state a page renders with, the departing page sent as
|
|
8
|
+
* `X-Timber-URL` — cannot disagree about what a URL says. They did: a
|
|
9
|
+
* history entry stored under `navigate('/café')`'s spelling was looked up
|
|
10
|
+
* under the address bar's `/caf%C3%A9`, and missed (TIM-1541).
|
|
11
|
+
*/
|
|
12
|
+
var BASE = "http://localhost";
|
|
13
|
+
/**
|
|
14
|
+
* Parse a router URL. A URL that starts with "/" is a path — including one
|
|
15
|
+
* that starts with "//": that is the pathname a document at
|
|
16
|
+
* `https://host//a/b` reports, and resolved against a base it would parse as
|
|
17
|
+
* a scheme-relative reference to host `a`. Anything else resolves against a
|
|
18
|
+
* placeholder origin, so an absolute URL keeps its own.
|
|
19
|
+
*/
|
|
20
|
+
function parseRouterUrl(url) {
|
|
21
|
+
return url.startsWith("/") ? new URL(BASE + url) : new URL(url, BASE);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The spelling a URL is stored and looked up under: the browser's own
|
|
25
|
+
* pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one
|
|
26
|
+
* key. The fragment is dropped — it is client-only.
|
|
27
|
+
*/
|
|
28
|
+
function routerUrlKey(url) {
|
|
29
|
+
const parsed = parseRouterUrl(url);
|
|
30
|
+
return parsed.pathname + parsed.search;
|
|
31
|
+
}
|
|
2
32
|
// src/client/global-context.ts
|
|
3
33
|
/**
|
|
4
34
|
* createGlobalContext — a React context with a process-wide singleton identity.
|
|
@@ -42,6 +72,6 @@ function createGlobalContextFor(react, key, defaultValue) {
|
|
|
42
72
|
}
|
|
43
73
|
return ctx;
|
|
44
74
|
}
|
|
45
|
-
export { createGlobalContext as t };
|
|
75
|
+
export { parseRouterUrl as n, routerUrlKey as r, createGlobalContext as t };
|
|
46
76
|
|
|
47
|
-
//# sourceMappingURL=global-context-
|
|
77
|
+
//# sourceMappingURL=global-context-CFSSysdJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"global-context-CFSSysdJ.js","names":[],"sources":["../../src/client/router-url.ts","../../src/client/global-context.ts"],"sourcesContent":["/**\n * How the client router reads the URLs it is handed.\n *\n * One parser, so the places that key or compare by URL — the history stack,\n * the navigation state a page renders with, the departing page sent as\n * `X-Timber-URL` — cannot disagree about what a URL says. They did: a\n * history entry stored under `navigate('/café')`'s spelling was looked up\n * under the address bar's `/caf%C3%A9`, and missed (TIM-1541).\n */\n\nconst BASE = 'http://localhost';\n\n/**\n * Parse a router URL. A URL that starts with \"/\" is a path — including one\n * that starts with \"//\": that is the pathname a document at\n * `https://host//a/b` reports, and resolved against a base it would parse as\n * a scheme-relative reference to host `a`. Anything else resolves against a\n * placeholder origin, so an absolute URL keeps its own.\n */\nexport function parseRouterUrl(url: string): URL {\n return url.startsWith('/') ? new URL(BASE + url) : new URL(url, BASE);\n}\n\n/**\n * The spelling a URL is stored and looked up under: the browser's own\n * pathname + search, so `/a?` and `/a`, `/café` and `/caf%C3%A9`, are one\n * key. The fragment is dropped — it is client-only.\n */\nexport function routerUrlKey(url: string): string {\n const parsed = parseRouterUrl(url);\n return parsed.pathname + parsed.search;\n}\n","/**\n * createGlobalContext — a React context with a process-wide singleton identity.\n *\n * SINGLETON GUARANTEE: Uses globalThis + Symbol.for — same pattern as\n * NavigationContext. The RSC client bundler can duplicate a module across\n * chunks (browser-entry graph + client-reference graph). With ESM output,\n * each chunk gets its own module scope — a bare createContext at module\n * level would create separate instances per chunk. globalThis guarantees a\n * single instance regardless of duplication.\n *\n * One context per React instance, not per process. Duplicated chunks share\n * one React, so they share the context. A dev SSR program reload evaluates\n * React and react-dom/server again, in the same process: the new renderer\n * must get a context of its own. Handed the previous one, React logs\n * \"Detected multiple renderers concurrently rendering the same context\n * provider\" on every client-component edit, and the stale context keeps a\n * piece of the discarded copy alive (TIM-1590).\n *\n * See design/19-client-navigation.md §\"Singleton Guarantee via globalThis\"\n */\n\nimport React from 'react';\n\n/** The part of a React instance a context comes from. */\nexport interface ContextFactory {\n createContext?: typeof React.createContext;\n}\n\n/**\n * The context `key` names for this React instance, created on first use.\n * Pass the key as a `Symbol.for('…')` literal at the call site, so each key\n * stays greppable in the build output (tests/bundle-singleton-audit.test.ts\n * checks `__timber_nav_ctx`).\n */\nexport function createGlobalContext<T>(key: symbol, defaultValue: T): React.Context<T> {\n return createGlobalContextFor(React, key, defaultValue);\n}\n\n/** createGlobalContext for a given React instance. Exported for tests. */\nexport function createGlobalContextFor<T>(\n react: ContextFactory,\n key: symbol,\n defaultValue: T\n): React.Context<T> {\n if (typeof react.createContext !== 'function') {\n // RSC environment — createContext not available. Return a dummy that\n // won't be used (the consumers only render on the client / during SSR).\n return undefined as unknown as React.Context<T>;\n }\n const slot: unknown = Reflect.get(globalThis, key);\n const byReact = slot instanceof WeakMap ? slot : new WeakMap<object, React.Context<T>>();\n if (byReact !== slot) Reflect.set(globalThis, key, byReact);\n let ctx: React.Context<T> | undefined = byReact.get(react);\n if (!ctx) {\n ctx = react.createContext<T>(defaultValue);\n byReact.set(react, ctx);\n }\n return ctx;\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAM,OAAO;;;;;;;;AASb,SAAgB,eAAe,KAAkB;CAC/C,OAAO,IAAI,WAAW,GAAG,IAAI,IAAI,IAAI,OAAO,GAAG,IAAI,IAAI,IAAI,KAAK,IAAI;AACtE;;;;;;AAOA,SAAgB,aAAa,KAAqB;CAChD,MAAM,SAAS,eAAe,GAAG;CACjC,OAAO,OAAO,WAAW,OAAO;AAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACGA,SAAgB,oBAAuB,KAAa,cAAmC;CACrF,OAAO,uBAAuB,OAAO,KAAK,YAAY;AACxD;;AAGA,SAAgB,uBACd,OACA,KACA,cACkB;CAClB,IAAI,OAAO,MAAM,kBAAkB,YAGjC;CAEF,MAAM,OAAgB,QAAQ,IAAI,YAAY,GAAG;CACjD,MAAM,UAAU,gBAAgB,UAAU,uBAAO,IAAI,QAAkC;CACvF,IAAI,YAAY,MAAM,QAAQ,IAAI,YAAY,KAAK,OAAO;CAC1D,IAAI,MAAoC,QAAQ,IAAI,KAAK;CACzD,IAAI,CAAC,KAAK;EACR,MAAM,MAAM,cAAiB,YAAY;EACzC,QAAQ,IAAI,OAAO,GAAG;CACxB;CACA,OAAO;AACT"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { o as logLossyCacheValue } from "./logger-
|
|
1
|
+
import { o as logLossyCacheValue } from "./logger-YtMSKfft.js";
|
|
2
2
|
// src/cache/json-lossy-check.ts
|
|
3
3
|
var LOSSY_TYPES = [
|
|
4
4
|
"Date",
|
|
@@ -62,4 +62,4 @@ function findLossyTypes(value, seen, depth) {
|
|
|
62
62
|
}
|
|
63
63
|
export { warnLossyJsonValue as t };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=json-lossy-check-
|
|
65
|
+
//# sourceMappingURL=json-lossy-check-BXM45k8p.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-lossy-check-
|
|
1
|
+
{"version":3,"file":"json-lossy-check-BXM45k8p.js","names":[],"sources":["../../src/cache/json-lossy-check.ts"],"sourcesContent":["import { logLossyCacheValue } from '../server/logger.ts';\n\nconst LOSSY_TYPES = ['Date', 'Map', 'Set', 'BigInt'] as const;\n\nlet hasWarned = false;\n\n/**\n * Dev-mode warning when a cache value contains types that lose fidelity\n * through JSON round-trip. Only runs in development — no-op in production.\n *\n * Detects: Date (→ ISO string), Map/Set (→ {}), BigInt (→ throws).\n * Emits once per process to avoid log spam.\n */\nexport function warnLossyJsonValue(value: unknown, cacheKey: string): void {\n if (hasWarned) return;\n if (process.env.NODE_ENV === 'production') return;\n\n const lossy = findLossyTypes(value, new Set(), 0);\n if (lossy.size === 0) return;\n\n hasWarned = true;\n logLossyCacheValue({ cacheKey, types: [...lossy].join(', ') });\n}\n\nfunction findLossyTypes(value: unknown, seen: Set<unknown>, depth: number): Set<string> {\n const lossy = new Set<string>();\n if (depth > 8 || value === null || value === undefined) return lossy;\n if (typeof value === 'bigint') {\n lossy.add('BigInt');\n return lossy;\n }\n if (typeof value !== 'object' && typeof value !== 'function') return lossy;\n if (seen.has(value)) return lossy;\n seen.add(value);\n\n if (value instanceof Date) {\n lossy.add('Date');\n return lossy;\n }\n if (value instanceof Map) {\n lossy.add('Map');\n return lossy;\n }\n if (value instanceof Set) {\n lossy.add('Set');\n return lossy;\n }\n\n if (Array.isArray(value)) {\n for (const item of value) {\n for (const t of findLossyTypes(item, seen, depth + 1)) lossy.add(t);\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n }\n\n for (const k of Object.keys(value as Record<string, unknown>)) {\n for (const t of findLossyTypes((value as Record<string, unknown>)[k], seen, depth + 1)) {\n lossy.add(t);\n }\n if (lossy.size === LOSSY_TYPES.length) return lossy;\n }\n return lossy;\n}\n\n/** Reset warning state — for tests only. */\nexport function _resetLossyWarning(): void {\n hasWarned = false;\n}\n"],"mappings":";;AAEA,IAAM,cAAc;CAAC;CAAQ;CAAO;CAAO;AAAQ;AAEnD,IAAI,YAAY;;;;;;;;AAShB,SAAgB,mBAAmB,OAAgB,UAAwB;CACzE,IAAI,WAAW;CACf,IAAA,QAAA,IAAA,aAA6B,cAAc;CAE3C,MAAM,QAAQ,eAAe,uBAAO,IAAI,IAAI,GAAG,CAAC;CAChD,IAAI,MAAM,SAAS,GAAG;CAEtB,YAAY;CACZ,mBAAmB;EAAE;EAAU,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,IAAI;CAAE,CAAC;AAC/D;AAEA,SAAS,eAAe,OAAgB,MAAoB,OAA4B;CACtF,MAAM,wBAAQ,IAAI,IAAY;CAC9B,IAAI,QAAQ,KAAK,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAC/D,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,IAAI,QAAQ;EAClB,OAAO;CACT;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO;CACrE,IAAI,KAAK,IAAI,KAAK,GAAG,OAAO;CAC5B,KAAK,IAAI,KAAK;CAEd,IAAI,iBAAiB,MAAM;EACzB,MAAM,IAAI,MAAM;EAChB,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CACA,IAAI,iBAAiB,KAAK;EACxB,MAAM,IAAI,KAAK;EACf,OAAO;CACT;CAEA,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,KAAK,MAAM,QAAQ,OAAO;GACxB,KAAK,MAAM,KAAK,eAAe,MAAM,MAAM,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC;GAClE,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;EAChD;EACA,OAAO;CACT;CAEA,KAAK,MAAM,KAAK,OAAO,KAAK,KAAgC,GAAG;EAC7D,KAAK,MAAM,KAAK,eAAgB,MAAkC,IAAI,MAAM,QAAQ,CAAC,GACnF,MAAM,IAAI,CAAC;EAEb,IAAI,MAAM,SAAS,YAAY,QAAQ,OAAO;CAChD;CACA,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { i as scanProjectSourceFiles, t as buildSourceExtensions } from "./scan-CyizcBiX.js";
|
|
2
|
-
import { i as detectDirective, n as classifyModule } from "./classify-
|
|
3
|
-
import { n as stitchImportChains } from "./chains-
|
|
4
|
-
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-
|
|
2
|
+
import { i as detectDirective, n as classifyModule } from "./classify-_W0RWa5w.js";
|
|
3
|
+
import { n as stitchImportChains } from "./chains-D-RRc7CM.js";
|
|
4
|
+
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-CRSP06Es.js";
|
|
5
5
|
import { normalizePath } from "vite";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { readFile } from "node:fs/promises";
|
|
@@ -147,4 +147,4 @@ async function classifyLiveProject(ctx) {
|
|
|
147
147
|
}
|
|
148
148
|
export { classifyLiveFile, classifyLiveProject };
|
|
149
149
|
|
|
150
|
-
//# sourceMappingURL=live-graph-
|
|
150
|
+
//# sourceMappingURL=live-graph-C7-yA8W9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live-graph-DiRVmRrC.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;;;;;AAOA,eAAsB,iBACpB,SACA,KAIA,eAA4C,oBAAoB,GAIhE,QAC2B;CAC3B,MAAM,OAAO,cAAc,OAAO;CAClC,IAAI,OAAsB;CAC1B,IAAI;EACF,OAAO,MAAM,SAAS,MAAM,MAAM;CACpC,SAAS,OAAO;E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,IAAI,MACJ,QACC,YACC,OAAO,KAAK;EAAE,aAAa;EAAQ,IAAI,QAAQ;EAAK,SAAS,QAAQ;CAAQ,CAAC,GAChF,GACA,UACF;CACA,MAAM,UAA8B,CAAC;CACrC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,QAAQ,OACjB,QAAQ,KAAK,MAAM,iBAAiB,MAAM,KAAK,cAAc,MAAM,CAAC;CAEtE,QAAQ,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;CACvE,OAAO;EAAE,MAAM,IAAI;EAAM;EAAS;CAAO;AAC3C"}
|
|
1
|
+
{"version":3,"file":"live-graph-C7-yA8W9.js","names":[],"sources":["../../src/analyze/live-graph.ts"],"sourcesContent":["/**\n * live-graph — classification from a running dev server's environment\n * module graphs (the fast path).\n *\n * When a dev server runs, the env module graphs are already resident —\n * classification is a lookup, not a crawl. This module adapts those\n * graphs to the SAME classification pipeline the cold crawl uses\n * (classify.ts + chains.ts + poison-scan.ts — design/47's \"one\n * classification module, thin frontends\" requirement), so the\n * dev-server endpoint and the CLI can never disagree about a file.\n *\n * Differences from the crawl, both inherent to the live source:\n *\n * - The browser (`client`) graph can be non-empty here (a real browser\n * has requested modules), so `envs.client` is confirmable.\n * - Rendering populates graphs lazily — only visited routes' code is\n * present, and modules behind unexecuted dynamic imports carry\n * `transformResult == null` (the §8 frontier). Those are reported as\n * `subtreeUnknown` rather than transformed on demand: a hint must\n * never mutate the dev server's graphs as a side effect of asking.\n *\n * Design docs: 47-module-environment-tooling.md §8, §\"Dev-server\n * endpoint\".\n */\n\nimport { readFile } from 'node:fs/promises';\nimport { readFileSync } from 'node:fs';\nimport { normalizePath } from 'vite';\nimport {\n classifyModule,\n detectDirective,\n type ClassifyContext,\n type Directive,\n} from './classify.ts';\nimport type { GraphModuleReport } from './crawl.ts';\nimport { stitchImportChains, type ChainGraph, type ImportChain } from './chains.ts';\nimport {\n collectImportSpecifiers,\n importSignals,\n poisoningsFor,\n type Poisoning,\n} from './poison-scan.ts';\nimport { buildSourceExtensions, scanProjectSourceFiles, type ScanFailure } from './scan.ts';\n\n/**\n * Duck-typed node view for liveness checks — the `transformResult`\n * member ChainModuleNode deliberately omits (§8 detection is a\n * classification concern, not a chain concern).\n */\ninterface LiveModuleNode {\n transformResult: unknown;\n}\n\nimport type { ChainModuleNode } from './chains.ts';\n\n/** Duck-typed module graph — structural supertype of Vite's. */\nexport interface LiveGraph extends ChainGraph {\n getModulesByFile(file: string): Set<ChainModuleNode & LiveModuleNode> | undefined;\n}\n\nexport interface LiveGraphContext {\n rsc: LiveGraph;\n ssr: LiveGraph;\n client: LiveGraph;\n /** Realpath'd project root. */\n root: string;\n appDir: string;\n pageExtensions?: readonly string[];\n}\n\n/**\n * Per-module answer — the crawl's shape, aliased rather than restated\n * so a field added to one frontend cannot silently miss the other.\n */\nexport type LiveModuleReport = GraphModuleReport;\n\n/** Non-empty node set for a file in one graph. */\nfunction memberOf(graph: LiveGraph, file: string): boolean {\n return (graph.getModulesByFile(file)?.size ?? 0) > 0;\n}\n\n/**\n * §8: an SSR-graph member whose every node was never transformed is a\n * module behind an unexecuted dynamic import — reachable (it ships to\n * the browser) but its subtree may be missing from the graphs.\n *\n * Live-source caveat: Vite also clears `transformResult` when a watched\n * edit invalidates a node, so on the live graphs `subtreeUnknown`\n * means \"not currently transformed\" — a freshly-edited module reads\n * the same as a dormant dynamic-import payload until the next render\n * re-transforms it. The two states are indistinguishable from the\n * graph alone, and both honestly mean the subtree is not currently\n * known; consumers refreshing on `timber:graph-update` events see the\n * flag clear once the module is re-transformed.\n */\nfunction ssrTransformed(graph: LiveGraph, file: string): boolean | undefined {\n const nodes = graph.getModulesByFile(file);\n if (!nodes || nodes.size === 0) return undefined;\n for (const node of nodes) {\n if (node.transformResult != null) return true;\n }\n return false;\n}\n\n/**\n * Classify one file from the live graphs. `file` must be an absolute\n * realpath (graph nodes carry realpaths); it is slash-normalized here\n * to match Vite's node keying.\n */\nexport async function classifyLiveFile(\n rawFile: string,\n ctx: LiveGraphContext,\n // Shared across a ?all=1 sweep (classifyLiveProject) — a per-call\n // cache would re-read every chain hop's source per target file,\n // quadratic sync IO on well-connected graphs.\n getDirective: (file: string) => Directive = makeDirectiveReader(),\n // Failures are recorded, not swallowed (crawl parity): a lost source\n // read means the directive/poisoning half of the answer is missing,\n // and consumers deserve to see that beside the classification.\n errors?: LiveGraphError[]\n): Promise<LiveModuleReport> {\n const file = normalizePath(rawFile);\n let code: string | null = null;\n try {\n code = await readFile(file, 'utf8');\n } catch (error) {\n // Unreadable (deleted mid-query): classification proceeds on graph\n // membership alone; directive/poisonings default to none.\n errors?.push({\n environment: 'scan',\n id: file,\n message: `source read failed: ${error instanceof Error ? error.message : String(error)}`,\n });\n }\n const directive: Directive = code === null ? null : detectDirective(code, file);\n const signals = code === null ? [] : importSignals(collectImportSpecifiers(code, file));\n\n const classifyCtx: ClassifyContext = {\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n };\n const classification = classifyModule(\n {\n file,\n inRsc: memberOf(ctx.rsc, file),\n inSsr: memberOf(ctx.ssr, file),\n inClient: memberOf(ctx.client, file),\n ssrTransformed: ssrTransformed(ctx.ssr, file),\n directive,\n },\n classifyCtx\n );\n\n const chains = classification.pending\n ? []\n : stitchImportChains(file, {\n rsc: ctx.rsc,\n ssr: ctx.ssr,\n appDir: ctx.appDir,\n pageExtensions: ctx.pageExtensions,\n getDirective,\n });\n\n return {\n ...classification,\n boundary: directive === 'use client',\n chains,\n poisonings: poisoningsFor(classification.kind, classification.pending, signals),\n };\n}\n\n/**\n * Synchronous directive reader with a per-call cache. chains.ts wants a\n * sync callback; node:fs readFileSync per unique hop file is acceptable\n * for a walk bounded by chain length.\n */\nfunction makeDirectiveReader(): (file: string) => Directive {\n const cache = new Map<string, Directive>();\n return (file) => {\n const hit = cache.get(file);\n if (hit !== undefined) return hit;\n let directive: Directive = null;\n try {\n directive = detectDirective(readFileSync(file, 'utf8'), file);\n } catch {\n directive = null;\n }\n cache.set(file, directive);\n return directive;\n };\n}\n\n/** Live-source error entry — the crawl's error vocabulary. */\nexport interface LiveGraphError {\n environment: 'scan';\n id: string;\n message: string;\n}\n\nexport interface LiveProjectReport {\n root: string;\n modules: LiveModuleReport[];\n errors: LiveGraphError[];\n}\n\n/**\n * Classify every project source file from the live graphs. Files on\n * disk that no graph reached get the §2 provisional/pending\n * classification — on a lazily-warmed dev server that includes routes\n * nobody has visited yet, which is honest: the graphs genuinely have\n * not confirmed them.\n */\nexport async function classifyLiveProject(ctx: LiveGraphContext): Promise<LiveProjectReport> {\n const files: string[] = [];\n const errors: LiveProjectReport['errors'] = [];\n const extensions = buildSourceExtensions(ctx.pageExtensions);\n await scanProjectSourceFiles(\n ctx.root,\n files,\n (failure: ScanFailure) =>\n errors.push({ environment: 'scan', id: failure.dir, message: failure.message }),\n 0,\n extensions\n );\n const modules: LiveModuleReport[] = [];\n const getDirective = makeDirectiveReader();\n for (const file of files) {\n modules.push(await classifyLiveFile(file, ctx, getDirective, errors));\n }\n modules.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : 0));\n return { root: ctx.root, modules, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6EA,SAAS,SAAS,OAAkB,MAAuB;CACzD,QAAQ,MAAM,iBAAiB,IAAI,CAAC,EAAE,QAAQ,KAAK;AACrD;;;;;;;;;;;;;;;AAgBA,SAAS,eAAe,OAAkB,MAAmC;CAC3E,MAAM,QAAQ,MAAM,iBAAiB,IAAI;CACzC,IAAI,CAAC,SAAS,MAAM,SAAS,GAAG,OAAO,KAAA;CACvC,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,mBAAmB,MAAM,OAAO;CAE3C,OAAO;AACT;;;;;;AAOA,eAAsB,iBACpB,SACA,KAIA,eAA4C,oBAAoB,GAIhE,QAC2B;CAC3B,MAAM,OAAO,cAAc,OAAO;CAClC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ACzB,MAAM,SAAsC,CAAC;CAC7C,MAAM,aAAa,sBAAsB,IAAI,cAAc;CAC3D,MAAM,uBACJ,IAAI,MACJ,QACC,YACC,OAAO,KAAK;EAAE,aAAa;EAAQ,IAAI,QAAQ;EAAK,SAAS,QAAQ;CAAQ,CAAC,GAChF,GACA,UACF;CACA,MAAM,UAA8B,CAAC;CACrC,MAAM,eAAe,oBAAoB;CACzC,KAAK,MAAM,QAAQ,OACjB,QAAQ,KAAK,MAAM,iBAAiB,MAAM,KAAK,cAAc,MAAM,CAAC;CAEtE,QAAQ,MAAM,GAAG,MAAO,EAAE,OAAO,EAAE,OAAO,KAAK,EAAE,OAAO,EAAE,OAAO,IAAI,CAAE;CACvE,OAAO;EAAE,MAAM,IAAI;EAAM;EAAS;CAAO;AAC3C"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { s as traceAls } from "./als-registry-DpygwCp0.js";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { SpanStatusCode, trace } from "@opentelemetry/api";
|
|
3
4
|
// src/server/signal-identity.ts
|
|
4
5
|
var DENY_BRAND = Symbol.for("timber:signal.deny");
|
|
5
6
|
var REDIRECT_BRAND = Symbol.for("timber:signal.redirect");
|
|
@@ -138,34 +139,19 @@ function getPlatformTracer() {
|
|
|
138
139
|
return globalThis[PLATFORM_TRACER_KEY];
|
|
139
140
|
}
|
|
140
141
|
/**
|
|
141
|
-
*
|
|
142
|
-
* package is not installed or no SDK is registered.
|
|
142
|
+
* The timber.js OTEL tracer.
|
|
143
143
|
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
*
|
|
144
|
+
* `@opentelemetry/api` is a direct dependency and a no-op until an SDK
|
|
145
|
+
* registers a provider (the user's `register()`, or dev tracing). Imported
|
|
146
|
+
* statically, not lazily, so `withSpan()` can invoke its callback in the
|
|
147
|
+
* same synchronous frame it was called in: a server component wrapped in a
|
|
148
|
+
* span (`timber.page`, `timber.layout`) must run while React's render
|
|
149
|
+
* dispatcher is still set, or a synchronous component that calls `use()`
|
|
150
|
+
* fails with an invalid hook call. Looked up per span — the API's proxy
|
|
151
|
+
* tracer follows a provider registered after boot.
|
|
147
152
|
*/
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
if (_otelApi === void 0) try {
|
|
151
|
-
_otelApi = await import("@opentelemetry/api");
|
|
152
|
-
} catch {
|
|
153
|
-
_otelApi = null;
|
|
154
|
-
}
|
|
155
|
-
return _otelApi;
|
|
156
|
-
}
|
|
157
|
-
/** OTEL tracer instance, lazily created. */
|
|
158
|
-
var _tracer;
|
|
159
|
-
/**
|
|
160
|
-
* Get the timber.js OTEL tracer. Returns null if @opentelemetry/api is not available.
|
|
161
|
-
*/
|
|
162
|
-
async function getTracer() {
|
|
163
|
-
if (_tracer === void 0) {
|
|
164
|
-
const api = await getOtelApi();
|
|
165
|
-
if (api) _tracer = api.trace.getTracer("timber.js");
|
|
166
|
-
else _tracer = null;
|
|
167
|
-
}
|
|
168
|
-
return _tracer;
|
|
153
|
+
function getTracer() {
|
|
154
|
+
return trace.getTracer("timber.js");
|
|
169
155
|
}
|
|
170
156
|
/**
|
|
171
157
|
* Run a function within a framework span. Composes two emission channels:
|
|
@@ -174,9 +160,12 @@ async function getTracer() {
|
|
|
174
160
|
* (Cloudflare Workers), the fn is wrapped in platformTracer.enterSpan()
|
|
175
161
|
* so it appears in the platform's native trace view.
|
|
176
162
|
* - **OTEL span** — when an OTEL SDK is active, the fn also runs inside an
|
|
177
|
-
* OTEL span (dual emission).
|
|
163
|
+
* OTEL span (dual emission). With no SDK the OTEL span is the API's
|
|
164
|
+
* non-recording no-op.
|
|
178
165
|
*
|
|
179
166
|
* Automatically:
|
|
167
|
+
* - Invokes fn synchronously, in the caller's frame — a wrapped server
|
|
168
|
+
* component still sees React's render dispatcher (see getTracer())
|
|
180
169
|
* - Creates the span as a child of the current context
|
|
181
170
|
* - Runs fn in its own trace scope carrying the span's IDs, for log–trace
|
|
182
171
|
* correlation and setSpanAttribute()
|
|
@@ -184,6 +173,20 @@ async function getTracer() {
|
|
|
184
173
|
* - Records exceptions on error (OTEL channel)
|
|
185
174
|
*/
|
|
186
175
|
async function withSpan(name, attributes, fn) {
|
|
176
|
+
return traceCall(name, attributes, fn);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The span core of {@link withSpan}, keeping the shape of the call: `fn` runs
|
|
180
|
+
* synchronously, a value it returns comes back as that value, a promise as a
|
|
181
|
+
* promise, and a synchronous throw is rethrown synchronously.
|
|
182
|
+
*
|
|
183
|
+
* For a framework wrapper that invokes a server component inside a span.
|
|
184
|
+
* React drives a synchronous component through throws: `use()` on a pending
|
|
185
|
+
* promise throws, and Flight retries the component once it settles. That only
|
|
186
|
+
* works if the throw leaves the wrapper synchronously — `withSpan()` would
|
|
187
|
+
* turn it into a rejection, which Flight reports as a render error.
|
|
188
|
+
*/
|
|
189
|
+
function traceCall(name, attributes, fn) {
|
|
187
190
|
const platformTracer = getPlatformTracer();
|
|
188
191
|
if (!platformTracer) return runOtelSpan(name, attributes, fn);
|
|
189
192
|
return platformTracer.enterSpan(name, (span) => {
|
|
@@ -191,12 +194,12 @@ async function withSpan(name, attributes, fn) {
|
|
|
191
194
|
return runInSpanScope({ platformSpan: span }, () => runOtelSpan(name, attributes, fn));
|
|
192
195
|
});
|
|
193
196
|
}
|
|
194
|
-
/**
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
return
|
|
197
|
+
/**
|
|
198
|
+
* The OTEL half of withSpan() — a non-recording span when no SDK is active.
|
|
199
|
+
* Calls `fn` synchronously; see {@link getTracer}.
|
|
200
|
+
*/
|
|
201
|
+
function runOtelSpan(name, attributes, fn) {
|
|
202
|
+
return getTracer().startActiveSpan(name, { attributes }, (span) => runInSpanScope({ spanId: span.spanContext().spanId }, () => settleOtelSpan(span, fn)));
|
|
200
203
|
}
|
|
201
204
|
/**
|
|
202
205
|
* True when `error` is a `redirect()`, or a `deny()` below 500: an outcome the
|
|
@@ -212,20 +215,68 @@ function isOutcomeSignal(error) {
|
|
|
212
215
|
const status = controlFlowStatus(isSsrStreamError(error) ? error.cause : error);
|
|
213
216
|
return status !== void 0 && status < 500;
|
|
214
217
|
}
|
|
215
|
-
/**
|
|
216
|
-
|
|
218
|
+
/**
|
|
219
|
+
* Run `fn` and end `span` with its outcome (see {@link isOutcomeSignal}),
|
|
220
|
+
* keeping the call's shape (see {@link traceCall}).
|
|
221
|
+
*/
|
|
222
|
+
function settleOtelSpan(span, fn) {
|
|
223
|
+
let result;
|
|
217
224
|
try {
|
|
218
|
-
|
|
219
|
-
span.setStatus({ code: api.SpanStatusCode.OK });
|
|
220
|
-
return result;
|
|
225
|
+
result = fn();
|
|
221
226
|
} catch (error) {
|
|
222
|
-
|
|
223
|
-
span.setStatus({ code: api.SpanStatusCode.ERROR });
|
|
224
|
-
if (error instanceof Error) span.recordException(error);
|
|
227
|
+
endSpanWithError(span, error);
|
|
225
228
|
throw error;
|
|
226
|
-
} finally {
|
|
227
|
-
span.end();
|
|
228
229
|
}
|
|
230
|
+
if (isPromiseLike(result)) {
|
|
231
|
+
const thenable = result;
|
|
232
|
+
return new Promise((resolve, reject) => {
|
|
233
|
+
const fail = (error) => {
|
|
234
|
+
endSpanWithError(span, error);
|
|
235
|
+
reject(error);
|
|
236
|
+
};
|
|
237
|
+
try {
|
|
238
|
+
thenable.then((value) => {
|
|
239
|
+
endSpanOk(span);
|
|
240
|
+
resolve(value);
|
|
241
|
+
}, fail);
|
|
242
|
+
} catch (error) {
|
|
243
|
+
fail(error);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
endSpanOk(span);
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
function isPromiseLike(value) {
|
|
251
|
+
return (typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function";
|
|
252
|
+
}
|
|
253
|
+
function endSpanOk(span) {
|
|
254
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
255
|
+
span.end();
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* True when `error` is React suspending the component, not failing it: a
|
|
259
|
+
* thrown thenable, or the `SuspenseException` that `use()` throws on a
|
|
260
|
+
* pending promise. Flight retries the component once the promise settles, so
|
|
261
|
+
* a span around a synchronous component (see {@link traceCall}) that suspends
|
|
262
|
+
* is not an error span — the retry's span carries the real outcome.
|
|
263
|
+
*
|
|
264
|
+
* React does not export `SuspenseException`; Flight recognises it by
|
|
265
|
+
* identity, and its message — which React keeps stable because it is the
|
|
266
|
+
* user-facing explanation when one is caught by mistake — is the only handle
|
|
267
|
+
* outside React.
|
|
268
|
+
*/
|
|
269
|
+
function isReactSuspension(error) {
|
|
270
|
+
if (typeof error !== "object" || error === null) return false;
|
|
271
|
+
if ("then" in error && typeof error.then === "function") return true;
|
|
272
|
+
return error instanceof Error && error.message.startsWith("Suspense Exception:");
|
|
273
|
+
}
|
|
274
|
+
function endSpanWithError(span, error) {
|
|
275
|
+
if (!isOutcomeSignal(error) && !isReactSuspension(error)) {
|
|
276
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
277
|
+
if (error instanceof Error) span.recordException(error);
|
|
278
|
+
}
|
|
279
|
+
span.end();
|
|
229
280
|
}
|
|
230
281
|
/**
|
|
231
282
|
* Set an attribute on the current active span (if any).
|
|
@@ -234,9 +285,7 @@ async function settleOtelSpan(api, span, fn) {
|
|
|
234
285
|
async function setSpanAttribute(key, value) {
|
|
235
286
|
const platformSpan = traceAls.getStore()?.platformSpan;
|
|
236
287
|
if (platformSpan) platformSpan.setAttribute(key, value);
|
|
237
|
-
const
|
|
238
|
-
if (!api) return;
|
|
239
|
-
const activeSpan = api.trace.getActiveSpan();
|
|
288
|
+
const activeSpan = trace.getActiveSpan();
|
|
240
289
|
if (activeSpan?.isRecording()) activeSpan.setAttribute(key, value);
|
|
241
290
|
}
|
|
242
291
|
/**
|
|
@@ -244,23 +293,19 @@ async function setSpanAttribute(key, value) {
|
|
|
244
293
|
* Used for timber.cache HIT/MISS events — recorded as span events, not child spans.
|
|
245
294
|
*/
|
|
246
295
|
async function addSpanEvent(name, attributes) {
|
|
247
|
-
const
|
|
248
|
-
if (!api) return;
|
|
249
|
-
const activeSpan = api.trace.getActiveSpan();
|
|
296
|
+
const activeSpan = trace.getActiveSpan();
|
|
250
297
|
if (activeSpan?.isRecording()) activeSpan.addEvent(name, attributes);
|
|
251
298
|
}
|
|
252
299
|
/**
|
|
253
300
|
* Fire-and-forget span event — no await, no microtask overhead.
|
|
254
301
|
*
|
|
255
302
|
* Used on the cache hot path where awaiting addSpanEvent creates an
|
|
256
|
-
* unnecessary microtask per cache operation.
|
|
257
|
-
* the event is silently dropped (acceptable for diagnostics).
|
|
303
|
+
* unnecessary microtask per cache operation.
|
|
258
304
|
*
|
|
259
305
|
* See TIM-370 for perf motivation.
|
|
260
306
|
*/
|
|
261
307
|
function addSpanEventSync(name, attributes) {
|
|
262
|
-
|
|
263
|
-
const activeSpan = _otelApi.trace.getActiveSpan();
|
|
308
|
+
const activeSpan = trace.getActiveSpan();
|
|
264
309
|
if (activeSpan?.isRecording()) activeSpan.addEvent(name, attributes);
|
|
265
310
|
}
|
|
266
311
|
/**
|
|
@@ -269,9 +314,7 @@ function addSpanEventSync(name, attributes) {
|
|
|
269
314
|
* reaches logs through the span's own trace scope, not from here.)
|
|
270
315
|
*/
|
|
271
316
|
async function getOtelTraceId() {
|
|
272
|
-
const
|
|
273
|
-
if (!api) return void 0;
|
|
274
|
-
const activeSpan = api.trace.getActiveSpan();
|
|
317
|
+
const activeSpan = trace.getActiveSpan();
|
|
275
318
|
if (!activeSpan) return void 0;
|
|
276
319
|
const ctx = activeSpan.spanContext();
|
|
277
320
|
if (!ctx.traceId || ctx.traceId === "00000000000000000000000000000000") return;
|
|
@@ -709,4 +752,4 @@ function swallow(err, reason, opts) {
|
|
|
709
752
|
}
|
|
710
753
|
export { runWithTraceId as A, addSpanEvent as C, getSpanId as D, getOtelTraceId as E, isControlFlowSignal as F, isDenySignal as I, isRedirectSignal as L, withSpan as M, DENY_BRAND as N, getTraceId as O, REDIRECT_BRAND as P, isDevMode as S, generateTraceId as T, logWaitUntilRejected as _, logKeyDisciplineViolation as a, swallow as b, logMiddlewareShortCircuit as c, logRequestCompleted as d, logRequestReceived as f, logSwrRefetchFailed as g, logSlowRequest as h, logCsrfRejected as i, setSpanAttribute as j, replaceTraceId as k, logProxyError as l, logRouteSetupError as m, logCacheMiss as n, logLossyCacheValue as o, logRouteError as p, logCacheReadFailed as r, logMiddlewareError as s, getLogger as t, logRenderError as u, logWaitUntilUnsupported as v, addSpanEventSync as w, isDebug as x, setLogger as y };
|
|
711
754
|
|
|
712
|
-
//# sourceMappingURL=logger-
|
|
755
|
+
//# sourceMappingURL=logger-YtMSKfft.js.map
|