@timber-js/app 0.2.0-alpha.219 → 0.2.0-alpha.220
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_chunks/chains-CDK1AWZQ.js +1 -0
- package/dist/_chunks/{chains-YKZ8WpIW.js → chains-e_Buf9vg.js} +2 -7
- package/dist/_chunks/{chains-YKZ8WpIW.js.map → chains-e_Buf9vg.js.map} +1 -1
- package/dist/_chunks/{cli-check-D2WtbNqo.js → cli-check-DDwCkeDY.js} +2 -2
- package/dist/_chunks/{cli-check-D2WtbNqo.js.map → cli-check-DDwCkeDY.js.map} +1 -1
- package/dist/_chunks/cli-context-BJQB6rtF.js +1 -0
- package/dist/_chunks/{cli-context-By7k2xVo.js → cli-context-_mPttGGY.js} +3 -3
- package/dist/_chunks/{cli-context-By7k2xVo.js.map → cli-context-_mPttGGY.js.map} +1 -1
- package/dist/_chunks/{cli-schema-sync-CySLKrO3.js → cli-schema-sync-BdIebmk3.js} +3 -12
- package/dist/_chunks/{cli-schema-sync-CySLKrO3.js.map → cli-schema-sync-BdIebmk3.js.map} +1 -1
- package/dist/_chunks/cli-schema-sync-CLNfXQDK.js +1 -0
- package/dist/_chunks/dev-server-DkytOEG2.js +1 -0
- package/dist/_chunks/{dev-server-B8zsT-ee.js → dev-server-DnODXuNM.js} +31 -14
- package/dist/_chunks/{dev-server-B8zsT-ee.js.map → dev-server-DnODXuNM.js.map} +1 -1
- package/dist/_chunks/flight-source-node-0dE-t3kq.js +519 -0
- package/dist/_chunks/flight-source-node-0dE-t3kq.js.map +1 -0
- package/dist/_chunks/{live-graph-BhtrZpRd.js → live-graph-tSWrv8eH.js} +2 -2
- package/dist/_chunks/{live-graph-BhtrZpRd.js.map → live-graph-tSWrv8eH.js.map} +1 -1
- package/dist/_chunks/node-response-Dibufw_b.js +187 -0
- package/dist/_chunks/node-response-Dibufw_b.js.map +1 -0
- package/dist/_chunks/{plugin-context-BPBPc3lL.js → plugin-context-DxMMvjUt.js} +2 -18
- package/dist/_chunks/{plugin-context-BPBPc3lL.js.map → plugin-context-DxMMvjUt.js.map} +1 -1
- package/dist/_chunks/plugin-context-uDHFqHHJ.js +1 -0
- package/dist/_chunks/{walkers-Ber9bamD.js → walkers-qu8TpiLh.js} +2 -2
- package/dist/_chunks/{walkers-Ber9bamD.js.map → walkers-qu8TpiLh.js.map} +1 -1
- package/dist/adapters/nitro-preview.d.ts.map +1 -1
- package/dist/adapters/nitro.js +40 -1
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/analyze/crawl-entry.js +2 -2
- package/dist/analyze/graph-command.js +3 -3
- package/dist/analyze/graph-command.js.map +1 -1
- package/dist/cli.js +5 -5
- package/dist/cli.js.map +1 -1
- package/dist/client/browser-entry/form-state.d.ts.map +1 -1
- package/dist/client/browser-entry/index.d.ts +1 -1
- package/dist/client/browser-entry/rsc-stream.d.ts +4 -1
- package/dist/client/browser-entry/rsc-stream.d.ts.map +1 -1
- package/dist/client/react-root.d.ts +6 -0
- package/dist/client/react-root.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -5
- package/dist/index.js.map +1 -1
- package/dist/plugins/encryption-runtime.d.ts +13 -0
- package/dist/plugins/encryption-runtime.d.ts.map +1 -0
- package/dist/plugins/entries.d.ts +1 -0
- package/dist/plugins/entries.d.ts.map +1 -1
- package/dist/plugins/server-bundle.d.ts +1 -1
- package/dist/plugins/server-bundle.d.ts.map +1 -1
- package/dist/routing/index.js +1 -1
- package/dist/rsc-runtime/encryption-runtime.d.ts +25 -0
- package/dist/rsc-runtime/encryption-runtime.d.ts.map +1 -0
- package/dist/rsc-runtime/render-flight.d.ts +14 -0
- package/dist/rsc-runtime/render-flight.d.ts.map +1 -0
- package/dist/rsc-runtime/rsc.d.ts +6 -2
- package/dist/rsc-runtime/rsc.d.ts.map +1 -1
- package/dist/rsc-runtime/ssr.d.ts +6 -12
- package/dist/rsc-runtime/ssr.d.ts.map +1 -1
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/compress.d.ts +2 -0
- package/dist/server/compress.d.ts.map +1 -1
- package/dist/server/deny-renderer.d.ts +2 -1
- package/dist/server/deny-renderer.d.ts.map +1 -1
- package/dist/server/flight-injector-core.d.ts +125 -0
- package/dist/server/flight-injector-core.d.ts.map +1 -0
- package/dist/server/flight-scripts.d.ts +9 -0
- package/dist/server/flight-scripts.d.ts.map +1 -1
- package/dist/server/flight-source-node.d.ts +105 -0
- package/dist/server/flight-source-node.d.ts.map +1 -0
- package/dist/server/flight-source.d.ts +136 -0
- package/dist/server/flight-source.d.ts.map +1 -0
- package/dist/server/head-response.d.ts.map +1 -1
- package/dist/server/html-injector-core.d.ts +3 -91
- package/dist/server/html-injector-core.d.ts.map +1 -1
- package/dist/server/html-injectors.d.ts +5 -17
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/internal.js +78 -138
- package/dist/server/internal.js.map +1 -1
- package/dist/server/node-body-response.d.ts +55 -0
- package/dist/server/node-body-response.d.ts.map +1 -0
- package/dist/server/node-response.d.ts +62 -0
- package/dist/server/node-response.d.ts.map +1 -0
- package/dist/server/node-stream-transforms.d.ts +24 -21
- package/dist/server/node-stream-transforms.d.ts.map +1 -1
- package/dist/server/node-streams-platform.d.ts +21 -0
- package/dist/server/node-streams-platform.d.ts.map +1 -0
- package/dist/server/pipeline-helpers.d.ts.map +1 -1
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/prebuilt-runtime.d.ts +2 -3
- package/dist/server/prebuilt-runtime.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/render-route.d.ts +4 -1
- package/dist/server/rsc-entry/render-route.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-payload.d.ts +9 -6
- package/dist/server/rsc-entry/rsc-payload.d.ts.map +1 -1
- package/dist/server/rsc-entry/rsc-stream.d.ts +9 -4
- package/dist/server/rsc-entry/rsc-stream.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-bridge.d.ts +2 -1
- package/dist/server/rsc-entry/ssr-bridge.d.ts.map +1 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts +2 -1
- package/dist/server/rsc-entry/ssr-renderer.d.ts.map +1 -1
- package/dist/server/ssr-bridge-types.d.ts +9 -4
- package/dist/server/ssr-bridge-types.d.ts.map +1 -1
- package/dist/server/ssr-entry.d.ts +8 -5
- package/dist/server/ssr-entry.d.ts.map +1 -1
- package/dist/server/ssr-render.d.ts +7 -16
- package/dist/server/ssr-render.d.ts.map +1 -1
- package/dist/server/stream-utils.d.ts +44 -10
- package/dist/server/stream-utils.d.ts.map +1 -1
- package/dist/shared/flight-base64.d.ts +13 -0
- package/dist/shared/flight-base64.d.ts.map +1 -0
- package/dist/shared/flight-segment.d.ts +18 -0
- package/dist/shared/flight-segment.d.ts.map +1 -0
- package/dist/shared/form-state-flight.d.ts +0 -4
- package/dist/shared/form-state-flight.d.ts.map +1 -1
- package/docs/learn/12-error-handling.mdx +1 -1
- package/package.json +1 -1
- package/src/adapters/nitro-preview.ts +39 -0
- package/src/client/browser-entry/form-state.ts +3 -2
- package/src/client/browser-entry/index.ts +14 -8
- package/src/client/browser-entry/rsc-stream.ts +14 -14
- package/src/client/react-root.ts +25 -2
- package/src/index.ts +2 -0
- package/src/plugins/encryption-runtime.ts +31 -0
- package/src/plugins/entries.ts +1 -1
- package/src/plugins/server-bundle.ts +17 -2
- package/src/rsc-runtime/encryption-runtime.ts +78 -0
- package/src/rsc-runtime/render-flight.ts +26 -0
- package/src/rsc-runtime/rsc.ts +7 -4
- package/src/rsc-runtime/ssr.ts +10 -48
- package/src/rsc-runtime/vendor-types.d.ts +31 -2
- package/src/server/action-handler.ts +43 -44
- package/src/server/compress.ts +49 -12
- package/src/server/deny-renderer.ts +14 -7
- package/src/server/flight-injector-core.ts +328 -0
- package/src/server/flight-scripts.ts +14 -2
- package/src/server/flight-source-node.ts +430 -0
- package/src/server/flight-source.ts +288 -0
- package/src/server/form-state-flight.ts +4 -4
- package/src/server/head-response.ts +6 -10
- package/src/server/html-injector-core.ts +24 -216
- package/src/server/html-injectors.ts +12 -71
- package/src/server/node-body-response.ts +236 -0
- package/src/server/node-response.ts +93 -0
- package/src/server/node-stream-transforms.ts +70 -53
- package/src/server/node-streams-platform.ts +23 -0
- package/src/server/pipeline-helpers.ts +3 -1
- package/src/server/pipeline.ts +14 -6
- package/src/server/prebuilt/capture-render.ts +5 -5
- package/src/server/prebuilt-runtime.ts +7 -10
- package/src/server/rsc-entry/error-renderer.ts +8 -4
- package/src/server/rsc-entry/index.ts +4 -2
- package/src/server/rsc-entry/render-route.ts +5 -2
- package/src/server/rsc-entry/rsc-payload.ts +52 -73
- package/src/server/rsc-entry/rsc-stream.ts +102 -106
- package/src/server/rsc-entry/ssr-bridge.ts +32 -10
- package/src/server/rsc-entry/ssr-renderer.ts +15 -18
- package/src/server/ssr-bridge-types.ts +10 -4
- package/src/server/ssr-entry.ts +56 -52
- package/src/server/ssr-render.ts +41 -76
- package/src/server/stream-utils.ts +125 -70
- package/src/shared/flight-base64.ts +23 -0
- package/src/shared/flight-segment.ts +35 -0
- package/src/shared/form-state-flight.ts +0 -15
- package/dist/_chunks/rolldown-runtime-D7D4PA-g.js +0 -13
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
import { r as RenderTimeoutError } from "./render-timeout-DOf_BBcO.js";
|
|
2
|
+
import { a as DEFAULT_MAX_BUFFER_BYTES, l as teeBufferExceeded, s as createStreamTimingRecorder, t as NODE_BODY, u as wrapResponseWithStreamTiming } from "./node-response-Dibufw_b.js";
|
|
3
|
+
import { Readable, Transform, pipeline } from "node:stream";
|
|
4
|
+
//#region src/server/node-body-response.ts
|
|
5
|
+
/**
|
|
6
|
+
* `NodeBodyResponse` — a `Response` whose body is a Node `Readable`, so a
|
|
7
|
+
* response built on Node streams reaches the socket without a Web Streams
|
|
8
|
+
* round trip (LOCAL-1475). Node only: loaded behind `nodeStreamsPlatform`.
|
|
9
|
+
*
|
|
10
|
+
* The status and headers are an ordinary `Response`'s. The body stays a Node
|
|
11
|
+
* stream until one of two things takes it:
|
|
12
|
+
*
|
|
13
|
+
* - **An adapter**, through `_toNodeResponse()` — srvx's protocol (nitro and
|
|
14
|
+
* the dev server send with srvx; nitro-preview's sender speaks it too). The
|
|
15
|
+
* stream is piped straight into `ServerResponse`.
|
|
16
|
+
* - **Web-API code** reading `body`, `text()`, `arrayBuffer()`, `clone()`, …
|
|
17
|
+
* The response then converts its body once, with `Readable.toWeb`, and
|
|
18
|
+
* behaves as a native `Response` from then on. Correct anywhere, so code
|
|
19
|
+
* that does not know about Node bodies keeps working; pipeline code on the
|
|
20
|
+
* hot path goes through `node-response.ts` instead, which never converts.
|
|
21
|
+
*
|
|
22
|
+
* Pattern from srvx's `NodeResponse` (`FastResponse`).
|
|
23
|
+
*
|
|
24
|
+
* Design doc: 02-rendering-pipeline.md §"Response Bodies on Node"
|
|
25
|
+
*/
|
|
26
|
+
/** Statuses whose responses carry no body (Fetch "null body status"). */
|
|
27
|
+
var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
|
|
28
|
+
101,
|
|
29
|
+
103,
|
|
30
|
+
204,
|
|
31
|
+
205,
|
|
32
|
+
304
|
|
33
|
+
]);
|
|
34
|
+
function ignoreError$1() {}
|
|
35
|
+
/** Destroy a body nothing will read, without an unhandled `'error'`. */
|
|
36
|
+
function destroyBody(body) {
|
|
37
|
+
if (!body.listeners("error").includes(ignoreError$1)) body.on("error", ignoreError$1);
|
|
38
|
+
body.destroy();
|
|
39
|
+
}
|
|
40
|
+
var NodeBodyResponse = class NodeBodyResponse extends Response {
|
|
41
|
+
#body;
|
|
42
|
+
#native = null;
|
|
43
|
+
/** An adapter or a pipeline op took the body: it is used, as a read one is. */
|
|
44
|
+
#taken = false;
|
|
45
|
+
constructor(body, init) {
|
|
46
|
+
super(null, init);
|
|
47
|
+
if (NULL_BODY_STATUSES.has(this.status)) {
|
|
48
|
+
destroyBody(body);
|
|
49
|
+
this.#body = null;
|
|
50
|
+
} else this.#body = body;
|
|
51
|
+
}
|
|
52
|
+
/** Take the Node body; this response no longer has it. */
|
|
53
|
+
#take() {
|
|
54
|
+
const body = this.#body;
|
|
55
|
+
if (body) this.#taken = true;
|
|
56
|
+
this.#body = null;
|
|
57
|
+
return body;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* This response as a native one, converting the Node body once. Throws, as
|
|
61
|
+
* a native Response whose body was read does, if something already took
|
|
62
|
+
* the body (an adapter, a re-wrap), rather than reading as empty.
|
|
63
|
+
*/
|
|
64
|
+
#toNative() {
|
|
65
|
+
if (!this.#native) {
|
|
66
|
+
if (this.#taken) throw new TypeError("Body is unusable: Body has already been read");
|
|
67
|
+
const body = this.#body;
|
|
68
|
+
this.#body = null;
|
|
69
|
+
this.#native = new Response(body ? Readable.toWeb(body) : null, {
|
|
70
|
+
status: this.status,
|
|
71
|
+
statusText: this.statusText,
|
|
72
|
+
headers: this.headers
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return this.#native;
|
|
76
|
+
}
|
|
77
|
+
get [NODE_BODY]() {
|
|
78
|
+
return {
|
|
79
|
+
hasBody: this.#native ? this.#native.body !== null : this.#body !== null,
|
|
80
|
+
rewrap: (init) => {
|
|
81
|
+
if (this.#native) return new Response(this.#native.body, init);
|
|
82
|
+
const body = this.#take();
|
|
83
|
+
return body ? new NodeBodyResponse(body, init) : new Response(null, init);
|
|
84
|
+
},
|
|
85
|
+
discard: () => {
|
|
86
|
+
if (this.#native) {
|
|
87
|
+
this.#native.body?.cancel().catch(() => {});
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const body = this.#take();
|
|
91
|
+
if (body) destroyBody(body);
|
|
92
|
+
},
|
|
93
|
+
through: (stream, init) => {
|
|
94
|
+
const body = this.#native ? this.#native.body && webToNode(this.#native.body) : this.#take();
|
|
95
|
+
return body ? new NodeBodyResponse(pipeThrough(body, stream), init) : new Response(null, init);
|
|
96
|
+
},
|
|
97
|
+
timed: (startTime) => {
|
|
98
|
+
const init = {
|
|
99
|
+
status: this.status,
|
|
100
|
+
statusText: this.statusText,
|
|
101
|
+
headers: this.headers
|
|
102
|
+
};
|
|
103
|
+
if (this.#native) {
|
|
104
|
+
const native = this.#native.body;
|
|
105
|
+
return new Response(native ? wrapResponseWithStreamTiming(native, startTime) : null, init);
|
|
106
|
+
}
|
|
107
|
+
const body = this.#take();
|
|
108
|
+
return body ? new NodeBodyResponse(timeBody(body, startTime), init) : this;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* srvx's protocol for a response with a Node body: srvx pipes `body` into
|
|
114
|
+
* `ServerResponse` with `pipeline()`. Headers as a flat `[name, value, …]`
|
|
115
|
+
* list, as srvx's own `NodeResponse` returns them.
|
|
116
|
+
*/
|
|
117
|
+
_toNodeResponse() {
|
|
118
|
+
const headers = [];
|
|
119
|
+
for (const [name, value] of this.headers) headers.push(name, value);
|
|
120
|
+
return {
|
|
121
|
+
status: this.status,
|
|
122
|
+
statusText: this.statusText,
|
|
123
|
+
headers,
|
|
124
|
+
body: this.#native ? this.#native.body : this.#take()
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
get body() {
|
|
128
|
+
return this.#toNative().body;
|
|
129
|
+
}
|
|
130
|
+
get bodyUsed() {
|
|
131
|
+
return this.#native ? this.#native.bodyUsed : this.#taken;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The other half of srvx's protocol: srvx/bun and srvx/deno send
|
|
135
|
+
* `res._response` for anything with `_toNodeResponse` (`toNativeResponse`),
|
|
136
|
+
* and their runtimes stream Web bodies natively. Converts once.
|
|
137
|
+
*/
|
|
138
|
+
get _response() {
|
|
139
|
+
return this.#toNative();
|
|
140
|
+
}
|
|
141
|
+
arrayBuffer() {
|
|
142
|
+
return this.#toNative().arrayBuffer();
|
|
143
|
+
}
|
|
144
|
+
blob() {
|
|
145
|
+
return this.#toNative().blob();
|
|
146
|
+
}
|
|
147
|
+
bytes() {
|
|
148
|
+
return this.#toNative().arrayBuffer().then((buffer) => new Uint8Array(buffer));
|
|
149
|
+
}
|
|
150
|
+
formData() {
|
|
151
|
+
return this.#toNative().formData();
|
|
152
|
+
}
|
|
153
|
+
json() {
|
|
154
|
+
return this.#toNative().json();
|
|
155
|
+
}
|
|
156
|
+
text() {
|
|
157
|
+
return this.#toNative().text();
|
|
158
|
+
}
|
|
159
|
+
clone() {
|
|
160
|
+
return this.#toNative().clone();
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
/** `body` piped through `stream`; an error or destroy on either end tears down both. */
|
|
164
|
+
function pipeThrough(body, stream) {
|
|
165
|
+
stream.on("error", ignoreError$1);
|
|
166
|
+
pipeline(body, stream, ignoreError$1);
|
|
167
|
+
return stream;
|
|
168
|
+
}
|
|
169
|
+
/** A Web body already taken out of this response, back as a Node stream. */
|
|
170
|
+
function webToNode(body) {
|
|
171
|
+
return Readable.fromWeb(body);
|
|
172
|
+
}
|
|
173
|
+
/** A body that reports stream-lifecycle timing ({@link createStreamTimingRecorder}). */
|
|
174
|
+
function timeBody(body, startTime) {
|
|
175
|
+
const timing = createStreamTimingRecorder(startTime);
|
|
176
|
+
const timed = new Transform({
|
|
177
|
+
transform(chunk, _encoding, callback) {
|
|
178
|
+
timing.chunk(chunk.byteLength);
|
|
179
|
+
callback(null, chunk);
|
|
180
|
+
},
|
|
181
|
+
flush(callback) {
|
|
182
|
+
timing.end(false);
|
|
183
|
+
callback();
|
|
184
|
+
},
|
|
185
|
+
destroy(error, callback) {
|
|
186
|
+
timing.end(true);
|
|
187
|
+
body.destroy(error ?? void 0);
|
|
188
|
+
callback(error);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
timed.on("error", ignoreError$1);
|
|
192
|
+
body.on("error", (error) => {
|
|
193
|
+
timing.end(false);
|
|
194
|
+
timed.destroy(error);
|
|
195
|
+
});
|
|
196
|
+
body.pipe(timed);
|
|
197
|
+
return timed;
|
|
198
|
+
}
|
|
199
|
+
//#endregion
|
|
200
|
+
//#region src/server/flight-source-node.ts
|
|
201
|
+
/**
|
|
202
|
+
* Node halves of the Flight source helpers in `flight-source.ts`.
|
|
203
|
+
*
|
|
204
|
+
* Only loaded on Node (`flight-source.ts` imports it behind
|
|
205
|
+
* `nodeStreamsPlatform`), so Workers never evaluate it.
|
|
206
|
+
*
|
|
207
|
+
* A Node Flight source is an object-mode `Readable` whose chunks are exactly
|
|
208
|
+
* what React's `renderToPipeableStream` wrote: `Uint8Array` views for short
|
|
209
|
+
* rows, and JS strings for long rows (≥ ~1365 chars) and text row bodies.
|
|
210
|
+
* The Node Flight client (`createFromNodeStream`) requires every string chunk
|
|
211
|
+
* in its original shape — it throws "String chunks need to be passed in their
|
|
212
|
+
* original shape" if one is split or merged — so nothing here splits or
|
|
213
|
+
* concatenates a chunk on its way to a consumer.
|
|
214
|
+
*
|
|
215
|
+
* Design doc: 02-rendering-pipeline.md §"RSC → SSR → Client Hydration",
|
|
216
|
+
* §"Stream Tee"
|
|
217
|
+
*/
|
|
218
|
+
/**
|
|
219
|
+
* Every stream here carries one no-op `'error'` listener. `destroy(err)` emits
|
|
220
|
+
* `'error'`, and a stream whose consumer already detached (an iterator that
|
|
221
|
+
* returned, a pipeline that finished) or has not attached yet would otherwise
|
|
222
|
+
* turn a cancel into an uncaught exception. Real consumers attach their own
|
|
223
|
+
* listeners, which still see every error.
|
|
224
|
+
*/
|
|
225
|
+
function ignoreError() {}
|
|
226
|
+
/**
|
|
227
|
+
* Release a Node Flight source: destroy it with `reason`, which aborts the
|
|
228
|
+
* render behind it. Cancellation reasons in the pipeline are `unknown` (a Web
|
|
229
|
+
* `cancel(reason)` takes anything); `destroy` takes an `Error`. Never throws
|
|
230
|
+
* and never leaves an unhandled `'error'` event, whoever is listening.
|
|
231
|
+
*/
|
|
232
|
+
function destroyNodeFlight(stream, reason) {
|
|
233
|
+
if (!stream.listeners("error").includes(ignoreError)) stream.on("error", ignoreError);
|
|
234
|
+
const error = reason === void 0 || reason === null ? void 0 : reason instanceof Error ? reason : new Error(String(reason));
|
|
235
|
+
stream.destroy(error);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Pipe a Flight render into an object-mode Node source.
|
|
239
|
+
*
|
|
240
|
+
* - Strings pass through `toWellFormed()`, as Next does
|
|
241
|
+
* (`renderToNodeFlightStream`): SSR decodes the raw string while the inline
|
|
242
|
+
* copy round-trips through JSON + `TextEncoder`, which turns a lone
|
|
243
|
+
* surrogate into U+FFFD, so without it SSR and hydration see different
|
|
244
|
+
* text. Length in UTF-16 units is unchanged, so a text row's length header
|
|
245
|
+
* still holds.
|
|
246
|
+
* - `renderToPipeableStream` takes no `signal`. `abort()` is called when the
|
|
247
|
+
* request signal fires, when `timeoutMs` passes (design/02 §"Always Wire
|
|
248
|
+
* abort() to Both Request Signal AND Timeout"), and when the source is
|
|
249
|
+
* destroyed (a consumer cancelling), with the destroy reason — the reason a
|
|
250
|
+
* Web `cancel(reason)` hands Flight. The listener and the timer are
|
|
251
|
+
* released when the source closes.
|
|
252
|
+
*/
|
|
253
|
+
function pipeFlightToNode(flight, { signal, timeoutMs }) {
|
|
254
|
+
const onAbort = () => flight.abort(signal?.reason);
|
|
255
|
+
const timer = timeoutMs === void 0 ? void 0 : setTimeout(() => flight.abort(new RenderTimeoutError(timeoutMs, "Flight render")), timeoutMs);
|
|
256
|
+
const stream = new Transform({
|
|
257
|
+
objectMode: true,
|
|
258
|
+
transform(chunk, _encoding, callback) {
|
|
259
|
+
callback(null, typeof chunk === "string" ? chunk.toWellFormed() : chunk);
|
|
260
|
+
},
|
|
261
|
+
destroy(error, callback) {
|
|
262
|
+
signal?.removeEventListener("abort", onAbort);
|
|
263
|
+
clearTimeout(timer);
|
|
264
|
+
flight.abort(error ?? void 0);
|
|
265
|
+
callback(error);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
stream.on("error", ignoreError);
|
|
269
|
+
if (signal?.aborted) flight.abort(signal.reason);
|
|
270
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
271
|
+
flight.pipe(stream);
|
|
272
|
+
return stream;
|
|
273
|
+
}
|
|
274
|
+
/** Bytes a chunk occupies, for the tee's divergence guard. */
|
|
275
|
+
function chunkByteLength(chunk) {
|
|
276
|
+
return typeof chunk === "string" ? Buffer.byteLength(chunk) : chunk.byteLength;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* Tee a Node Flight source into two object-mode branches, with the contract
|
|
280
|
+
* of `teeWithErrorPropagation` (`stream-utils.ts`):
|
|
281
|
+
*
|
|
282
|
+
* - Each branch has its own queue, so the lagging branch buffers without
|
|
283
|
+
* bound until the divergence guard (`maxBufferBytes`, default 5MB, counted
|
|
284
|
+
* in UTF-8 bytes) cancels both. Nothing couples the branches' backpressure:
|
|
285
|
+
* the inline branch is not read until Fizz emits its first HTML chunk, and
|
|
286
|
+
* Fizz needs SSR to consume Flight first, so a `pipe()` into two
|
|
287
|
+
* PassThroughs would deadlock once the inline one filled.
|
|
288
|
+
* - The source is read at the pace of the faster branch (paused only while
|
|
289
|
+
* neither branch wants data), like a Web `tee()`.
|
|
290
|
+
* - An error on the source, or a branch destroyed before it ended, destroys
|
|
291
|
+
* the other branch with an error and destroys the source — which aborts the
|
|
292
|
+
* render — so neither consumer hangs and both are released.
|
|
293
|
+
*/
|
|
294
|
+
function teeNodeFlight(source, maxBufferBytes = DEFAULT_MAX_BUFFER_BYTES) {
|
|
295
|
+
let tornDown = false;
|
|
296
|
+
const branches = [createBranch(), createBranch()];
|
|
297
|
+
function createBranch() {
|
|
298
|
+
const branch = {
|
|
299
|
+
readable: new Readable({
|
|
300
|
+
objectMode: true,
|
|
301
|
+
read() {
|
|
302
|
+
settle(branch);
|
|
303
|
+
branch.wanting = true;
|
|
304
|
+
drain(branch);
|
|
305
|
+
},
|
|
306
|
+
destroy(error, callback) {
|
|
307
|
+
if (!branch.readable.readableEnded) teardown(error ?? /* @__PURE__ */ new Error("RSC stream tee branch cancelled"), error);
|
|
308
|
+
callback(error);
|
|
309
|
+
}
|
|
310
|
+
}),
|
|
311
|
+
queue: [],
|
|
312
|
+
heldBytes: 0,
|
|
313
|
+
pushedSizes: [],
|
|
314
|
+
wanting: false
|
|
315
|
+
};
|
|
316
|
+
branch.readable.on("error", ignoreError);
|
|
317
|
+
return branch;
|
|
318
|
+
}
|
|
319
|
+
/** Stop counting the pushed chunks the consumer has read. */
|
|
320
|
+
function settle(branch) {
|
|
321
|
+
while (branch.pushedSizes.length > branch.readable.readableLength) branch.heldBytes -= branch.pushedSizes.shift() ?? 0;
|
|
322
|
+
}
|
|
323
|
+
function drain(branch) {
|
|
324
|
+
while (branch.wanting) {
|
|
325
|
+
const chunk = branch.queue.shift();
|
|
326
|
+
if (chunk === void 0) break;
|
|
327
|
+
if (chunk === null) {
|
|
328
|
+
branch.wanting = false;
|
|
329
|
+
branch.readable.push(null);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
branch.pushedSizes.push(chunkByteLength(chunk));
|
|
333
|
+
branch.wanting = branch.readable.push(chunk);
|
|
334
|
+
}
|
|
335
|
+
if (branch.wanting && source.isPaused()) source.resume();
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Destroy both branches and the source. `branchError` is what the branches'
|
|
339
|
+
* consumers see; `sourceReason` is what Flight is aborted with — the
|
|
340
|
+
* consumer's own cancel reason, which may be `undefined`, as with a Web tee.
|
|
341
|
+
*/
|
|
342
|
+
function teardown(branchError, sourceReason) {
|
|
343
|
+
if (tornDown) return;
|
|
344
|
+
tornDown = true;
|
|
345
|
+
source.off("data", onData);
|
|
346
|
+
for (const branch of branches) {
|
|
347
|
+
branch.queue.length = 0;
|
|
348
|
+
branch.heldBytes = 0;
|
|
349
|
+
branch.pushedSizes.length = 0;
|
|
350
|
+
if (!branch.readable.destroyed) branch.readable.destroy(branchError);
|
|
351
|
+
}
|
|
352
|
+
source.destroy(sourceReason ?? void 0);
|
|
353
|
+
}
|
|
354
|
+
function onData(chunk) {
|
|
355
|
+
const bytes = chunkByteLength(chunk);
|
|
356
|
+
for (const branch of branches) {
|
|
357
|
+
branch.queue.push(chunk);
|
|
358
|
+
branch.heldBytes += bytes;
|
|
359
|
+
drain(branch);
|
|
360
|
+
}
|
|
361
|
+
for (const branch of branches) settle(branch);
|
|
362
|
+
const divergence = Math.max(branches[0].heldBytes, branches[1].heldBytes);
|
|
363
|
+
if (divergence > maxBufferBytes) {
|
|
364
|
+
const error = teeBufferExceeded(maxBufferBytes, divergence);
|
|
365
|
+
teardown(error, error);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (!branches[0].wanting && !branches[1].wanting) source.pause();
|
|
369
|
+
}
|
|
370
|
+
const finished = finishedState(source);
|
|
371
|
+
if (finished) {
|
|
372
|
+
if ("error" in finished) teardown(finished.error, finished.error);
|
|
373
|
+
else for (const branch of branches) branch.readable.push(null);
|
|
374
|
+
return [branches[0].readable, branches[1].readable];
|
|
375
|
+
}
|
|
376
|
+
source.on("data", onData);
|
|
377
|
+
source.on("end", () => {
|
|
378
|
+
for (const branch of branches) {
|
|
379
|
+
branch.queue.push(null);
|
|
380
|
+
drain(branch);
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
source.on("error", (error) => teardown(error, error));
|
|
384
|
+
source.on("close", () => {
|
|
385
|
+
if (!source.readableEnded) teardown(/* @__PURE__ */ new Error("RSC stream closed before it ended"), void 0);
|
|
386
|
+
});
|
|
387
|
+
return [branches[0].readable, branches[1].readable];
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* A Node Flight source as a `Response` (`NodeBodyResponse`): its body stays a
|
|
391
|
+
* Node stream all the way to the adapter, which pipes it to the socket
|
|
392
|
+
* (LOCAL-1475). Nothing in the Flight path converts it to a Web stream.
|
|
393
|
+
*
|
|
394
|
+
* Every chunk that arrives in one tick goes out as one buffer, with string
|
|
395
|
+
* chunks encoded straight into it. React writes a flush synchronously, and
|
|
396
|
+
* its Node build passes each long row as its own string: a heavy payload
|
|
397
|
+
* arrives as ~4x the chunks of the Web build's 4KB views, and the socket pays
|
|
398
|
+
* per write. The body pauses the source while the client is slow (a payload
|
|
399
|
+
* never piles up in memory), destroying it early destroys the source (which
|
|
400
|
+
* aborts the render), and an error or early close on the source ends it.
|
|
401
|
+
* Wired by hand rather than with `pipeline()`, which allocates an
|
|
402
|
+
* AbortController and an error on every finish.
|
|
403
|
+
*/
|
|
404
|
+
function nodeFlightResponse(source, init) {
|
|
405
|
+
return new NodeBodyResponse(batchFlightBytes(source), init);
|
|
406
|
+
}
|
|
407
|
+
/** Largest batch the payload body coalesces before pushing (and checking backpressure). */
|
|
408
|
+
var MAX_BATCH_BYTES = 65536;
|
|
409
|
+
function batchFlightBytes(source) {
|
|
410
|
+
let batch = [];
|
|
411
|
+
let batchBytes = 0;
|
|
412
|
+
let scheduled = false;
|
|
413
|
+
let detach = () => {};
|
|
414
|
+
const emit = () => {
|
|
415
|
+
scheduled = false;
|
|
416
|
+
if (batch.length === 0 || bytes.destroyed) return;
|
|
417
|
+
const merged = Buffer.allocUnsafe(batchBytes);
|
|
418
|
+
let offset = 0;
|
|
419
|
+
for (const chunk of batch) if (typeof chunk === "string") offset += merged.write(chunk, offset);
|
|
420
|
+
else {
|
|
421
|
+
merged.set(chunk, offset);
|
|
422
|
+
offset += chunk.byteLength;
|
|
423
|
+
}
|
|
424
|
+
batch = [];
|
|
425
|
+
batchBytes = 0;
|
|
426
|
+
if (!bytes.push(merged)) source.pause();
|
|
427
|
+
};
|
|
428
|
+
const bytes = new Readable({
|
|
429
|
+
read() {
|
|
430
|
+
if (source.isPaused()) source.resume();
|
|
431
|
+
},
|
|
432
|
+
destroy(error, callback) {
|
|
433
|
+
batch = [];
|
|
434
|
+
batchBytes = 0;
|
|
435
|
+
detach();
|
|
436
|
+
if (!source.readableEnded) destroyNodeFlight(source, error ?? void 0);
|
|
437
|
+
callback(error);
|
|
438
|
+
}
|
|
439
|
+
});
|
|
440
|
+
bytes.on("error", ignoreError);
|
|
441
|
+
const finished = finishedState(source);
|
|
442
|
+
if (finished) {
|
|
443
|
+
if ("error" in finished) bytes.destroy(finished.error);
|
|
444
|
+
else bytes.push(null);
|
|
445
|
+
return bytes;
|
|
446
|
+
}
|
|
447
|
+
const onData = (chunk) => {
|
|
448
|
+
batch.push(chunk);
|
|
449
|
+
batchBytes += chunkByteLength(chunk);
|
|
450
|
+
if (batchBytes >= MAX_BATCH_BYTES) emit();
|
|
451
|
+
else if (!scheduled) {
|
|
452
|
+
scheduled = true;
|
|
453
|
+
queueMicrotask(emit);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
const onEnd = () => {
|
|
457
|
+
emit();
|
|
458
|
+
bytes.push(null);
|
|
459
|
+
};
|
|
460
|
+
const onError = (error) => {
|
|
461
|
+
bytes.destroy(error);
|
|
462
|
+
};
|
|
463
|
+
const onClose = () => {
|
|
464
|
+
if (!source.readableEnded) bytes.destroy(source.errored ?? /* @__PURE__ */ new Error("RSC stream closed before it ended"));
|
|
465
|
+
};
|
|
466
|
+
detach = () => {
|
|
467
|
+
source.off("data", onData);
|
|
468
|
+
source.off("end", onEnd);
|
|
469
|
+
source.off("error", onError);
|
|
470
|
+
source.off("close", onClose);
|
|
471
|
+
};
|
|
472
|
+
source.on("data", onData);
|
|
473
|
+
source.on("end", onEnd);
|
|
474
|
+
source.on("error", onError);
|
|
475
|
+
source.on("close", onClose);
|
|
476
|
+
return bytes;
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Why `source` will never emit again, if it was destroyed or ended before a
|
|
480
|
+
* consumer attached: `'end'`, `'error'` and `'close'` have already fired,
|
|
481
|
+
* so a consumer that only listens would wait forever. `null` while live.
|
|
482
|
+
*/
|
|
483
|
+
function finishedState(source) {
|
|
484
|
+
if (source.readableEnded) return { ended: true };
|
|
485
|
+
if (!source.destroyed) return null;
|
|
486
|
+
return { error: source.errored ?? /* @__PURE__ */ new Error("RSC stream closed before it ended") };
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Settles once a chunk (or the end) can be read from `source`, without
|
|
490
|
+
* consuming it: the chunk stays in the source for whatever reads it next.
|
|
491
|
+
* Rejects if the source errors first.
|
|
492
|
+
*
|
|
493
|
+
* The `'readable'` listener is removed on settle; Node restores the stream's
|
|
494
|
+
* flowing state on the next tick, so a consumer attached afterwards (a pipe,
|
|
495
|
+
* a `'data'` listener) still starts it.
|
|
496
|
+
*/
|
|
497
|
+
function whenNodeFlightReadable(source) {
|
|
498
|
+
if (source.readableLength > 0) return Promise.resolve();
|
|
499
|
+
const finished = finishedState(source);
|
|
500
|
+
if (finished) return "error" in finished ? Promise.reject(finished.error) : Promise.resolve();
|
|
501
|
+
return new Promise((resolve, reject) => {
|
|
502
|
+
const settle = (error) => {
|
|
503
|
+
source.off("readable", onReadable);
|
|
504
|
+
source.off("error", settle);
|
|
505
|
+
source.off("close", onClose);
|
|
506
|
+
if (error) reject(error);
|
|
507
|
+
else resolve();
|
|
508
|
+
};
|
|
509
|
+
const onReadable = () => settle();
|
|
510
|
+
const onClose = () => settle(source.errored ?? void 0);
|
|
511
|
+
source.on("readable", onReadable);
|
|
512
|
+
source.on("error", settle);
|
|
513
|
+
source.on("close", onClose);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
517
|
+
export { destroyNodeFlight, nodeFlightResponse, pipeFlightToNode, teeNodeFlight, whenNodeFlightReadable };
|
|
518
|
+
|
|
519
|
+
//# sourceMappingURL=flight-source-node-0dE-t3kq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flight-source-node-0dE-t3kq.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 { RenderTimeoutError } from './render-timeout.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 onAbort = (): void => flight.abort(signal?.reason);\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 signal?.removeEventListener('abort', onAbort);\n clearTimeout(timer);\n // A no-op once Flight has finished (it ignores abort after close).\n flight.abort(error ?? undefined);\n callback(error);\n },\n });\n stream.on('error', ignoreError);\n if (signal?.aborted) flight.abort(signal.reason);\n else signal?.addEventListener('abort', onAbort, { once: true });\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,SAAS;IAChB,IAAI,KAA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./scan-BoP17W3w.js";
|
|
2
2
|
import { i as detectDirective, n as classifyModule } from "./classify-2Yp3xJY1.js";
|
|
3
|
-
import { n as stitchImportChains } from "./chains-
|
|
3
|
+
import { n as stitchImportChains } from "./chains-e_Buf9vg.js";
|
|
4
4
|
import { n as importSignals, r as poisoningsFor, t as collectImportSpecifiers } from "./poison-scan-C4FgMxFl.js";
|
|
5
5
|
import { normalizePath } from "vite";
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
@@ -148,4 +148,4 @@ async function classifyLiveProject(ctx) {
|
|
|
148
148
|
//#endregion
|
|
149
149
|
export { classifyLiveFile, classifyLiveProject };
|
|
150
150
|
|
|
151
|
-
//# sourceMappingURL=live-graph-
|
|
151
|
+
//# sourceMappingURL=live-graph-tSWrv8eH.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"live-graph-BhtrZpRd.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;;;;;;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AM,SAAS;EACzB,OAAO;CACT;AACF;;;;;;;;AAsBA,eAAsB,oBAAoB,KAAmD;CAC3F,MAAM,QAAkB,CAAC;CACzB,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
|
+
{"version":3,"file":"live-graph-tSWrv8eH.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,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