@timber-js/app 0.2.0-alpha.97 → 0.2.0-alpha.98
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/{metadata-routes-DS3eKNmf.js → metadata-routes-BU684ls2.js} +1 -1
- package/dist/_chunks/{metadata-routes-DS3eKNmf.js.map → metadata-routes-BU684ls2.js.map} +1 -1
- package/dist/_chunks/segment-classify-BjfuctV2.js +137 -0
- package/dist/_chunks/segment-classify-BjfuctV2.js.map +1 -0
- package/dist/_chunks/{interception-BbqMCVXa.js → walkers-VOXgavMF.js} +61 -85
- package/dist/_chunks/walkers-VOXgavMF.js.map +1 -0
- package/dist/adapters/nitro.d.ts.map +1 -1
- package/dist/adapters/nitro.js +55 -5
- package/dist/adapters/nitro.js.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +189 -62
- package/dist/index.js.map +1 -1
- package/dist/plugins/build-report.d.ts +6 -4
- package/dist/plugins/build-report.d.ts.map +1 -1
- package/dist/plugins/dev-404-page.d.ts +8 -18
- package/dist/plugins/dev-404-page.d.ts.map +1 -1
- package/dist/routing/index.d.ts +5 -3
- package/dist/routing/index.d.ts.map +1 -1
- package/dist/routing/index.js +3 -3
- package/dist/routing/scanner.d.ts +1 -10
- package/dist/routing/scanner.d.ts.map +1 -1
- package/dist/routing/segment-classify.d.ts +37 -8
- package/dist/routing/segment-classify.d.ts.map +1 -1
- package/dist/routing/types.d.ts +63 -23
- package/dist/routing/types.d.ts.map +1 -1
- package/dist/routing/walkers.d.ts +51 -0
- package/dist/routing/walkers.d.ts.map +1 -0
- package/dist/server/action-handler.d.ts.map +1 -1
- package/dist/server/dev-holding-server.d.ts +4 -2
- package/dist/server/dev-holding-server.d.ts.map +1 -1
- package/dist/server/html-injector-core.d.ts +212 -0
- package/dist/server/html-injector-core.d.ts.map +1 -0
- package/dist/server/html-injectors.d.ts +59 -59
- package/dist/server/html-injectors.d.ts.map +1 -1
- package/dist/server/internal.js +710 -563
- package/dist/server/internal.js.map +1 -1
- package/dist/server/node-stream-transforms.d.ts +46 -49
- package/dist/server/node-stream-transforms.d.ts.map +1 -1
- package/dist/server/pipeline-helpers.d.ts +88 -0
- package/dist/server/pipeline-helpers.d.ts.map +1 -0
- package/dist/server/pipeline-phases.d.ts +97 -0
- package/dist/server/pipeline-phases.d.ts.map +1 -0
- package/dist/server/pipeline.d.ts +53 -32
- package/dist/server/pipeline.d.ts.map +1 -1
- package/dist/server/port-resolution.d.ts +117 -0
- package/dist/server/port-resolution.d.ts.map +1 -0
- package/dist/server/route-matcher.d.ts +20 -47
- package/dist/server/route-matcher.d.ts.map +1 -1
- package/dist/server/rsc-entry/index.d.ts.map +1 -1
- package/dist/server/rsc-entry/wrap-action-dispatch.d.ts +74 -0
- package/dist/server/rsc-entry/wrap-action-dispatch.d.ts.map +1 -0
- package/dist/server/status-code-resolver.d.ts +16 -11
- package/dist/server/status-code-resolver.d.ts.map +1 -1
- package/dist/server/tree-builder.d.ts.map +1 -1
- package/dist/utils/directive-parser.d.ts +0 -45
- package/dist/utils/directive-parser.d.ts.map +1 -1
- package/package.json +7 -6
- package/src/adapters/nitro.ts +55 -5
- package/src/cli.ts +0 -0
- package/src/index.ts +84 -31
- package/src/plugins/build-report.ts +13 -22
- package/src/plugins/dev-404-page.ts +15 -41
- package/src/plugins/routing.ts +14 -12
- package/src/routing/codegen.ts +1 -1
- package/src/routing/convention-lint.ts +4 -4
- package/src/routing/index.ts +5 -3
- package/src/routing/interception.ts +1 -1
- package/src/routing/scanner.ts +17 -93
- package/src/routing/segment-classify.ts +107 -8
- package/src/routing/status-file-lint.ts +3 -3
- package/src/routing/types.ts +63 -23
- package/src/routing/walkers.ts +90 -0
- package/src/server/action-handler.ts +6 -0
- package/src/server/deny-renderer.ts +5 -5
- package/src/server/dev-holding-server.ts +4 -2
- package/src/server/fallback-error.ts +1 -1
- package/src/server/html-injector-core.ts +403 -0
- package/src/server/html-injectors.ts +158 -297
- package/src/server/node-stream-transforms.ts +108 -248
- package/src/server/pipeline-helpers.ts +180 -0
- package/src/server/pipeline-phases.ts +591 -0
- package/src/server/pipeline.ts +76 -539
- package/src/server/port-resolution.ts +215 -0
- package/src/server/route-element-builder.ts +1 -1
- package/src/server/route-matcher.ts +28 -60
- package/src/server/rsc-entry/api-handler.ts +2 -2
- package/src/server/rsc-entry/error-renderer.ts +1 -1
- package/src/server/rsc-entry/index.ts +52 -98
- package/src/server/rsc-entry/wrap-action-dispatch.ts +156 -0
- package/src/server/sitemap-generator.ts +1 -1
- package/src/server/slot-resolver.ts +1 -1
- package/src/server/status-code-resolver.ts +112 -128
- package/src/server/tree-builder.ts +6 -4
- package/src/utils/directive-parser.ts +0 -392
- package/LICENSE +0 -8
- package/dist/_chunks/interception-BbqMCVXa.js.map +0 -1
- package/dist/_chunks/segment-classify-BDNn6EzD.js +0 -65
- package/dist/_chunks/segment-classify-BDNn6EzD.js.map +0 -1
- package/dist/server/manifest-status-resolver.d.ts +0 -58
- package/dist/server/manifest-status-resolver.d.ts.map +0 -1
- package/src/server/manifest-status-resolver.ts +0 -215
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTML injector core — pure stateful helpers for streaming HTML post-processing.
|
|
3
|
+
*
|
|
4
|
+
* These helpers contain the actual byte/string logic for the held-flush
|
|
5
|
+
* streaming pipeline (buffered transforms, suffix moving, head injection,
|
|
6
|
+
* RSC flight interleaving). They are stream-shape agnostic: they know
|
|
7
|
+
* nothing about Web `TransformStream` or Node.js `Transform` and contain
|
|
8
|
+
* no `setImmediate` scheduling or controller plumbing.
|
|
9
|
+
*
|
|
10
|
+
* The Web Stream wrapper (`html-injectors.ts`) and the Node Stream wrapper
|
|
11
|
+
* (`node-stream-transforms.ts`) compose these helpers behind whichever
|
|
12
|
+
* stream shape their target runtime needs:
|
|
13
|
+
*
|
|
14
|
+
* - On Cloudflare/edge: Web `TransformStream` wraps the helpers.
|
|
15
|
+
* - On Node.js/Bun: Node `Transform` wraps the helpers (faster — C++ streams).
|
|
16
|
+
*
|
|
17
|
+
* Keeping this module split per-shape (rather than one file exporting both)
|
|
18
|
+
* preserves the build-time tree-shake: Cloudflare bundles never import
|
|
19
|
+
* `node:stream` even transitively. Only the helpers below are shared.
|
|
20
|
+
*
|
|
21
|
+
* **Pure functions only.** Anything that touches a stream API, schedules
|
|
22
|
+
* a tick, or owns a controller belongs in the wrapper, not here.
|
|
23
|
+
*
|
|
24
|
+
* Design docs: 02-rendering-pipeline.md §"Streaming Constraints", 18-build-system.md §"Entry Files"
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { createMachine, type Machine } from '../utils/state-machine.js';
|
|
28
|
+
import { flightChunkScript } from './flight-scripts.js';
|
|
29
|
+
import {
|
|
30
|
+
flightInjectionTransitions,
|
|
31
|
+
isHtmlDone,
|
|
32
|
+
isPullDone,
|
|
33
|
+
type FlightInjectionState,
|
|
34
|
+
type FlightInjectionEvent,
|
|
35
|
+
} from './flight-injection-state.js';
|
|
36
|
+
import { withTimeout, RenderTimeoutError } from './render-timeout.js';
|
|
37
|
+
|
|
38
|
+
// ─── Encoders / Constants ────────────────────────────────────────────────────
|
|
39
|
+
|
|
40
|
+
const encoder = new TextEncoder();
|
|
41
|
+
|
|
42
|
+
/** Closing tags React Fizz emits inside the shell chunk. */
|
|
43
|
+
export const SUFFIX = '</body></html>';
|
|
44
|
+
/** UTF-8 bytes of {@link SUFFIX}. Cached so wrappers don't re-encode per request. */
|
|
45
|
+
export const SUFFIX_BYTES: Uint8Array = encoder.encode(SUFFIX);
|
|
46
|
+
|
|
47
|
+
/** Encode a UTF-8 string. Convenience for wrappers that need a single source of truth. */
|
|
48
|
+
export function encodeUtf8(text: string): Uint8Array {
|
|
49
|
+
return encoder.encode(text);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// ─── Buffered Aggregator ─────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Pure buffer state for the buffered transform.
|
|
56
|
+
*
|
|
57
|
+
* Both Web and Node wrappers want the same behaviour: collect chunks that
|
|
58
|
+
* arrive in the same event-loop tick, decide whether the buffer has grown
|
|
59
|
+
* beyond `maxBufferByteLength` and must flush synchronously, then emit a
|
|
60
|
+
* single concatenated chunk on the next tick.
|
|
61
|
+
*
|
|
62
|
+
* The only thing the two wrappers disagree on is *who schedules the tick*
|
|
63
|
+
* (`setImmediate` callback vs Promise-based) and *how to push the merged
|
|
64
|
+
* chunk* (`controller.enqueue` vs `transform.push`). This class owns
|
|
65
|
+
* everything else.
|
|
66
|
+
*/
|
|
67
|
+
export class BufferAggregator {
|
|
68
|
+
private chunks: Uint8Array[] = [];
|
|
69
|
+
private byteLength = 0;
|
|
70
|
+
|
|
71
|
+
constructor(private readonly maxBufferByteLength: number = Infinity) {}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Append a chunk. Returns `true` if the caller should flush synchronously
|
|
75
|
+
* right now (the buffer has reached the byte cap), `false` if a deferred
|
|
76
|
+
* tick-end flush is sufficient.
|
|
77
|
+
*/
|
|
78
|
+
append(chunk: Uint8Array): boolean {
|
|
79
|
+
this.chunks.push(chunk);
|
|
80
|
+
this.byteLength += chunk.byteLength;
|
|
81
|
+
return this.byteLength >= this.maxBufferByteLength;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Drain the buffer into a single concatenated chunk, or `null` if empty. */
|
|
85
|
+
drain(): Uint8Array | null {
|
|
86
|
+
if (this.chunks.length === 0) return null;
|
|
87
|
+
|
|
88
|
+
const merged = new Uint8Array(this.byteLength);
|
|
89
|
+
let offset = 0;
|
|
90
|
+
for (const chunk of this.chunks) {
|
|
91
|
+
merged.set(chunk, offset);
|
|
92
|
+
offset += chunk.byteLength;
|
|
93
|
+
}
|
|
94
|
+
this.chunks = [];
|
|
95
|
+
this.byteLength = 0;
|
|
96
|
+
return merged;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
get bufferedByteLength(): number {
|
|
100
|
+
return this.byteLength;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
get isEmpty(): boolean {
|
|
104
|
+
return this.chunks.length === 0;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// ─── Suffix Mover ────────────────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Result of feeding one chunk through the suffix-mover state.
|
|
112
|
+
*
|
|
113
|
+
* - `passthrough` — already found and removed the suffix on a previous chunk.
|
|
114
|
+
* Caller emits the chunk unchanged.
|
|
115
|
+
* - `noSuffix` — current chunk does not contain the suffix. Caller emits unchanged.
|
|
116
|
+
* - `suffixFound` — caller emits `before` and `after` (skipping the suffix
|
|
117
|
+
* itself). The suffix will be re-emitted later by {@link suffixFlush}.
|
|
118
|
+
*/
|
|
119
|
+
export type SuffixChunkResult =
|
|
120
|
+
| { kind: 'passthrough' }
|
|
121
|
+
| { kind: 'noSuffix' }
|
|
122
|
+
| { kind: 'suffixFound'; before: Uint8Array | null; after: Uint8Array | null };
|
|
123
|
+
|
|
124
|
+
export interface SuffixState {
|
|
125
|
+
found: boolean;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export function createSuffixState(): SuffixState {
|
|
129
|
+
return { found: false };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Search a chunk for {@link SUFFIX}. If found, mark state and return the
|
|
134
|
+
* surrounding bytes (the caller emits them; the suffix is held for the
|
|
135
|
+
* end of the stream). The bytes-vs-text dance matches what both Web and
|
|
136
|
+
* Node implementations did before extraction — search via decoded UTF-8
|
|
137
|
+
* to avoid splitting multi-byte characters at the suffix boundary.
|
|
138
|
+
*/
|
|
139
|
+
export function processSuffixChunk(state: SuffixState, chunk: Uint8Array): SuffixChunkResult {
|
|
140
|
+
if (state.found) return { kind: 'passthrough' };
|
|
141
|
+
|
|
142
|
+
const text = new TextDecoder().decode(chunk, { stream: true });
|
|
143
|
+
const idx = text.indexOf(SUFFIX);
|
|
144
|
+
if (idx === -1) return { kind: 'noSuffix' };
|
|
145
|
+
|
|
146
|
+
state.found = true;
|
|
147
|
+
|
|
148
|
+
// Whole chunk was the suffix — nothing to emit before/after.
|
|
149
|
+
if (chunk.byteLength === SUFFIX_BYTES.byteLength) {
|
|
150
|
+
return { kind: 'suffixFound', before: null, after: null };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const beforeText = text.slice(0, idx);
|
|
154
|
+
const afterText = text.slice(idx + SUFFIX.length);
|
|
155
|
+
return {
|
|
156
|
+
kind: 'suffixFound',
|
|
157
|
+
before: beforeText ? encoder.encode(beforeText) : null,
|
|
158
|
+
after: afterText ? encoder.encode(afterText) : null,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Final emit for the suffix mover. Always returns the suffix bytes — even
|
|
164
|
+
* if no suffix was ever observed in the input — so output is well-formed.
|
|
165
|
+
*/
|
|
166
|
+
export function suffixFlush(_state: SuffixState): Uint8Array {
|
|
167
|
+
return SUFFIX_BYTES;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// ─── Tag Injector (head / body) ──────────────────────────────────────────────
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Pure state for `injectHead`-style transforms: scan for a target tag,
|
|
174
|
+
* inject `content` once at the matching position, then pass everything
|
|
175
|
+
* else through. We keep a small trailing string buffer (just under the
|
|
176
|
+
* length of the target tag) so the tag can be detected even when split
|
|
177
|
+
* across chunk boundaries.
|
|
178
|
+
*
|
|
179
|
+
* The `decoder` is a long-lived `TextDecoder` reused across every chunk
|
|
180
|
+
* with `{ stream: true }`. This is required so a UTF-8 codepoint that
|
|
181
|
+
* spans two chunks (e.g. the bytes of `é` arriving in two halves) is
|
|
182
|
+
* reassembled correctly. A fresh decoder per chunk would drop or
|
|
183
|
+
* replace the partial codepoint and corrupt streamed HTML.
|
|
184
|
+
*/
|
|
185
|
+
export interface InjectorState {
|
|
186
|
+
injected: boolean;
|
|
187
|
+
tail: string;
|
|
188
|
+
readonly content: string;
|
|
189
|
+
readonly targetTag: string;
|
|
190
|
+
readonly position: 'before' | 'after';
|
|
191
|
+
readonly tailLen: number;
|
|
192
|
+
readonly decoder: TextDecoder;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export interface InjectorOptions {
|
|
196
|
+
content: string;
|
|
197
|
+
targetTag: string;
|
|
198
|
+
position?: 'before' | 'after';
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function createInjectorState(options: InjectorOptions): InjectorState {
|
|
202
|
+
return {
|
|
203
|
+
injected: false,
|
|
204
|
+
tail: '',
|
|
205
|
+
content: options.content,
|
|
206
|
+
targetTag: options.targetTag,
|
|
207
|
+
position: options.position ?? 'before',
|
|
208
|
+
tailLen: options.targetTag.length - 1,
|
|
209
|
+
decoder: new TextDecoder('utf-8'),
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Result of feeding one chunk through {@link processInjectorChunk}.
|
|
215
|
+
*
|
|
216
|
+
* - `passthrough` — already injected. Emit `chunk` unchanged.
|
|
217
|
+
* - `emit` — emit the returned bytes (or nothing if `null`).
|
|
218
|
+
*
|
|
219
|
+
* Note: when not yet injected and the target tag is not present, the
|
|
220
|
+
* helper still emits the *safe head* of the buffer — everything except
|
|
221
|
+
* the trailing `tailLen` characters that might be the start of the
|
|
222
|
+
* target tag spilled into the next chunk. The unsafe tail is held in
|
|
223
|
+
* `state.tail` for the next call.
|
|
224
|
+
*/
|
|
225
|
+
export type InjectorChunkResult =
|
|
226
|
+
| { kind: 'passthrough' }
|
|
227
|
+
| { kind: 'emit'; bytes: Uint8Array | null };
|
|
228
|
+
|
|
229
|
+
export function processInjectorChunk(state: InjectorState, chunk: Uint8Array): InjectorChunkResult {
|
|
230
|
+
if (state.injected) return { kind: 'passthrough' };
|
|
231
|
+
|
|
232
|
+
// Reuse the long-lived decoder so split UTF-8 codepoints are preserved
|
|
233
|
+
// across chunk boundaries. See comment on InjectorState.decoder.
|
|
234
|
+
const decoded = state.decoder.decode(chunk, { stream: true });
|
|
235
|
+
const text = state.tail + decoded;
|
|
236
|
+
const tagIndex = text.indexOf(state.targetTag);
|
|
237
|
+
|
|
238
|
+
if (tagIndex !== -1) {
|
|
239
|
+
const splitPoint = state.position === 'before' ? tagIndex : tagIndex + state.targetTag.length;
|
|
240
|
+
const before = text.slice(0, splitPoint);
|
|
241
|
+
const after = text.slice(splitPoint);
|
|
242
|
+
state.injected = true;
|
|
243
|
+
state.tail = '';
|
|
244
|
+
return { kind: 'emit', bytes: encoder.encode(before + state.content + after) };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Tag not yet seen — flush everything except the last tailLen chars,
|
|
248
|
+
// which might be the start of the target tag split across chunks.
|
|
249
|
+
const safeEnd = Math.max(0, text.length - state.tailLen);
|
|
250
|
+
const safe = safeEnd > 0 ? text.slice(0, safeEnd) : '';
|
|
251
|
+
state.tail = text.slice(safeEnd);
|
|
252
|
+
return { kind: 'emit', bytes: safe ? encoder.encode(safe) : null };
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Final emit for the injector. If the target tag never appeared, the
|
|
257
|
+
* leftover tail bytes are returned so they aren't lost. (The injection
|
|
258
|
+
* itself is silently skipped — same behaviour as before extraction.)
|
|
259
|
+
*/
|
|
260
|
+
export function injectorFlush(state: InjectorState): Uint8Array | null {
|
|
261
|
+
if (!state.injected && state.tail) return encoder.encode(state.tail);
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ─── Flight Injection Core ───────────────────────────────────────────────────
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* Pure async core of the RSC flight-injection transform.
|
|
269
|
+
*
|
|
270
|
+
* Both wrappers (Web `TransformStream` and Node `Transform`) implement the
|
|
271
|
+
* exact same protocol around an RSC reader:
|
|
272
|
+
*
|
|
273
|
+
* 1. On the first HTML chunk, send `FIRST_CHUNK` and start the pull loop.
|
|
274
|
+
* 2. The pull loop reads from `rscReader` (timeout-guarded), wraps each
|
|
275
|
+
* chunk in a `<script>` via `flightChunkScript`, and pushes it onto a
|
|
276
|
+
* pending queue. Between reads, it yields with a single-shot
|
|
277
|
+
* `setImmediate` so HTML chunks get event-loop priority — and after
|
|
278
|
+
* yielding, it drains the queue (via the wrapper's `onYieldDrain`)
|
|
279
|
+
* so flight data reaches the client at shell-flush time.
|
|
280
|
+
* 3. After every emitted HTML chunk, the wrapper drains the queue.
|
|
281
|
+
* 4. On `flush()` the wrapper sends `HTML_DONE` and awaits `pullPromise`.
|
|
282
|
+
* No polling — just `.then()`.
|
|
283
|
+
*
|
|
284
|
+
* The wrappers only differ in:
|
|
285
|
+
* - How they push bytes (controller.enqueue vs transform.push).
|
|
286
|
+
* - How they signal a terminal error (controller.error vs transform.destroy).
|
|
287
|
+
*
|
|
288
|
+
* This class owns the state machine, the pending queue, and the pull
|
|
289
|
+
* loop itself. The wrapper supplies the drain callback and consumes the
|
|
290
|
+
* pending queue + machine state to decide what to push.
|
|
291
|
+
*
|
|
292
|
+
* **No polling.** See design/02-rendering-pipeline.md §"No Polling".
|
|
293
|
+
* **Always timeout-guarded reads.** Per design/02 §"Streaming Constraints".
|
|
294
|
+
*/
|
|
295
|
+
export class FlightInjectorCore {
|
|
296
|
+
readonly machine: Machine<FlightInjectionState, FlightInjectionEvent>;
|
|
297
|
+
/** Script chunks waiting to be drained between HTML chunks. */
|
|
298
|
+
readonly pending: Uint8Array[] = [];
|
|
299
|
+
|
|
300
|
+
private readonly rscReader: ReadableStreamDefaultReader<Uint8Array>;
|
|
301
|
+
private readonly timeoutMs: number;
|
|
302
|
+
private readonly decoder = new TextDecoder('utf-8', { fatal: true });
|
|
303
|
+
private pullPromise: Promise<void> | null = null;
|
|
304
|
+
|
|
305
|
+
constructor(rscStream: ReadableStream<Uint8Array>, renderTimeoutMs?: number) {
|
|
306
|
+
this.rscReader = rscStream.getReader();
|
|
307
|
+
this.timeoutMs = renderTimeoutMs ?? 30_000;
|
|
308
|
+
this.machine = createMachine<FlightInjectionState, FlightInjectionEvent>({
|
|
309
|
+
initial: { phase: 'init' },
|
|
310
|
+
transitions: flightInjectionTransitions,
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Tell the machine the first HTML chunk has arrived. Idempotent-ish: caller checks. */
|
|
315
|
+
notifyFirstChunk(): void {
|
|
316
|
+
this.machine.send({ type: 'FIRST_CHUNK' });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Tell the machine HTML output is finished — pull loop will stop yielding. */
|
|
320
|
+
notifyHtmlDone(): void {
|
|
321
|
+
this.machine.send({ type: 'HTML_DONE' });
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
get isInit(): boolean {
|
|
325
|
+
return this.machine.state.phase === 'init';
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
get isPullDone(): boolean {
|
|
329
|
+
return isPullDone(this.machine.state);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
get hasPullPromise(): boolean {
|
|
333
|
+
return this.pullPromise !== null;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Get (or start) the pull-loop promise. The wrapper calls this from
|
|
338
|
+
* `flush()` and chains `.then()` onto it — never `await` without an
|
|
339
|
+
* existing finish callback (we don't want to block transform()).
|
|
340
|
+
*
|
|
341
|
+
* `onYieldDrain` is invoked between RSC reads while HTML is still
|
|
342
|
+
* streaming. It must drain the pending queue into the output stream.
|
|
343
|
+
*/
|
|
344
|
+
ensurePullLoop(onYieldDrain: () => void): Promise<void> {
|
|
345
|
+
if (!this.pullPromise) {
|
|
346
|
+
this.pullPromise = this.runPullLoop(onYieldDrain);
|
|
347
|
+
}
|
|
348
|
+
return this.pullPromise;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Get the current terminal error if the machine is in the error phase,
|
|
353
|
+
* else `null`. Wrappers use this after a drain to decide whether to
|
|
354
|
+
* `controller.error()` / `transform.destroy()`.
|
|
355
|
+
*/
|
|
356
|
+
get terminalError(): unknown {
|
|
357
|
+
return this.machine.state.phase === 'error' ? this.machine.state.error : null;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
private async runPullLoop(onYieldDrain: () => void): Promise<void> {
|
|
361
|
+
// Yield once so the first HTML shell chunk flows through the wrapper
|
|
362
|
+
// before we start reading RSC data.
|
|
363
|
+
await new Promise<void>((r) => setImmediate(r));
|
|
364
|
+
|
|
365
|
+
try {
|
|
366
|
+
for (;;) {
|
|
367
|
+
// Guard each read with a timeout so a permanently hung RSC stream
|
|
368
|
+
// eventually aborts. See design/02 §"Streaming Constraints".
|
|
369
|
+
const readPromise = this.rscReader.read();
|
|
370
|
+
const { done, value } =
|
|
371
|
+
this.timeoutMs > 0
|
|
372
|
+
? await withTimeout(readPromise, this.timeoutMs, 'RSC stream read timed out')
|
|
373
|
+
: await readPromise;
|
|
374
|
+
|
|
375
|
+
if (done) {
|
|
376
|
+
this.machine.send({ type: 'PULL_DONE' });
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const decoded = this.decoder.decode(value, { stream: true });
|
|
381
|
+
this.pending.push(encoder.encode(flightChunkScript(decoded)));
|
|
382
|
+
|
|
383
|
+
// Yield between reads so HTML chunks get priority — but only while
|
|
384
|
+
// HTML is still streaming. Once flush() fires (HTML_DONE), drain
|
|
385
|
+
// without yielding so remaining RSC data doesn't stall.
|
|
386
|
+
if (!isHtmlDone(this.machine.state)) {
|
|
387
|
+
await new Promise<void>((r) => setImmediate(r));
|
|
388
|
+
// After yielding, drain. Without this, hydration blocks waiting
|
|
389
|
+
// for flight data stuck in pending[]. Safe because we're between
|
|
390
|
+
// event-loop ticks (no transform() call mid-execution → no
|
|
391
|
+
// mid-tag risk; the buffered transform upstream coalesced HTML
|
|
392
|
+
// chunks to coherent fragments).
|
|
393
|
+
if (this.pending.length > 0) onYieldDrain();
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
} catch (err) {
|
|
397
|
+
if (err instanceof RenderTimeoutError) {
|
|
398
|
+
this.rscReader.cancel(err).catch(() => {});
|
|
399
|
+
}
|
|
400
|
+
this.machine.send({ type: 'PULL_ERROR', error: err });
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|