@qredence/fleet 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/web/client/assets/{artifacts-panel-Qd6JlHzz.js → artifacts-panel-C69vz-oo.js} +1 -1
  3. package/dist/web/client/assets/{badge-BjFxrtmB.js → badge-DOGhnsYk.js} +7 -7
  4. package/dist/web/client/assets/{chat-command-palette-CPlJp2cO.js → chat-command-palette-wyZjTNa8.js} +1 -1
  5. package/dist/web/client/assets/{chunk-YOKDWASO-C8deEx7Z.js → chunk-YOKDWASO-Dego39cu.js} +4 -4
  6. package/dist/web/client/assets/{dist-CZDnnosQ.js → dist-QgsZ1U9l.js} +1 -1
  7. package/dist/web/client/assets/{highlighted-body-KPVGNVTW-CZcNaoxi.js → highlighted-body-KPVGNVTW-CSgDVUQp.js} +1 -1
  8. package/dist/web/client/assets/index-BARp0bjW.js +13 -0
  9. package/dist/web/client/assets/{markdown-code-BqFVdovL.js → markdown-code-DfJbKhL9.js} +1 -1
  10. package/dist/web/client/assets/{markdown-C-Y9gskI.js → markdown-yn-nhRzB.js} +2 -2
  11. package/dist/web/client/assets/mermaid-HWGCJPDP-BpEVCu9T.js +1 -0
  12. package/dist/web/client/assets/{openui-renderer-CH9K7_8t.js → openui-renderer-DrfHxs1t.js} +1 -1
  13. package/dist/web/client/assets/{preload-helper-Czpn1I53.js → preload-helper-BZ1Pz5am.js} +1 -1
  14. package/dist/web/client/assets/{right-panel-registry-BJG8ubHt.js → right-panel-registry-CF7GLJrk.js} +2 -2
  15. package/dist/web/client/assets/{routes-BXFQmjL9.js → routes-DCP1DP1g.js} +4 -4
  16. package/dist/web/client/assets/session-tool-renderer-Yu4G1165.js +1389 -0
  17. package/dist/web/client/assets/{subagent-chat-panel-DQEnhU2t.js → subagent-chat-panel-bVnkDkgs.js} +1 -1
  18. package/dist/web/client/assets/{subagent-transcript-CCpg3uL6.js → subagent-transcript-D_L-8PQi.js} +1 -1
  19. package/dist/web/client/assets/{subagent-utils-DTV2RcFl.js → subagent-utils-D7sXbLsS.js} +2 -2
  20. package/dist/web/client/assets/{subagents-panel-B-X7WPUU.js → subagents-panel-i5-12E1U.js} +1 -1
  21. package/dist/web/client/assets/{tool-result-C5Ixe-AJ.js → tool-result-D7HtJ_yg.js} +2 -2
  22. package/dist/web/client/assets/{workspace-panel-DDjQuELx.js → workspace-panel-Clbmrdza.js} +1 -1
  23. package/dist/web/client/assets/{workspace-path-nav-DmxBrMV6.js → workspace-path-nav-eVT0rYvv.js} +2 -2
  24. package/dist/web/client/bundle-budget.json +5 -5
  25. package/dist/web/server/{_tanstack-start-manifest_v-vL58CVrY-7SDCWIHD.js → _tanstack-start-manifest_v-CaT-3S-N-VAOGUHEJ.js} +9 -9
  26. package/dist/web/server/{artifacts-panel-CozDO7ak-5T4W7RME.js → artifacts-panel-BuAqeJzj-6DYYLKUW.js} +8 -8
  27. package/dist/web/server/{chat-command-palette-CLE-L0qp-ZZNKVTSS.js → chat-command-palette-Ca8gXVi2-P6EOQ43G.js} +5 -5
  28. package/dist/web/server/{chunk-GRGV5FVO.js → chunk-35AFSKDX.js} +3 -3
  29. package/dist/web/server/{chunk-SLRV7YNY.js → chunk-COWE2EJ6.js} +2 -2
  30. package/dist/web/server/{chunk-54UEKLGD.js → chunk-FPPKECLB.js} +5 -5
  31. package/dist/web/server/{chunk-EUWNVEIC.js → chunk-GCDOYNXR.js} +107 -97
  32. package/dist/web/server/{chunk-QCDSLD3L.js → chunk-ITKXE2Q5.js} +252 -214
  33. package/dist/web/server/{chunk-NHV77NOI.js → chunk-J4Y2Z3XM.js} +1 -1
  34. package/dist/web/server/{chunk-RYU7I34A.js → chunk-JFAUSHBI.js} +4 -4
  35. package/dist/web/server/{chunk-D7GSWBRI.js → chunk-K4KN3QBT.js} +1 -1
  36. package/dist/web/server/{chunk-B4EBMF5J.js → chunk-M7BTY55G.js} +2 -2
  37. package/dist/web/server/{chunk-XJHYJLGU.js → chunk-PHHC52CO.js} +3 -3
  38. package/dist/web/server/{chunk-RVDWGK6U.js → chunk-UTV66W5H.js} +3 -3
  39. package/dist/web/server/{chunk-F5DJQ3PQ.js → chunk-WPSI5TBE.js} +1528 -2185
  40. package/dist/web/server/{create-project-dialog-CReZdM5g-2V7C5J67.js → create-project-dialog-DCvdysey-IZUGGDAN.js} +5 -5
  41. package/dist/web/server/{empty-plugin-adapters-Cqtvkauv-ILKI7W7V.js → empty-plugin-adapters-DOl-E2pL-RKRSN75W.js} +1 -1
  42. package/dist/web/server/{fork-picker-dialog-CXcLEaor-6SVM5RJO.js → fork-picker-dialog-QH00XmqX-6YLU5REF.js} +3 -3
  43. package/dist/web/server/{message-queue-Q_Q6hbqc-AOV2PSCX.js → message-queue-BzEFQR8k-2W53EW32.js} +3 -3
  44. package/dist/web/server/{model-selector-list-BOKU5_Z3-III72ZT2.js → model-selector-list-BjoXmw92-TEKBPB3E.js} +5 -5
  45. package/dist/web/server/{openui-renderer-VuQOQeAP-XBOR3XGN.js → openui-renderer-CJ7Q2zZ_-FPXKZPSO.js} +5 -5
  46. package/dist/web/server/{resources-panel-Cnz-X1bx-TT5KVROR.js → resources-panel-yVB4xF_K-OHFHXVU4.js} +4 -4
  47. package/dist/web/server/{router-C437aaqv-72HBLLJI.js → router-UgU5vJxm-R33FGTXY.js} +2 -2
  48. package/dist/web/server/{routes-BkVN3m9i-PYNMNLQ5.js → routes-Cbbo-jh9-ZUPH4SJD.js} +2 -2
  49. package/dist/web/server/server.js +2410 -1672
  50. package/dist/web/server/{session-reasoning-panel-2_TR5nKM-KA5OY7ZV.js → session-reasoning-panel-C50VbaQ8-4YLMVVY6.js} +4 -4
  51. package/dist/web/server/{session-tool-renderer-BFEWy2Pk-JTSYUPO5.js → session-tool-renderer-QcAkYD-V-6RXRKDH6.js} +5 -5
  52. package/dist/web/server/{session-tree-panel-3y9LVA0A-4V4TJX62.js → session-tree-panel-CL49XSTK-4ZPK6AIV.js} +3 -3
  53. package/dist/web/server/{settings-dialog-DgZ8Z5e4-6T5AS2EB.js → settings-dialog-DG9HEZeP-TWDRDGMN.js} +6 -6
  54. package/dist/web/server/{start-QK6aG02q-EMREW2SB.js → start-DEejK9Uj-FODAOTAO.js} +1 -1
  55. package/dist/web/server/{subagent-chat-panel-B0pmAxCp-DKXNAOUU.js → subagent-chat-panel-Cg2CxshI-WWGFHTIF.js} +7 -7
  56. package/dist/web/server/{subagents-panel-FUUT0t1i-5ZKJ2QAJ.js → subagents-panel-aC3Eo-MR-RNIPLCZQ.js} +7 -7
  57. package/dist/web/server/{workspace-panel-BbI1N4f8-WYOEVH4G.js → workspace-panel-DfdFkgHU-6HIOXRBX.js} +4 -4
  58. package/package.json +2 -2
  59. package/dist/web/client/assets/index-D3HpiAnD.js +0 -12
  60. package/dist/web/client/assets/mermaid-HWGCJPDP-CVNXPao6.js +0 -1
  61. package/dist/web/client/assets/session-tool-renderer-mOZdkbiU.js +0 -1389
@@ -1,46 +1,869 @@
1
1
  import {
2
- GLOBAL_TSR,
2
+ RawStream,
3
3
  RouterProvider,
4
- TSR_SCRIPT_BARRIER_ID,
5
4
  _getRenderedMatches,
6
5
  createInlineCssPlaceholderAsset,
7
6
  createInlineCssStyleAsset,
8
- createLRUCache,
9
- createMemoryHistory,
10
- createRawStreamRPCPlugin,
7
+ createPlugin,
11
8
  createSerializationAdapter,
9
+ createServerHistory,
10
+ createSieveCache,
11
+ createStream,
12
12
  crossSerializeStream,
13
13
  decodePath,
14
- defaultSerovalPlugins,
15
14
  dehydrateSsrMatchId,
16
15
  executeRewriteInput,
17
16
  getCrossReferenceHeader,
18
17
  getScriptPreloadAttrs,
19
18
  getStylesheetHref,
20
19
  invariant,
20
+ isDangerousProtocol,
21
21
  isNotFound,
22
+ isPromise,
22
23
  isRedirect,
23
- isResolvedRedirect,
24
+ isStream,
24
25
  makeSerovalPlugin,
25
- makeSsrSerovalPlugin,
26
26
  resolveManifestAssetLink,
27
27
  resolveManifestCssLink,
28
- rootRouteId
29
- } from "./chunk-F5DJQ3PQ.js";
28
+ rootRouteId,
29
+ waitForReason
30
+ } from "./chunk-WPSI5TBE.js";
30
31
  import "./chunk-CZ7CSFO4.js";
31
32
 
32
33
  // web/app/dist/server/server.js
33
34
  import "react";
34
35
  import { jsx } from "react/jsx-runtime";
35
36
 
36
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/tsrScript.js
37
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/ShallowErrorPlugin.js
38
+ var ShallowErrorPlugin = /* @__PURE__ */ createPlugin({
39
+ tag: "$TSR/Error",
40
+ test(value) {
41
+ return value instanceof Error;
42
+ },
43
+ parse: {
44
+ sync(value, ctx) {
45
+ return { message: ctx.parse(value.message) };
46
+ },
47
+ async async(value, ctx) {
48
+ return { message: await ctx.parse(value.message) };
49
+ },
50
+ stream(value, ctx) {
51
+ return { message: ctx.parse(value.message) };
52
+ }
53
+ },
54
+ serialize(node, ctx) {
55
+ return "new Error(" + ctx.serialize(node.message) + ")";
56
+ },
57
+ deserialize(node, ctx) {
58
+ return new Error(ctx.deserialize(node.message));
59
+ }
60
+ });
61
+
62
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/rawStreamCodec.js
63
+ function toBase64(bytes) {
64
+ const chunks = [];
65
+ for (let i = 0; i < bytes.length; i += 32768) chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + 32768)));
66
+ return btoa(chunks.join(""));
67
+ }
68
+ function fromBase64(value) {
69
+ const binary = atob(value);
70
+ const bytes = new Uint8Array(binary.length);
71
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
72
+ return bytes;
73
+ }
74
+ var textDecoder = /* @__PURE__ */ new TextDecoder("utf-8", {
75
+ fatal: true,
76
+ ignoreBOM: true
77
+ });
78
+ function encodeText(value) {
79
+ try {
80
+ return "t" + textDecoder.decode(value);
81
+ } catch {
82
+ return "b" + toBase64(value);
83
+ }
84
+ }
85
+ var textEncoder = /* @__PURE__ */ new TextEncoder();
86
+ function decodeText(value) {
87
+ const data = value.slice(1);
88
+ return value[0] === "t" ? textEncoder.encode(data) : fromBase64(data);
89
+ }
90
+ function pumpEncodedStream(readable, encode, signal) {
91
+ signal?.throwIfAborted();
92
+ const stream = createStream();
93
+ const reader = readable.getReader();
94
+ let active = true;
95
+ const release = () => {
96
+ active = false;
97
+ signal?.removeEventListener("abort", abort);
98
+ reader.releaseLock();
99
+ };
100
+ const stop = (reason) => {
101
+ if (!active) return false;
102
+ reader.cancel(reason).catch(() => {
103
+ });
104
+ release();
105
+ return true;
106
+ };
107
+ const abort = () => {
108
+ if (stop(signal.reason)) stream.throw(signal.reason);
109
+ };
110
+ signal?.addEventListener("abort", abort);
111
+ (async () => {
112
+ try {
113
+ while (active) {
114
+ const { done, value } = await reader.read();
115
+ if (!active) return;
116
+ if (done) {
117
+ release();
118
+ stream.return(void 0);
119
+ return;
120
+ }
121
+ stream.next(encode(value));
122
+ }
123
+ } catch (error) {
124
+ if (stop(error)) stream.throw(error);
125
+ }
126
+ })();
127
+ return [stream, stop];
128
+ }
129
+ function fromEncodedStream(source, decode) {
130
+ let unsubscribe;
131
+ let done = false;
132
+ return new ReadableStream({
133
+ start(controller) {
134
+ const dispose = source.on({
135
+ next(value) {
136
+ if (done) return;
137
+ try {
138
+ controller.enqueue(decode(value));
139
+ } catch (error) {
140
+ done = true;
141
+ const stop = unsubscribe;
142
+ unsubscribe = void 0;
143
+ stop?.();
144
+ controller.error(error);
145
+ }
146
+ },
147
+ throw(error) {
148
+ if (!done) {
149
+ done = true;
150
+ unsubscribe = void 0;
151
+ controller.error(error);
152
+ }
153
+ },
154
+ return() {
155
+ if (!done) {
156
+ done = true;
157
+ unsubscribe = void 0;
158
+ controller.close();
159
+ }
160
+ }
161
+ });
162
+ if (done) dispose();
163
+ else unsubscribe = dispose;
164
+ },
165
+ cancel() {
166
+ const dispose = unsubscribe;
167
+ unsubscribe = void 0;
168
+ dispose?.();
169
+ }
170
+ });
171
+ }
172
+
173
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/RawStreamJSONPlugin.js
174
+ // @__NO_SIDE_EFFECTS__
175
+ function createRawStreamJSONPlugin(signal) {
176
+ return /* @__PURE__ */ createPlugin({
177
+ tag: "tss/RawStream",
178
+ test: (value) => value instanceof RawStream,
179
+ parse: { async: async (value, ctx) => {
180
+ const text = await ctx.parse(value.hint === "text");
181
+ const [stream] = pumpEncodedStream(value.stream, value.hint === "text" ? encodeText : toBase64, signal);
182
+ return {
183
+ text,
184
+ stream: await ctx.parse(stream)
185
+ };
186
+ } },
187
+ serialize: void 0,
188
+ deserialize: void 0
189
+ });
190
+ }
191
+ var RawStreamJSONPlugin = /* @__PURE__ */ createRawStreamJSONPlugin();
192
+ var RawStreamJSONDeserializePlugin = /* @__PURE__ */ createPlugin({
193
+ tag: "tss/RawStream",
194
+ test: () => false,
195
+ parse: {},
196
+ serialize: void 0,
197
+ deserialize(node, ctx) {
198
+ return fromEncodedStream(ctx.deserialize(node.stream), ctx.deserialize(node.text) ? decodeText : fromBase64);
199
+ }
200
+ });
201
+
202
+ // node_modules/.pnpm/seroval-plugins@1.6.7_seroval@1.6.7/node_modules/seroval-plugins/dist/web-CWqRG00W.js
203
+ var READABLE_STREAM_FACTORY = {};
204
+ var READABLE_STREAM_FACTORY_CONSTRUCTOR = (stream) => new ReadableStream({ start(controller) {
205
+ stream.on({
206
+ next(value) {
207
+ try {
208
+ controller.enqueue(value);
209
+ } catch (_error) {
210
+ }
211
+ },
212
+ throw(value) {
213
+ controller.error(value);
214
+ },
215
+ return() {
216
+ try {
217
+ controller.close();
218
+ } catch (_error) {
219
+ }
220
+ }
221
+ });
222
+ } });
223
+ var ReadableStreamFactoryPlugin = /* @__PURE__ */ createPlugin({
224
+ tag: "seroval-plugins/web/ReadableStreamFactory",
225
+ test(value) {
226
+ return value === READABLE_STREAM_FACTORY;
227
+ },
228
+ parse: {
229
+ sync() {
230
+ return READABLE_STREAM_FACTORY;
231
+ },
232
+ async async() {
233
+ return await Promise.resolve(READABLE_STREAM_FACTORY);
234
+ },
235
+ stream() {
236
+ return READABLE_STREAM_FACTORY;
237
+ }
238
+ },
239
+ serialize() {
240
+ return READABLE_STREAM_FACTORY_CONSTRUCTOR.toString();
241
+ },
242
+ deserialize() {
243
+ return READABLE_STREAM_FACTORY;
244
+ }
245
+ });
246
+ async function drainStream(stream, reader) {
247
+ try {
248
+ while (true) {
249
+ const result = await reader.read();
250
+ if (result.done) {
251
+ stream.return(result.value);
252
+ reader.releaseLock();
253
+ break;
254
+ }
255
+ stream.next(result.value);
256
+ }
257
+ } catch (error) {
258
+ reader.releaseLock();
259
+ stream.throw(error);
260
+ }
261
+ }
262
+ function cleanupStream(reader) {
263
+ reader.cancel().catch(() => {
264
+ });
265
+ reader.releaseLock();
266
+ }
267
+ function toStream(value) {
268
+ const stream = createStream();
269
+ const reader = value.getReader();
270
+ const cleanup = cleanupStream.bind(null, reader);
271
+ drainStream(stream, reader).catch(cleanup);
272
+ return [stream, cleanup];
273
+ }
274
+ var ReadableStreamPlugin = /* @__PURE__ */ createPlugin({
275
+ tag: "seroval/plugins/web/ReadableStream",
276
+ extends: [ReadableStreamFactoryPlugin],
277
+ test(value) {
278
+ if (typeof ReadableStream === "undefined") return false;
279
+ return value instanceof ReadableStream;
280
+ },
281
+ parse: {
282
+ sync(_value, ctx) {
283
+ return {
284
+ factory: ctx.parse(READABLE_STREAM_FACTORY),
285
+ stream: ctx.parse(createStream())
286
+ };
287
+ },
288
+ async async(value, ctx) {
289
+ return {
290
+ factory: await ctx.parse(READABLE_STREAM_FACTORY),
291
+ stream: await ctx.parse(toStream(value)[0])
292
+ };
293
+ },
294
+ stream(value, ctx) {
295
+ const [stream, cleanup] = toStream(value);
296
+ ctx.addCleanup(cleanup);
297
+ return {
298
+ factory: ctx.parse(READABLE_STREAM_FACTORY),
299
+ stream: ctx.parse(stream)
300
+ };
301
+ }
302
+ },
303
+ serialize(node, ctx) {
304
+ return "(" + ctx.serialize(node.factory) + ")(" + ctx.serialize(node.stream) + ")";
305
+ },
306
+ deserialize(node, ctx) {
307
+ const stream = ctx.deserialize(node.stream);
308
+ if (!stream || typeof stream !== "object" || !isStream(stream)) throw new Error("Expected a stream source.");
309
+ return READABLE_STREAM_FACTORY_CONSTRUCTOR(stream);
310
+ }
311
+ });
312
+
313
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/seroval-plugins.js
314
+ // @__NO_SIDE_EFFECTS__
315
+ function createDefaultSerovalPlugins(signal) {
316
+ return [
317
+ ShallowErrorPlugin,
318
+ signal ? /* @__PURE__ */ createRawStreamJSONPlugin(signal) : RawStreamJSONPlugin,
319
+ ReadableStreamPlugin
320
+ ];
321
+ }
322
+ var defaultSerovalPlugins = /* @__PURE__ */ createDefaultSerovalPlugins();
323
+ var defaultSerovalDeserializerPlugins = [RawStreamJSONDeserializePlugin, ...defaultSerovalPlugins];
324
+
325
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/RawStreamRPCPlugin.js
326
+ // @__NO_SIDE_EFFECTS__
327
+ function createRawStreamRPCPlugin(onRawStream) {
328
+ let nextStreamId = 1;
329
+ return /* @__PURE__ */ createPlugin({
330
+ tag: "tss/RawStream",
331
+ test(value) {
332
+ return value instanceof RawStream;
333
+ },
334
+ parse: { stream(value, ctx) {
335
+ const streamId = nextStreamId++;
336
+ onRawStream(streamId, value.stream);
337
+ return { streamId: ctx.parse(streamId) };
338
+ } },
339
+ serialize: void 0,
340
+ deserialize: void 0
341
+ });
342
+ }
343
+
344
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/constants.js
345
+ var GLOBAL_TSR = "$_TSR";
346
+
347
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/makeSsrSerovalPlugin.js
348
+ // @__NO_SIDE_EFFECTS__
349
+ function makeSsrSerovalPlugin(serializationAdapter, tracker) {
350
+ return /* @__PURE__ */ createPlugin({
351
+ tag: "$TSR/t/" + serializationAdapter.key,
352
+ test: serializationAdapter.test,
353
+ parse: { stream(value, ctx) {
354
+ return { v: ctx.parse(serializationAdapter.toSerializable(value)) };
355
+ } },
356
+ serialize(node, ctx) {
357
+ if (tracker) tracker.didRun = true;
358
+ return GLOBAL_TSR + '.t.get("' + serializationAdapter.key + '")(' + ctx.serialize(node.v) + ")";
359
+ },
360
+ deserialize: void 0
361
+ });
362
+ }
363
+
364
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/tsrScript.js
37
365
  var tsrScript_default = "self.$_TSR={h(){this.hydrated=!0,this.c()},e(){this.streamEnded=!0,this.c()},c(){this.hydrated&&this.streamEnded&&(delete self.$_TSR,delete self.$R.tsr)},p(e){this.initialized?e():this.buffer.push(e)},buffer:[]}";
38
366
 
39
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/ssr-server.js
40
- var SCOPE_ID = "tsr";
41
- var TSR_PREFIX = GLOBAL_TSR + ".router=";
42
- var P_PREFIX = GLOBAL_TSR + ".p(()=>";
43
- var P_SUFFIX = ")";
367
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/htmlBoundaryScanner.js
368
+ var textEncoder2 = new TextEncoder();
369
+ var DOCUMENT_CLOSE = "</body></html>";
370
+ var SCRIPT_CLOSE = "</script>";
371
+ var DOCUMENT_CLOSE_ANCHOR_INDEX = DOCUMENT_CLOSE.indexOf("y");
372
+ var SCRIPT_CLOSE_ANCHOR_INDEX = SCRIPT_CLOSE.indexOf("p");
373
+ var DOCUMENT_CLOSE_BYTES = textEncoder2.encode(DOCUMENT_CLOSE);
374
+ var SCRIPT_CLOSE_BYTES = textEncoder2.encode(SCRIPT_CLOSE);
375
+ function encodeIntoBoundedChunk(source, sourceOffset, output, outputOffset = 0) {
376
+ return textEncoder2.encodeInto(sourceOffset === 0 ? source : source.slice(sourceOffset), outputOffset === 0 ? output : output.subarray(outputOffset));
377
+ }
378
+ function advanceByteMatcher(matcher, value, startIndex = 0, findLast = false) {
379
+ const { pattern: pattern2, anchorIndex } = matcher;
380
+ let matched = matcher.matched;
381
+ let lastMatchEnd;
382
+ let index = startIndex;
383
+ while (index < value.length) {
384
+ if (matched === 0) if (anchorIndex > 0 && index < value.length - anchorIndex) {
385
+ const anchor = value.indexOf(pattern2[anchorIndex], index + anchorIndex);
386
+ if (anchor < 0) {
387
+ index = value.length - anchorIndex;
388
+ continue;
389
+ }
390
+ index = anchor - anchorIndex;
391
+ } else {
392
+ index = value.indexOf(pattern2[0], index);
393
+ if (index < 0) {
394
+ matcher.matched = matched;
395
+ return lastMatchEnd;
396
+ }
397
+ }
398
+ const byte = value[index];
399
+ if (byte === pattern2[matched]) matched++;
400
+ else matched = byte === pattern2[0] ? 1 : 0;
401
+ index++;
402
+ if (matched === pattern2.length) {
403
+ matched = 0;
404
+ if (!findLast) {
405
+ matcher.matched = matched;
406
+ return index;
407
+ }
408
+ lastMatchEnd = index;
409
+ }
410
+ }
411
+ matcher.matched = matched;
412
+ return lastMatchEnd;
413
+ }
414
+ function findExactBytes(value, pattern2, startIndex = 0, anchorIndex = 0) {
415
+ let anchor = value.indexOf(pattern2[anchorIndex], startIndex + anchorIndex);
416
+ while (anchor >= 0) {
417
+ const candidate = anchor - anchorIndex;
418
+ if (candidate + pattern2.length > value.length) return -1;
419
+ let patternIndex = 0;
420
+ while (patternIndex < pattern2.length && value[candidate + patternIndex] === pattern2[patternIndex]) patternIndex++;
421
+ if (patternIndex === pattern2.length) return candidate;
422
+ anchor = value.indexOf(pattern2[anchorIndex], anchor + 1);
423
+ }
424
+ return -1;
425
+ }
426
+ function getExactBytesPrefixAtEnd(value, pattern2, startIndex = 0) {
427
+ candidate: for (let length = Math.min(pattern2.length - 1, value.length - startIndex); length > 0; length--) {
428
+ const candidateStart = value.length - length;
429
+ for (let index = 0; index < length; index++) if (value[candidateStart + index] !== pattern2[index]) continue candidate;
430
+ return candidateStart;
431
+ }
432
+ }
433
+
434
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/hydrationScripts.js
435
+ var encoder = new TextEncoder();
436
+ var SOURCE_SEPARATOR = ";";
437
+ var MAX_INITIAL_SOURCE_CODE_UNITS = 16 * 1024;
438
+ var MAX_BACKLOG_CODE_UNITS = 16 * 1024 * 1024;
439
+ var MAX_BACKLOG_SOURCES = 4096;
440
+ var MIN_OUTPUT_BYTES = 256;
441
+ var MAX_DIRECT_CODE_UNITS = 16 * 1024;
442
+ var MAX_HYDRATION_OUTPUT_CHUNK_BYTES = 64 * 1024;
443
+ var MAX_DYNAMIC_RECORD_CODE_UNITS = MAX_HYDRATION_OUTPUT_CHUNK_BYTES;
444
+ var STREAM_PART_ATTRIBUTE = "data-tsr-stream-part";
445
+ var INITIAL_CLEANUP_SOURCE = `{let s=document.currentScript,p;while((p=s.previousElementSibling)&&p.hasAttribute('${STREAM_PART_ATTRIBUTE}'))p.remove();s.remove()}`;
446
+ var INITIAL_CLEANUP_SUFFIX = SOURCE_SEPARATOR + INITIAL_CLEANUP_SOURCE;
447
+ var DYNAMIC_CLOSE_SOURCE = "document.currentScript.remove()</script>";
448
+ var HYDRATION_SCRIPT_BOUNDARY_SOURCE = "document.currentScript.remove();/*$tsr-stream-boundary*/";
449
+ var HYDRATION_SCRIPT_BOUNDARY_SUFFIX = ";/*$tsr-stream-boundary*/</script>";
450
+ var HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX = HYDRATION_SCRIPT_BOUNDARY_SUFFIX.lastIndexOf("*");
451
+ var HYDRATION_SCRIPT_BOUNDARY_BYTES = encoder.encode(HYDRATION_SCRIPT_BOUNDARY_SUFFIX);
452
+ var ROUTER_PREFIX = GLOBAL_TSR + ".router=";
453
+ var PROMISE_PREFIX = GLOBAL_TSR + ".p(()=>";
454
+ var DEFAULT_INITIAL_SOURCES = [getCrossReferenceHeader("tsr"), tsrScript_default];
455
+ var HydrationScriptOutputState = {
456
+ Waiting: 0,
457
+ Ready: 1,
458
+ Active: 2,
459
+ Done: 3,
460
+ Failed: 4
461
+ };
462
+ function escapeAttribute(value) {
463
+ return value.replace(/[&"'<>]/g, (char) => `&#${char.charCodeAt(0)};`);
464
+ }
465
+ function createInitialTags(sources, nonce) {
466
+ const before = [];
467
+ for (const source of sources) {
468
+ if (!source) continue;
469
+ const previous = before[before.length - 1];
470
+ if (previous?.children && previous.children.length + 1 + source.length <= MAX_INITIAL_SOURCE_CODE_UNITS) previous.children += SOURCE_SEPARATOR + source;
471
+ else before.push({
472
+ tag: "script",
473
+ attrs: {
474
+ nonce,
475
+ [STREAM_PART_ATTRIBUTE]: ""
476
+ },
477
+ children: source
478
+ });
479
+ }
480
+ const lastHydrationTag = before[before.length - 1];
481
+ if (lastHydrationTag) {
482
+ const lastSource = lastHydrationTag.children;
483
+ if (lastSource.length + INITIAL_CLEANUP_SUFFIX.length <= MAX_INITIAL_SOURCE_CODE_UNITS) lastHydrationTag.children = lastSource + INITIAL_CLEANUP_SUFFIX;
484
+ else before.push({
485
+ tag: "script",
486
+ attrs: {
487
+ nonce,
488
+ [STREAM_PART_ATTRIBUTE]: ""
489
+ },
490
+ children: INITIAL_CLEANUP_SOURCE
491
+ });
492
+ }
493
+ return {
494
+ before,
495
+ boundary: {
496
+ tag: "script",
497
+ attrs: { nonce },
498
+ children: HYDRATION_SCRIPT_BOUNDARY_SOURCE
499
+ }
500
+ };
501
+ }
502
+ var HydrationScriptsOwner = class {
503
+ constructor(nonce, initialSources) {
504
+ this.nonce = nonce;
505
+ this.queuedSources = [];
506
+ this.queuedSourceHead = 0;
507
+ this.initialTaken = false;
508
+ this.barrierLifted = false;
509
+ this.producerDone = false;
510
+ this.retainedSources = 0;
511
+ this.regularCodeUnits = 0;
512
+ this.hasOversizedSource = false;
513
+ this.segmentIndex = 0;
514
+ this.closingSegmentIndex = 0;
515
+ this.source = "";
516
+ this.sourceOffset = 0;
517
+ this.outputCapacity = MIN_OUTPUT_BYTES;
518
+ this.outputState = HydrationScriptOutputState.Waiting;
519
+ this.takeInitialHydrationScriptTags = this.takeInitialHydrationScriptTags.bind(this);
520
+ const seedSources = initialSources ?? DEFAULT_INITIAL_SOURCES;
521
+ for (const seedSource of seedSources) {
522
+ if (!this.account(seedSource)) break;
523
+ this.queuedSources.push(seedSource);
524
+ }
525
+ }
526
+ get state() {
527
+ return this.outputState;
528
+ }
529
+ get error() {
530
+ return this.outputError;
531
+ }
532
+ notify() {
533
+ try {
534
+ this.listener?.();
535
+ } catch (listenerError) {
536
+ console.error("Hydration script output listener error:", listenerError);
537
+ }
538
+ }
539
+ refresh(notifyChange = true) {
540
+ const next = this.outputState === HydrationScriptOutputState.Failed ? HydrationScriptOutputState.Failed : this.active ? HydrationScriptOutputState.Active : typeof this.consumer === "object" && this.initialTaken && this.barrierLifted && !this.queueIsEmpty() ? HydrationScriptOutputState.Ready : this.producerDone && this.initialTaken && this.queueIsEmpty() ? HydrationScriptOutputState.Done : HydrationScriptOutputState.Waiting;
541
+ if (this.outputState !== next) {
542
+ this.outputState = next;
543
+ if (notifyChange) this.notify();
544
+ }
545
+ }
546
+ clearTimeoutIfSet() {
547
+ if (this.timeout !== void 0) {
548
+ clearTimeout(this.timeout);
549
+ this.timeout = void 0;
550
+ }
551
+ }
552
+ queueIsEmpty() {
553
+ return this.queuedSourceHead === this.queuedSources.length;
554
+ }
555
+ clearQueue() {
556
+ this.queuedSources = [];
557
+ this.queuedSourceHead = 0;
558
+ }
559
+ dropBufferedOutput() {
560
+ this.clearQueue();
561
+ this.active = void 0;
562
+ this.retainedSources = 0;
563
+ this.regularCodeUnits = 0;
564
+ this.hasOversizedSource = false;
565
+ this.segmentIndex = 0;
566
+ this.closingSegmentIndex = 0;
567
+ this.source = "";
568
+ this.sourceOffset = 0;
569
+ this.outputCapacity = MIN_OUTPUT_BYTES;
570
+ this.opening = void 0;
571
+ }
572
+ fail(reason) {
573
+ if (this.consumer === "cleaned" || this.outputState === HydrationScriptOutputState.Failed) return;
574
+ this.outputError = reason;
575
+ this.clearTimeoutIfSet();
576
+ this.dropBufferedOutput();
577
+ this.outputState = HydrationScriptOutputState.Failed;
578
+ this.notify();
579
+ }
580
+ rejectBacklog(kind) {
581
+ this.fail(/* @__PURE__ */ new Error(`SSR hydration backlog exceeded maximum ${kind} count`));
582
+ return false;
583
+ }
584
+ account(nextSource) {
585
+ if (this.retainedSources === MAX_BACKLOG_SOURCES) return this.rejectBacklog("source-part");
586
+ if (nextSource.length > MAX_BACKLOG_CODE_UNITS) {
587
+ if (this.hasOversizedSource) return this.rejectBacklog("code-unit");
588
+ this.hasOversizedSource = true;
589
+ } else if (this.regularCodeUnits + nextSource.length > MAX_BACKLOG_CODE_UNITS) return this.rejectBacklog("code-unit");
590
+ else this.regularCodeUnits += nextSource.length;
591
+ this.retainedSources++;
592
+ return true;
593
+ }
594
+ releaseSource(part) {
595
+ this.retainedSources--;
596
+ if (part.length > MAX_BACKLOG_CODE_UNITS) this.hasOversizedSource = false;
597
+ else this.regularCodeUnits -= part.length;
598
+ }
599
+ releaseAccounting(batch) {
600
+ for (const part of batch) if (part !== void 0) this.releaseSource(part);
601
+ }
602
+ liftBarrier() {
603
+ if (this.consumer !== "cleaned" && !this.barrierLifted) {
604
+ this.barrierLifted = true;
605
+ this.refresh();
606
+ }
607
+ }
608
+ producerCanWrite() {
609
+ return this.consumer !== "cleaned" && this.outputState !== HydrationScriptOutputState.Failed && !this.producerDone;
610
+ }
611
+ pushSource(nextSource) {
612
+ if (!this.producerCanWrite()) return false;
613
+ if (this.account(nextSource)) {
614
+ this.queuedSources.push(nextSource);
615
+ if (this.initialTaken) this.refresh();
616
+ } else return false;
617
+ return this.producerCanWrite();
618
+ }
619
+ takeQueuedBatch(batchLength) {
620
+ if (this.queuedSourceHead === 0 && batchLength === this.queuedSources.length) {
621
+ const batch2 = this.queuedSources;
622
+ this.clearQueue();
623
+ return batch2;
624
+ }
625
+ const end = this.queuedSourceHead + batchLength;
626
+ const batch = this.queuedSources.slice(this.queuedSourceHead, end);
627
+ for (let index = this.queuedSourceHead; index < end; index++) this.queuedSources[index] = void 0;
628
+ this.queuedSourceHead = end;
629
+ if (this.queueIsEmpty()) this.clearQueue();
630
+ else if (this.queuedSourceHead >= 1024 && this.queuedSourceHead >= this.queuedSources.length - this.queuedSourceHead) {
631
+ this.queuedSources = this.queuedSources.slice(this.queuedSourceHead);
632
+ this.queuedSourceHead = 0;
633
+ }
634
+ return batch;
635
+ }
636
+ release(batch) {
637
+ this.releaseAccounting(batch);
638
+ this.active = void 0;
639
+ this.source = "";
640
+ this.sourceOffset = 0;
641
+ this.refresh(false);
642
+ }
643
+ advanceSource() {
644
+ const batch = this.active;
645
+ if (this.segmentIndex > 0 && this.segmentIndex < this.closingSegmentIndex) {
646
+ const partIndex = this.segmentIndex - 1 >> 1;
647
+ if (this.segmentIndex % 2 === 1) {
648
+ const part = batch[partIndex];
649
+ if (part !== void 0) {
650
+ this.releaseSource(part);
651
+ batch[partIndex] = void 0;
652
+ }
653
+ }
654
+ }
655
+ this.segmentIndex++;
656
+ if (this.segmentIndex < this.closingSegmentIndex) {
657
+ const partIndex = this.segmentIndex - 1 >> 1;
658
+ this.source = this.segmentIndex % 2 === 1 ? batch[partIndex] : SOURCE_SEPARATOR;
659
+ } else if (this.segmentIndex === this.closingSegmentIndex) this.source = DYNAMIC_CLOSE_SOURCE;
660
+ else this.release(batch);
661
+ this.sourceOffset = 0;
662
+ }
663
+ pullActive() {
664
+ const bytes = new Uint8Array(this.outputCapacity);
665
+ let offset = 0;
666
+ while (this.active) if (this.sourceOffset === this.source.length) this.advanceSource();
667
+ else if (offset === bytes.length) break;
668
+ else {
669
+ const result = encodeIntoBoundedChunk(this.source, this.sourceOffset, bytes, offset);
670
+ if (result.read === 0) break;
671
+ this.sourceOffset += result.read;
672
+ offset += result.written;
673
+ }
674
+ if (offset === 0) throw new Error("SSR router script record produced no output");
675
+ if (offset === bytes.length) return bytes;
676
+ return offset * 2 < bytes.length ? bytes.slice(0, offset) : bytes.subarray(0, offset);
677
+ }
678
+ pullReady() {
679
+ const scriptOpening = this.opening ??= this.nonce ? `<script nonce="${escapeAttribute(this.nonce)}">` : "<script>";
680
+ let codeUnits = scriptOpening.length + 40;
681
+ let batchLength = 0;
682
+ for (let index = this.queuedSourceHead; index < this.queuedSources.length; index++) {
683
+ const part = this.queuedSources[index];
684
+ const nextCodeUnits = codeUnits + 1 + part.length;
685
+ if (batchLength > 0 && nextCodeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) break;
686
+ codeUnits = nextCodeUnits;
687
+ batchLength++;
688
+ if (codeUnits > MAX_DYNAMIC_RECORD_CODE_UNITS) break;
689
+ }
690
+ const batch = this.takeQueuedBatch(batchLength);
691
+ if (codeUnits <= MAX_DIRECT_CODE_UNITS) {
692
+ const joined = batch.length === 1 ? batch[0] : batch.join(SOURCE_SEPARATOR);
693
+ const bytes = encoder.encode(scriptOpening + joined + ";document.currentScript.remove()</script>");
694
+ this.release(batch);
695
+ return bytes;
696
+ }
697
+ this.active = batch;
698
+ this.segmentIndex = 0;
699
+ this.closingSegmentIndex = (batch.length << 1) + 1;
700
+ this.source = scriptOpening;
701
+ this.sourceOffset = 0;
702
+ this.outputCapacity = Math.max(MIN_OUTPUT_BYTES, Math.min(MAX_HYDRATION_OUTPUT_CHUNK_BYTES, codeUnits));
703
+ this.outputState = HydrationScriptOutputState.Active;
704
+ return this.pullActive();
705
+ }
706
+ pullChunk() {
707
+ if (this.outputState !== HydrationScriptOutputState.Ready && this.outputState !== HydrationScriptOutputState.Active) throw new Error("Hydration script output is not ready");
708
+ try {
709
+ return this.outputState === HydrationScriptOutputState.Ready ? this.pullReady() : this.pullActive();
710
+ } catch (cause) {
711
+ this.fail(cause);
712
+ throw cause;
713
+ }
714
+ }
715
+ subscribe(onChange) {
716
+ if (this.consumer === "cleaned") return () => {
717
+ };
718
+ if (this.listener) throw new Error("SSR hydration output already has a subscriber");
719
+ this.listener = onChange;
720
+ return () => {
721
+ if (this.listener === onChange) this.listener = void 0;
722
+ };
723
+ }
724
+ pushSerializedSource(data, initial, wrap) {
725
+ let serialized = initial ? ROUTER_PREFIX + data : data;
726
+ if (wrap) serialized = PROMISE_PREFIX + serialized + ")";
727
+ return this.pushSource(serialized);
728
+ }
729
+ finish() {
730
+ if (!this.pushSource("$_TSR.e()")) return;
731
+ this.producerDone = true;
732
+ this.clearTimeoutIfSet();
733
+ this.refresh();
734
+ }
735
+ takeInitialHydrationScriptTags() {
736
+ if (this.consumer === "cleaned" || this.outputState === HydrationScriptOutputState.Failed || this.initialTaken) return;
737
+ const sources = this.queuedSources;
738
+ const tags = createInitialTags(sources, this.nonce);
739
+ this.initialTaken = true;
740
+ this.releaseAccounting(sources);
741
+ sources.length = 0;
742
+ this.queuedSourceHead = 0;
743
+ this.refresh();
744
+ return tags;
745
+ }
746
+ /**
747
+ * Opt this request out of hydration output entirely (for example a
748
+ * `hydrate: false` page). Drops the queued bootstrap sources, marks the
749
+ * producer done, and makes the fast pass-through path reservable without
750
+ * a rendered `<Scripts>` boundary. Must run before the initial take and
751
+ * before serialization produces output.
752
+ */
753
+ disableHydration() {
754
+ if (this.consumer === "cleaned" || this.outputState === HydrationScriptOutputState.Failed) return;
755
+ if (this.initialTaken || this.consumer !== void 0 || this.producerDone) {
756
+ if (process.env.NODE_ENV !== "production") throw new Error("Invariant failed: hydration output is already committed; disableHydration() must run before <Scripts> renders and before serialization starts.");
757
+ invariant();
758
+ }
759
+ this.releaseAccounting(this.queuedSources);
760
+ this.clearQueue();
761
+ this.initialTaken = true;
762
+ this.barrierLifted = true;
763
+ this.producerDone = true;
764
+ this.refresh();
765
+ }
766
+ isInitialTaken() {
767
+ return this.initialTaken;
768
+ }
769
+ skipInitialTake() {
770
+ if (this.consumer !== "cleaned" && !this.initialTaken) {
771
+ this.initialTaken = true;
772
+ this.refresh();
773
+ }
774
+ }
775
+ claimOutput() {
776
+ if (this.consumer === "cleaned") throw new Error("SSR hydration script output is already cleaned up");
777
+ if (this.consumer !== void 0) throw new Error("SSR hydration script output already has a consumer");
778
+ this.consumer = this;
779
+ this.refresh(false);
780
+ return this;
781
+ }
782
+ reserveFastPath(output) {
783
+ const ownsConsumer = this.consumer === output;
784
+ if (this.outputState === HydrationScriptOutputState.Failed || !this.producerDone || !this.initialTaken || !this.queueIsEmpty() || this.active || !ownsConsumer) return false;
785
+ this.consumer = "fast-path";
786
+ return true;
787
+ }
788
+ startSerializationTimeout(timeoutMs) {
789
+ if (this.consumer === "cleaned" || this.outputState === HydrationScriptOutputState.Failed || this.producerDone || this.timeout !== void 0) return;
790
+ this.timeout = setTimeout(() => {
791
+ this.timeout = void 0;
792
+ if (this.consumer !== "cleaned" && this.outputState !== HydrationScriptOutputState.Failed && !this.producerDone) {
793
+ console.error("Serialization timeout after app render finished");
794
+ this.fail(/* @__PURE__ */ new Error("Serialization timeout after app render finished"));
795
+ }
796
+ }, timeoutMs);
797
+ }
798
+ cleanup() {
799
+ if (this.consumer === "cleaned") return;
800
+ this.consumer = "cleaned";
801
+ this.clearTimeoutIfSet();
802
+ this.dropBufferedOutput();
803
+ this.listener = void 0;
804
+ this.outputError = void 0;
805
+ this.producerDone = true;
806
+ this.outputState = HydrationScriptOutputState.Done;
807
+ }
808
+ };
809
+ function createHydrationScripts(nonce, initialSources) {
810
+ return new HydrationScriptsOwner(nonce, initialSources);
811
+ }
812
+
813
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/RawStreamSSRPlugin.js
814
+ var nodeBuffer = globalThis.Buffer;
815
+ var toBase64Fast = nodeBuffer ? (bytes) => nodeBuffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64") : toBase64;
816
+ var BINARY_FACTORY = () => {
817
+ };
818
+ var TEXT_FACTORY = () => {
819
+ };
820
+ var FACTORY_BINARY = `((s,u=1)=>new ReadableStream({start(c,f){f=s.on({next(b){const d=atob(b),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)},throw(e){s=u=0;c.error(e)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`;
821
+ var FACTORY_TEXT = `((s,u=1,e=new TextEncoder)=>new ReadableStream({start(c,f){f=s.on({next(v){const x=v.slice(1);if(v[0]==='t')c.enqueue(e.encode(x));else{const d=atob(x),a=new Uint8Array(d.length);for(let i=0;i<d.length;i++)a[i]=d.charCodeAt(i);c.enqueue(a)}},throw(x){s=u=0;c.error(x)},return(){s=u=0;c.close()}});u=u&&f},cancel(){u&&u()}}))`;
822
+ function makeFactoryPlugin(tag, sentinel, source) {
823
+ return createPlugin({
824
+ tag,
825
+ test(value) {
826
+ return value === sentinel;
827
+ },
828
+ parse: { stream() {
829
+ return {};
830
+ } },
831
+ serialize() {
832
+ return source;
833
+ },
834
+ deserialize: void 0
835
+ });
836
+ }
837
+ var RawStreamSSRPlugin = /* @__PURE__ */ createPlugin({
838
+ tag: "tss/RawStream",
839
+ extends: [/* @__PURE__ */ makeFactoryPlugin("tss/RawStreamFactory", BINARY_FACTORY, FACTORY_BINARY), /* @__PURE__ */ makeFactoryPlugin("tss/RawStreamFactoryText", TEXT_FACTORY, FACTORY_TEXT)],
840
+ test(value) {
841
+ return value instanceof RawStream;
842
+ },
843
+ parse: { stream(value, ctx) {
844
+ const text = value.hint === "text";
845
+ const factory = ctx.parse(text ? TEXT_FACTORY : BINARY_FACTORY);
846
+ const [stream, stop] = pumpEncodedStream(value.stream, text ? encodeText : toBase64Fast);
847
+ ctx.addCleanup(stop);
848
+ return {
849
+ factory,
850
+ stream: ctx.parse(stream)
851
+ };
852
+ } },
853
+ serialize(node, ctx) {
854
+ return "(" + ctx.serialize(node.factory) + ")(" + ctx.serialize(node.stream) + ")";
855
+ },
856
+ deserialize: void 0
857
+ });
858
+
859
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/serializer/seroval-plugins.ssr.js
860
+ var ssrSerovalPlugins = [
861
+ ShallowErrorPlugin,
862
+ RawStreamSSRPlugin,
863
+ ReadableStreamPlugin
864
+ ];
865
+
866
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/ssr-server.js
44
867
  function dehydrateMatch(match) {
45
868
  const dehydratedMatch = {
46
869
  i: dehydrateSsrMatchId(match.id),
@@ -56,98 +879,38 @@ function dehydrateMatch(match) {
56
879
  if (match._notFound) dehydratedMatch.g = true;
57
880
  return dehydratedMatch;
58
881
  }
59
- var INITIAL_SCRIPTS = [getCrossReferenceHeader(SCOPE_ID), tsrScript_default];
60
- var ScriptBuffer = class {
61
- constructor(injectScript) {
62
- this._scriptBarrierLifted = false;
63
- this._cleanedUp = false;
64
- this._microtaskVersion = 0;
65
- this._pendingMicrotaskVersion = 0;
66
- this.injectScript = injectScript;
67
- this._queue = INITIAL_SCRIPTS.slice();
68
- }
69
- enqueue(script) {
70
- if (this._cleanedUp) return;
71
- this._queue.push(script);
72
- if (this._scriptBarrierLifted) this.scheduleInjectBufferedScripts();
73
- }
74
- liftBarrier() {
75
- if (this._scriptBarrierLifted || this._cleanedUp) return;
76
- this._scriptBarrierLifted = true;
77
- if (this._queue.length > 0) this.scheduleInjectBufferedScripts();
78
- }
79
- scheduleInjectBufferedScripts() {
80
- if (this._pendingMicrotaskVersion !== 0) return;
81
- const pendingVersion = ++this._microtaskVersion;
82
- this._pendingMicrotaskVersion = pendingVersion;
83
- queueMicrotask(() => {
84
- if (this._pendingMicrotaskVersion !== pendingVersion) return;
85
- this._pendingMicrotaskVersion = 0;
86
- this.injectBufferedScripts();
87
- });
88
- }
89
- clearPendingMicrotask() {
90
- if (this._pendingMicrotaskVersion === 0) return;
91
- this._pendingMicrotaskVersion = 0;
92
- this._microtaskVersion++;
93
- }
94
- /**
95
- * Flushes any pending scripts synchronously.
96
- * Call this before signaling serialization finished to ensure all scripts are injected.
97
- *
98
- * IMPORTANT: Only injects if the barrier has been lifted. Before the barrier is lifted,
99
- * scripts should remain in the queue so takeBufferedScripts() can retrieve them
100
- */
101
- flush() {
102
- if (!this._scriptBarrierLifted) return;
103
- if (this._cleanedUp) return;
104
- this.clearPendingMicrotask();
105
- this.injectBufferedScripts();
106
- }
107
- takeAll() {
108
- return this.takeScripts(this._queue.length);
109
- }
110
- takeScripts(count) {
111
- if (count <= 0) return void 0;
112
- const bufferedScripts = this._queue.splice(0, count);
113
- if (bufferedScripts.length === 0) return;
114
- if (bufferedScripts.length === 1) return bufferedScripts[0] + ";document.currentScript.remove()";
115
- return bufferedScripts.join(";") + ";document.currentScript.remove()";
116
- }
117
- hasPending() {
118
- return this._queue.length > 0;
119
- }
120
- injectBufferedScripts() {
121
- if (this._cleanedUp) return;
122
- if (this._queue.length === 0) return;
123
- const scriptsToInject = this.takeAll();
124
- if (scriptsToInject) this.injectScript?.(scriptsToInject);
882
+ function disposeSerializationSafely(dispose) {
883
+ try {
884
+ dispose?.();
885
+ } catch (err) {
886
+ console.error("Error disposing SSR serialization:", err);
125
887
  }
126
- cleanup() {
127
- this._cleanedUp = true;
128
- this.clearPendingMicrotask();
129
- this._queue = [];
130
- this.injectScript = void 0;
888
+ }
889
+ function notifyAndClearListeners(listeners, errorMessage, arg) {
890
+ const pending = listeners.slice();
891
+ listeners.length = 0;
892
+ for (const listener of pending) try {
893
+ listener(arg);
894
+ } catch (error) {
895
+ console.error(errorMessage, error);
131
896
  }
132
- };
897
+ }
133
898
  var isProd = process.env.NODE_ENV === "production";
134
899
  var MANIFEST_CACHE_SIZE = 100;
135
900
  var manifestCaches = /* @__PURE__ */ new WeakMap();
136
901
  function getManifestCache(manifest2) {
137
902
  const cache = manifestCaches.get(manifest2);
138
903
  if (cache) return cache;
139
- const newCache = createLRUCache(MANIFEST_CACHE_SIZE);
904
+ const newCache = createSieveCache(MANIFEST_CACHE_SIZE);
140
905
  manifestCaches.set(manifest2, newCache);
141
906
  return newCache;
142
907
  }
143
908
  function getInlineCssForPreparedRoutes(manifest2, preparedRoutes) {
144
- if (preparedRoutes.inlineCss !== void 0) return preparedRoutes.inlineCss;
145
909
  const styles = manifest2.inlineCss?.styles;
146
910
  const hrefs = preparedRoutes.inlineCssHrefs;
147
- if (!styles || !hrefs?.length) return void 0;
911
+ if (!styles || !hrefs?.length) return;
148
912
  let css = "";
149
913
  for (const href of hrefs) css += styles[href];
150
- preparedRoutes.inlineCss = css;
151
914
  return css;
152
915
  }
153
916
  function getInlineCssAssetForPreparedRoutes(manifest2, preparedRoutes) {
@@ -246,78 +1009,69 @@ function mergeRequestAssetsIntoRootRoute(rootRoute, requestAssets) {
246
1009
  ...cssLinks?.length ? { css: cssLinks } : {}
247
1010
  };
248
1011
  }
1012
+ function composeManifest(scriptFormat, inlineStyle, routes, requestAssets) {
1013
+ const base = {
1014
+ ...scriptFormat ? { scriptFormat } : {},
1015
+ ...inlineStyle ? { inlineStyle } : {},
1016
+ routes
1017
+ };
1018
+ if (!hasRequestAssets(requestAssets)) return base;
1019
+ return {
1020
+ ...base,
1021
+ routes: {
1022
+ ...routes,
1023
+ [rootRouteId]: mergeRequestAssetsIntoRootRoute(routes[rootRouteId], requestAssets)
1024
+ }
1025
+ };
1026
+ }
249
1027
  function attachRouterServerSsrUtils({ router, manifest: manifest2, getRequestAssets }) {
1028
+ let memoizedPreparedManifest;
250
1029
  router.ssr = { get manifest() {
251
1030
  if (!manifest2) return manifest2;
252
1031
  const requestAssets = getRequestAssets?.();
253
- const matches = _getRenderedMatches(router.stores.matches.get());
254
1032
  const hasAssets = hasRequestAssets(requestAssets);
255
1033
  if (!hasAssets && !manifest2.inlineCss) return manifest2;
256
1034
  let inlineCssAsset;
257
1035
  let routes = manifest2.routes;
258
1036
  if (manifest2.inlineCss) {
259
- const preparedManifest = getPreparedMatchedManifestRoutes(manifest2, matches, getMatchedRoutesCacheKey(matches));
260
- inlineCssAsset = getInlineCssAssetForPreparedRoutes(manifest2, preparedManifest);
261
- if (preparedManifest.hasStrippedRoutes) routes = {
262
- ...manifest2.routes,
263
- ...preparedManifest.routes
264
- };
265
- }
266
- if (!hasAssets) return {
267
- ...manifest2.scriptFormat ? { scriptFormat: manifest2.scriptFormat } : {},
268
- ...inlineCssAsset ? { inlineStyle: inlineCssAsset } : {},
269
- routes
270
- };
271
- const rootRoute = routes[rootRouteId];
272
- return {
273
- ...manifest2.scriptFormat ? { scriptFormat: manifest2.scriptFormat } : {},
274
- ...inlineCssAsset ? { inlineStyle: inlineCssAsset } : {},
275
- routes: {
276
- ...routes,
277
- [rootRouteId]: mergeRequestAssetsIntoRootRoute(rootRoute, requestAssets)
1037
+ const matches = _getRenderedMatches(router.stores.matches.get());
1038
+ const cacheKey = getMatchedRoutesCacheKey(matches);
1039
+ if (memoizedPreparedManifest?.cacheKey === cacheKey) {
1040
+ inlineCssAsset = memoizedPreparedManifest.inlineCssAsset;
1041
+ routes = memoizedPreparedManifest.routes;
1042
+ } else {
1043
+ const preparedManifest = getPreparedMatchedManifestRoutes(manifest2, matches, cacheKey);
1044
+ inlineCssAsset = getInlineCssAssetForPreparedRoutes(manifest2, preparedManifest);
1045
+ if (preparedManifest.hasStrippedRoutes) routes = {
1046
+ ...manifest2.routes,
1047
+ ...preparedManifest.routes
1048
+ };
1049
+ memoizedPreparedManifest = {
1050
+ cacheKey,
1051
+ inlineCssAsset,
1052
+ routes
1053
+ };
278
1054
  }
279
- };
1055
+ }
1056
+ return composeManifest(manifest2.scriptFormat, inlineCssAsset, routes, hasAssets ? requestAssets : void 0);
280
1057
  } };
281
- let _dehydrated = false;
282
- let _serializationFinished = false;
283
- let streamFastPathReserved = false;
1058
+ let dehydrationPhase = "idle";
1059
+ let renderFinished = false;
284
1060
  const renderFinishedListeners = [];
285
- const injectedHtmlListeners = [];
286
- const serializationFinishedListeners = [];
287
1061
  const cleanupListeners = [];
288
1062
  let cleanupStarted = false;
289
- let injectedHtmlBuffer = "";
290
- const callListeners = (listeners, errorPrefix) => {
291
- const snapshot = listeners.slice();
292
- for (const l of snapshot) try {
293
- l();
294
- } catch (err) {
295
- console.error(`${errorPrefix}:`, err);
296
- }
297
- };
298
- const removeListener = (listeners, listener) => {
299
- const index = listeners.indexOf(listener);
300
- if (index >= 0) listeners.splice(index, 1);
301
- };
302
- const scriptBuffer = new ScriptBuffer((script) => {
303
- serverSsr.injectScript(script);
304
- });
1063
+ let settled = false;
1064
+ let disposeSerialization;
1065
+ const hydrationScripts = createHydrationScripts(router.options.ssr?.nonce);
305
1066
  const serverSsr = {
306
- injectHtml: (html) => {
307
- if (!html || cleanupStarted) return;
308
- injectedHtmlBuffer += html;
309
- callListeners(injectedHtmlListeners, "SSR injected HTML listener error");
310
- },
311
- injectScript: (script) => {
312
- if (!script || cleanupStarted) return;
313
- const html = `<script${router.options.ssr?.nonce ? ` nonce='${router.options.ssr.nonce}'` : ""}>${script}</script>`;
314
- serverSsr.injectHtml(html);
315
- },
1067
+ hydrationScripts,
316
1068
  dehydrate: async (opts) => {
317
- if (_dehydrated) {
318
- if (process.env.NODE_ENV !== "production") throw new Error("Invariant failed: router is already dehydrated!");
1069
+ if (dehydrationPhase !== "idle") {
1070
+ if (process.env.NODE_ENV !== "production") throw new Error(dehydrationPhase === "disabled" ? "Invariant failed: hydration is disabled for this request!" : "Invariant failed: router is already dehydrated!");
319
1071
  invariant();
320
1072
  }
1073
+ opts?.signal?.throwIfAborted();
1074
+ dehydrationPhase = "started";
321
1075
  let matchesToDehydrate = _getRenderedMatches(router.stores.matches.get());
322
1076
  if (router.isShell()) matchesToDehydrate = matchesToDehydrate.slice(0, 1);
323
1077
  const matches = matchesToDehydrate.map(dehydrateMatch);
@@ -325,160 +1079,106 @@ function attachRouterServerSsrUtils({ router, manifest: manifest2, getRequestAss
325
1079
  if (manifest2) {
326
1080
  const cacheKey = getMatchedRoutesCacheKey(matchesToDehydrate);
327
1081
  const preparedManifest = getPreparedMatchedManifestRoutes(manifest2, matchesToDehydrate, cacheKey);
328
- manifestToDehydrate = {
329
- ...manifest2.scriptFormat ? { scriptFormat: manifest2.scriptFormat } : {},
330
- ...preparedManifest.inlineCssHrefs ? { inlineStyle: createInlineCssPlaceholderAsset() } : {},
331
- routes: preparedManifest.routes
332
- };
333
- const requestAssets = opts?.requestAssets;
334
- if (hasRequestAssets(requestAssets)) {
335
- const existingRoot = manifestToDehydrate.routes[rootRouteId];
336
- manifestToDehydrate.routes = {
337
- ...manifestToDehydrate.routes,
338
- [rootRouteId]: mergeRequestAssetsIntoRootRoute(existingRoot, requestAssets)
339
- };
340
- }
1082
+ manifestToDehydrate = composeManifest(manifest2.scriptFormat, preparedManifest.inlineCssHrefs ? createInlineCssPlaceholderAsset() : void 0, preparedManifest.routes, opts?.requestAssets);
341
1083
  }
342
1084
  const dehydratedRouter = {
343
1085
  manifest: manifestToDehydrate,
344
1086
  matches
345
1087
  };
346
- const dehydratedData = await router.options.dehydrate?.();
1088
+ const dehydrate = router.options.dehydrate;
1089
+ const dehydratedData = dehydrate ? opts?.signal ? await waitForReason(dehydrate.call(router.options), opts.signal) : await dehydrate.call(router.options) : void 0;
1090
+ opts?.signal?.throwIfAborted();
347
1091
  if (cleanupStarted) return;
348
- if (dehydratedData) dehydratedRouter.dehydratedData = dehydratedData;
349
- _dehydrated = true;
1092
+ if (dehydratedData !== void 0) dehydratedRouter.dehydratedData = dehydratedData;
350
1093
  const trackPlugins = { didRun: false };
351
1094
  const serializationAdapters = router.options.serializationAdapters;
352
- const plugins = serializationAdapters ? serializationAdapters.map((t) => /* @__PURE__ */ makeSsrSerovalPlugin(t, trackPlugins)).concat(defaultSerovalPlugins) : defaultSerovalPlugins;
1095
+ const plugins = serializationAdapters ? [...serializationAdapters.map((adapter) => /* @__PURE__ */ makeSsrSerovalPlugin(adapter, trackPlugins)), ...ssrSerovalPlugins] : ssrSerovalPlugins;
353
1096
  let serializationCompleteSignaled = false;
354
- const signalSerializationComplete = () => {
1097
+ let initialSerialized = false;
1098
+ const completeScriptSerialization = (result) => {
355
1099
  if (serializationCompleteSignaled || cleanupStarted) return;
356
1100
  serializationCompleteSignaled = true;
357
- _serializationFinished = true;
358
- const listeners = serializationFinishedListeners.slice();
359
- serializationFinishedListeners.length = 0;
360
- for (const l of listeners) try {
361
- l();
362
- } catch (err) {
363
- console.error("Serialization listener error:", err);
364
- }
365
- };
366
- const finishScriptSerialization = () => {
367
- if (serializationCompleteSignaled || cleanupStarted) return;
368
- scriptBuffer.enqueue(GLOBAL_TSR + ".e()");
369
- scriptBuffer.flush();
370
- signalSerializationComplete();
1101
+ const dispose2 = disposeSerialization;
1102
+ disposeSerialization = void 0;
1103
+ if (result === true) {
1104
+ settled = true;
1105
+ hydrationScripts.finish();
1106
+ } else if (result) hydrationScripts.fail(result.error);
1107
+ if (dispose2) queueMicrotask(() => disposeSerializationSafely(dispose2));
371
1108
  };
372
- crossSerializeStream(dehydratedRouter, {
1109
+ let synchronousFailure;
1110
+ const dispose = crossSerializeStream(dehydratedRouter, {
373
1111
  refs: /* @__PURE__ */ new Map(),
374
1112
  plugins,
375
1113
  onSerialize: (data, initial) => {
376
- let serialized = initial ? TSR_PREFIX + data : data;
377
- if (trackPlugins.didRun) serialized = P_PREFIX + serialized + P_SUFFIX;
378
- scriptBuffer.enqueue(serialized);
1114
+ if (serializationCompleteSignaled || cleanupStarted) return;
1115
+ initialSerialized ||= initial;
1116
+ if (!hydrationScripts.pushSerializedSource(data, initial, trackPlugins.didRun)) completeScriptSerialization(false);
379
1117
  },
380
1118
  onError: (err) => {
1119
+ if (serializationCompleteSignaled || cleanupStarted) return;
381
1120
  console.error("Serialization error:", err);
382
- if (err && err.stack) console.error(err.stack);
383
- finishScriptSerialization();
1121
+ synchronousFailure = { error: err };
1122
+ completeScriptSerialization({ error: err });
384
1123
  },
385
- scopeId: SCOPE_ID,
1124
+ scopeId: "tsr",
386
1125
  onDone: () => {
387
- finishScriptSerialization();
1126
+ if (initialSerialized) completeScriptSerialization(true);
388
1127
  }
389
1128
  });
390
- },
391
- isDehydrated() {
392
- return _dehydrated;
393
- },
394
- isSerializationFinished() {
395
- return _serializationFinished;
396
- },
397
- reserveStreamFastPath() {
398
- if (!cleanupStarted && _serializationFinished && !streamFastPathReserved && renderFinishedListeners.length === 0 && !injectedHtmlBuffer && !scriptBuffer.hasPending()) {
399
- streamFastPathReserved = true;
400
- return true;
401
- }
402
- return false;
403
- },
404
- onInjectedHtml: (listener) => {
405
- if (cleanupStarted) return () => {
406
- };
407
- injectedHtmlListeners.push(listener);
408
- return () => removeListener(injectedHtmlListeners, listener);
1129
+ if (cleanupStarted || serializationCompleteSignaled) disposeSerializationSafely(dispose);
1130
+ else disposeSerialization = dispose;
1131
+ if (synchronousFailure) throw synchronousFailure.error;
409
1132
  },
410
1133
  onRenderFinished: (listener) => {
411
- if (cleanupStarted || streamFastPathReserved) return;
412
- renderFinishedListeners.push(listener);
413
- },
414
- onSerializationFinished: (listener) => {
415
- if (cleanupStarted) return () => {
416
- };
417
- if (_serializationFinished && !cleanupStarted) {
1134
+ if (cleanupStarted) return;
1135
+ if (renderFinished) {
418
1136
  try {
419
1137
  listener();
420
- } catch (err) {
421
- console.error("Serialization listener error:", err);
1138
+ } catch (error) {
1139
+ console.error("Error in render finished listener:", error);
422
1140
  }
423
- return () => {
424
- };
1141
+ return;
425
1142
  }
426
- serializationFinishedListeners.push(listener);
427
- return () => removeListener(serializationFinishedListeners, listener);
1143
+ renderFinishedListeners.push(listener);
428
1144
  },
429
1145
  onCleanup: (listener) => {
430
- if (cleanupStarted) return;
1146
+ if (cleanupStarted) {
1147
+ try {
1148
+ listener(settled);
1149
+ } catch (error) {
1150
+ console.error("Error in SSR cleanup listener:", error);
1151
+ }
1152
+ return;
1153
+ }
431
1154
  cleanupListeners.push(listener);
432
1155
  },
433
1156
  setRenderFinished: () => {
434
- if (cleanupStarted) return;
435
- scriptBuffer.liftBarrier();
436
- const listeners = renderFinishedListeners.slice();
437
- renderFinishedListeners.length = 0;
438
- for (const l of listeners) try {
439
- l();
440
- } catch (err) {
441
- console.error("Error in render finished listener:", err);
442
- }
443
- if (_serializationFinished) scriptBuffer.flush();
444
- },
445
- takeBufferedScripts() {
446
- const scripts = scriptBuffer.takeAll();
447
- if (!scripts) return void 0;
448
- return {
449
- tag: "script",
450
- attrs: {
451
- nonce: router.options.ssr?.nonce,
452
- className: "$tsr",
453
- id: TSR_SCRIPT_BARRIER_ID
454
- },
455
- children: scripts
456
- };
457
- },
458
- liftScriptBarrier() {
459
- scriptBuffer.liftBarrier();
1157
+ if (cleanupStarted || renderFinished) return;
1158
+ renderFinished = true;
1159
+ hydrationScripts.liftBarrier();
1160
+ notifyAndClearListeners(renderFinishedListeners, "Error in render finished listener:", void 0);
460
1161
  },
461
- takeBufferedHtml() {
462
- if (!injectedHtmlBuffer) return;
463
- const buffered = injectedHtmlBuffer;
464
- injectedHtmlBuffer = "";
465
- return buffered;
1162
+ disableHydration: () => {
1163
+ if (cleanupStarted || dehydrationPhase === "disabled") return;
1164
+ if (dehydrationPhase !== "idle") {
1165
+ if (process.env.NODE_ENV !== "production") throw new Error("Invariant failed: cannot disable hydration after dehydrate()!");
1166
+ invariant();
1167
+ }
1168
+ hydrationScripts.disableHydration();
1169
+ dehydrationPhase = "disabled";
466
1170
  },
1171
+ takeInitialHydrationScriptTags: hydrationScripts.takeInitialHydrationScriptTags,
467
1172
  cleanup() {
468
1173
  if (cleanupStarted) return;
469
1174
  cleanupStarted = true;
470
- const listeners = cleanupListeners.slice();
471
- cleanupListeners.length = 0;
472
- for (const l of listeners) try {
473
- l();
474
- } catch (err) {
475
- console.error("Error in SSR cleanup listener:", err);
476
- }
1175
+ hydrationScripts.cleanup();
1176
+ const dispose = disposeSerialization;
1177
+ disposeSerialization = void 0;
1178
+ disposeSerializationSafely(dispose);
1179
+ notifyAndClearListeners(cleanupListeners, "Error in SSR cleanup listener:", settled);
477
1180
  renderFinishedListeners.length = 0;
478
- injectedHtmlListeners.length = 0;
479
- serializationFinishedListeners.length = 0;
480
- injectedHtmlBuffer = "";
481
- scriptBuffer.cleanup();
1181
+ router.ssr = void 0;
482
1182
  router.serverSsr = void 0;
483
1183
  }
484
1184
  };
@@ -489,17 +1189,11 @@ function attachRouterServerSsrUtils({ router, manifest: manifest2, getRequestAss
489
1189
  console.error("SSR attach listener error:", err);
490
1190
  }
491
1191
  }
492
- function getOrigin(request) {
493
- try {
494
- return new URL(request.url).origin;
495
- } catch {
496
- }
497
- return "http://localhost";
498
- }
499
1192
  function getNormalizedURL(url, base) {
500
1193
  if (typeof url === "string") url = url.replace("\\", "%5C");
501
1194
  const rawUrl = new URL(url, base);
502
- const { path: decodedPathname, handledProtocolRelativeURL } = decodePath(rawUrl.pathname);
1195
+ const handledProtocolRelativeURL = rawUrl.pathname.startsWith("//");
1196
+ const decodedPathname = decodePath(handledProtocolRelativeURL ? rawUrl.pathname.replace(/^\/+/, "/") : rawUrl.pathname);
503
1197
  const searchParams = new URLSearchParams(rawUrl.search);
504
1198
  const normalizedHref = decodedPathname + (searchParams.size > 0 ? "?" : "") + searchParams.toString() + rawUrl.hash;
505
1199
  return {
@@ -508,7 +1202,7 @@ function getNormalizedURL(url, base) {
508
1202
  };
509
1203
  }
510
1204
 
511
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/handlerCallback.js
1205
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/handlerCallback.js
512
1206
  function isSsrResponse(value) {
513
1207
  return typeof value === "object" && value !== null && "response" in value && "serverSsrCleanup" in value;
514
1208
  }
@@ -518,76 +1212,69 @@ function normalizeSsrResponse(result) {
518
1212
  serverSsrCleanup: "none"
519
1213
  };
520
1214
  }
521
- function disposeSsrResponse(response, reason) {
522
- if (response.serverSsrCleanup !== "stream") return Promise.resolve();
523
- try {
524
- return Promise.resolve(response.dispose(reason));
525
- } catch (error) {
526
- return Promise.reject(error);
527
- }
1215
+ function cancelResponseBody(response, reason) {
1216
+ const body = response.body;
1217
+ if (!body) return;
1218
+ body.cancel(reason).catch(console.error);
528
1219
  }
529
- function disposeSsrResponseDetached(result, reason, onError2 = console.error) {
530
- const ssrResponse = normalizeSsrResponse(result);
531
- if (ssrResponse.serverSsrCleanup === "stream") {
532
- disposeSsrResponse(ssrResponse, reason).catch(onError2);
533
- return;
534
- }
535
- if (ssrResponse.response.body) try {
536
- ssrResponse.response.body.cancel(reason).catch(onError2);
537
- } catch (error) {
538
- onError2(error);
539
- }
1220
+ function disposeSsrResponse(result, reason) {
1221
+ const response = normalizeSsrResponse(result);
1222
+ if (response.serverSsrCleanup === "stream") response.dispose(reason);
1223
+ else cancelResponseBody(response.response, reason);
1224
+ }
1225
+ function getSsrStatus(router) {
1226
+ return router._serverResult?.type === "render" ? router._serverResult.status : 200;
540
1227
  }
541
1228
  function createSsrStreamResponse(router, response) {
542
- if (!response.body) throw new Error("Invariant failed: SSR stream response requires a body");
543
- let disposed = false;
1229
+ const body = response.body;
1230
+ if (!body) throw new Error("Invariant failed: SSR stream response requires a body");
544
1231
  return {
545
1232
  response,
546
1233
  serverSsrCleanup: "stream",
547
- async dispose(reason) {
548
- if (disposed) return;
549
- disposed = true;
1234
+ dispose(reason) {
550
1235
  router.serverSsr?.cleanup();
551
- try {
552
- await response.body.cancel(reason);
553
- } catch {
554
- }
1236
+ body.cancel(reason).catch(() => {
1237
+ });
555
1238
  }
556
1239
  };
557
1240
  }
558
1241
  function bindSsrResponseToRequest(router, result, signal) {
559
1242
  const ssrResponse = normalizeSsrResponse(result);
560
1243
  if (ssrResponse.serverSsrCleanup !== "stream") {
561
- if (signal.aborted) disposeSsrResponseDetached(result, signal.reason);
1244
+ if (signal.aborted) disposeSsrResponse(result, signal.reason);
562
1245
  return ssrResponse;
563
1246
  }
564
- const failed = (error) => {
565
- router?.serverSsr?.cleanup();
566
- console.error(error);
567
- };
568
1247
  const abort = () => {
569
- disposeSsrResponseDetached(ssrResponse, signal.reason, failed);
1248
+ disposeSsrResponse(ssrResponse, signal.reason);
570
1249
  };
571
1250
  if (signal.aborted) {
572
1251
  abort();
573
1252
  return ssrResponse;
574
1253
  }
1254
+ const serverSsr = router?.serverSsr;
1255
+ if (serverSsr?.hydrationScripts.requestSignal === signal) {
1256
+ serverSsr.onCleanup(() => {
1257
+ if (signal.aborted) abort();
1258
+ });
1259
+ return ssrResponse;
1260
+ }
575
1261
  signal.addEventListener("abort", abort, { once: true });
576
- router?.serverSsr?.onCleanup(() => {
1262
+ if (!serverSsr) return ssrResponse;
1263
+ serverSsr.onCleanup(() => {
577
1264
  signal.removeEventListener("abort", abort);
578
1265
  });
579
1266
  return ssrResponse;
580
1267
  }
581
- async function replaceSsrResponse(result, response, reason) {
582
- await disposeSsrResponse(normalizeSsrResponse(result), reason);
1268
+ function replaceSsrResponse(result, response, reason) {
1269
+ disposeSsrResponse(result, reason);
583
1270
  return {
584
1271
  response,
585
1272
  serverSsrCleanup: "none"
586
1273
  };
587
1274
  }
588
- async function stripSsrResponseBody(result, reason) {
1275
+ function stripSsrResponseBody(result, reason) {
589
1276
  const ssrResponse = normalizeSsrResponse(result);
590
- await disposeSsrResponse(ssrResponse, reason);
1277
+ disposeSsrResponse(ssrResponse, reason);
591
1278
  return {
592
1279
  response: new Response(null, ssrResponse.response),
593
1280
  serverSsrCleanup: "none"
@@ -640,7 +1327,7 @@ function splitSetCookieString(cookiesString) {
640
1327
  return cookiesStrings;
641
1328
  }
642
1329
 
643
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/headers.js
1330
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/headers.js
644
1331
  function toHeadersInstance(init) {
645
1332
  if (init instanceof Headers) return init;
646
1333
  else if (Array.isArray(init)) return new Headers(init);
@@ -657,647 +1344,490 @@ function mergeHeaders(...headers) {
657
1344
  }, new Headers());
658
1345
  }
659
1346
 
660
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/createRequestHandler.js
661
- var requestWaiters = /* @__PURE__ */ new WeakMap();
662
- function removeRequestWaiter(waiters, index, reject) {
663
- if (waiters[index] !== reject) return;
664
- if (index !== waiters.length - 1) {
665
- waiters[index] = void 0;
666
- return;
667
- }
668
- waiters.pop();
669
- while (waiters.length && waiters[waiters.length - 1] === void 0) waiters.pop();
670
- }
671
- function waitForRequest(value, signal, onLate) {
672
- const promise = Promise.resolve(value);
673
- if (signal.aborted) {
674
- promise.then(onLate, () => {
675
- });
676
- return Promise.reject(signal.reason);
677
- }
678
- return new Promise((resolve, reject) => {
679
- let waiters = requestWaiters.get(signal);
680
- let index;
681
- if (waiters) index = waiters.push(reject) - 1;
682
- else {
683
- const newWaiters = [reject];
684
- waiters = newWaiters;
685
- index = 0;
686
- requestWaiters.set(signal, newWaiters);
687
- signal.addEventListener("abort", () => {
688
- requestWaiters.delete(signal);
689
- for (const rejectWaiter of newWaiters) rejectWaiter?.(signal.reason);
690
- newWaiters.length = 0;
691
- }, { once: true });
692
- }
693
- promise.then((result) => {
694
- removeRequestWaiter(waiters, index, reject);
695
- if (signal.aborted) onLate?.(result);
696
- else resolve(result);
697
- }, (error) => {
698
- removeRequestWaiter(waiters, index, reject);
699
- reject(error);
700
- });
701
- });
702
- }
703
-
704
- // node_modules/.pnpm/@tanstack+router-core@1.171.27/node_modules/@tanstack/router-core/dist/esm/ssr/transformStreamWithRouter.js
705
- import { ReadableStream as ReadableStream2 } from "node:stream/web";
706
- import { Readable } from "node:stream";
707
- function transformReadableStreamWithRouter(router, routerStream, opts) {
708
- return transformStreamWithRouter(router, routerStream, opts);
709
- }
710
- function transformPipeableStreamWithRouter(router, routerStream, opts) {
711
- return Readable.fromWeb(transformStreamWithRouter(router, Readable.toWeb(routerStream), opts));
712
- }
713
- var MIN_CLOSING_TAG_LENGTH = 4;
1347
+ // node_modules/.pnpm/@tanstack+router-core@1.171.33/node_modules/@tanstack/router-core/dist/esm/ssr/transformStreamWithRouter.js
714
1348
  var DEFAULT_SERIALIZATION_TIMEOUT_MS = 6e4;
715
- var DEFAULT_LIFETIME_TIMEOUT_MS = DEFAULT_SERIALIZATION_TIMEOUT_MS * 2;
716
- var MAX_LEFTOVER_CHARS = 2048;
717
- var MAX_TAIL_CHARS = 64 * 1024;
718
- var MAX_ROUTER_HTML_CHARS = 16 * 1024 * 1024;
719
- var MAX_PENDING_WRITE_CHARS = 16 * 1024 * 1024;
720
- var MergeState = {
721
- ReadingBody: 0,
722
- HoldingTail: 1,
723
- AppDone: 2,
724
- Draining: 3,
725
- Done: 4
1349
+ var MIN_APPLICATION_STRING_CHUNK_BYTES = 256;
1350
+ var MAX_APPLICATION_STRING_CHUNK_BYTES = 64 * 1024;
1351
+ var ApplicationPhase = {
1352
+ BeforeBoundary: 0,
1353
+ Merge: 1,
1354
+ HeldClose: 2,
1355
+ PassThrough: 3
726
1356
  };
727
- var textEncoder = new TextEncoder();
728
- var noop = () => {
729
- };
730
- var resolvedPromise = Promise.resolve();
731
- function findHtmlBoundary(str) {
732
- let lastClosingTagEnd = -1;
733
- let searchFrom = str.length - MIN_CLOSING_TAG_LENGTH;
734
- while (searchFrom >= 0) {
735
- const openSlash = str.lastIndexOf("</", searchFrom);
736
- if (openSlash === -1) break;
737
- if ((str.charCodeAt(openSlash + 2) | 32) === 98 && (str.charCodeAt(openSlash + 3) | 32) === 111 && (str.charCodeAt(openSlash + 4) | 32) === 100 && (str.charCodeAt(openSlash + 5) | 32) === 121 && str.charCodeAt(openSlash + 6) === 62) return -openSlash - 2;
738
- if (lastClosingTagEnd === -1) {
739
- let i = openSlash + 2;
740
- const startCode = str.charCodeAt(i);
741
- if (startCode >= 97 && startCode <= 122 || startCode >= 65 && startCode <= 90) {
742
- i++;
743
- while (i < str.length) {
744
- const code = str.charCodeAt(i);
745
- if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57 || code === 95 || code === 58 || code === 46 || code === 45) i++;
746
- else break;
747
- }
748
- if (str.charCodeAt(i) === 62) lastClosingTagEnd = i + 1;
749
- }
750
- }
751
- searchFrom = openSlash - 1;
752
- }
753
- return lastClosingTagEnd;
754
- }
755
- function safeReleaseReader(reader) {
1357
+ function releaseReader(reader) {
756
1358
  try {
757
1359
  reader.releaseLock();
758
- return true;
759
1360
  } catch {
760
- return false;
761
1361
  }
762
1362
  }
763
- function safeCancelReader(reader, reason) {
764
- let cancelPromise;
1363
+ function cancelReader(reader, reason) {
1364
+ const cancelled = reader.cancel(reason).catch(() => {
1365
+ });
1366
+ releaseReader(reader);
1367
+ return cancelled;
1368
+ }
1369
+ function finalizeSsrStream(kind, reason, controller, reader, serverSsr, onAbort) {
765
1370
  try {
766
- cancelPromise = reader.cancel(reason);
1371
+ if (kind === "complete") controller.close();
1372
+ else if (kind === "failure") controller.error(reason);
767
1373
  } catch {
768
1374
  }
769
- if (!safeReleaseReader(reader) && cancelPromise) return cancelPromise.then(noop, noop).then(() => {
770
- safeReleaseReader(reader);
771
- });
772
- return cancelPromise ? cancelPromise.then(noop, noop) : resolvedPromise;
1375
+ const aborted = kind !== "complete";
1376
+ if (aborted) try {
1377
+ onAbort?.(reason);
1378
+ } catch {
1379
+ }
1380
+ const readerDone = aborted ? cancelReader(reader, reason) : releaseReader(reader);
1381
+ serverSsr.cleanup();
1382
+ return readerDone;
773
1383
  }
774
- function createReaderState(appStream) {
775
- const reader = appStream.getReader();
776
- let released = false;
777
- return {
778
- reader,
779
- cancel: (reason) => {
780
- if (released) return resolvedPromise;
781
- released = true;
782
- return safeCancelReader(reader, reason);
783
- },
784
- release: () => {
785
- if (released) return;
786
- released = true;
787
- safeReleaseReader(reader);
788
- }
789
- };
1384
+ function getLifetimeMs(opts) {
1385
+ return opts?.lifetimeMs ?? (opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS) * 2;
790
1386
  }
791
- function createAbortNotifier(opts) {
792
- let abortNotified = false;
793
- return (reason) => {
794
- if (abortNotified) return;
795
- abortNotified = true;
796
- try {
797
- opts?.onAbort?.(reason);
798
- } catch {
799
- }
800
- };
1387
+ function createCleanupAbortError() {
1388
+ const error = /* @__PURE__ */ new Error("SSR stream transform aborted by router SSR cleanup");
1389
+ error.name = "AbortError";
1390
+ return error;
801
1391
  }
802
- function listenToAbort(signal, onAbort) {
1392
+ function listenForAbort(signal, onAbort) {
803
1393
  if (!signal) return;
804
- if (signal.aborted) {
805
- onAbort(signal.reason);
806
- return;
807
- }
808
1394
  const listener = () => onAbort(signal.reason);
809
1395
  signal.addEventListener("abort", listener, { once: true });
810
1396
  return () => signal.removeEventListener("abort", listener);
811
1397
  }
812
- function transformStreamWithRouter(router, appStream, opts) {
813
- const serverSsr = router.serverSsr;
814
- if (!serverSsr) throw new Error("Invariant failed: router.serverSsr is required");
815
- if (serverSsr.reserveStreamFastPath()) return makeFastPathStream(appStream, opts, serverSsr);
816
- return makeMainStream(serverSsr, appStream, opts);
1398
+ function setUnrefTimeout(callback, timeoutMs) {
1399
+ const handle = setTimeout(callback, timeoutMs);
1400
+ handle.unref?.();
1401
+ return handle;
817
1402
  }
818
- function makeFastPathStream(appStream, opts, serverSsr) {
819
- let cleanedUp = false;
820
- let controller;
821
- let state = MergeState.ReadingBody;
1403
+ function armStreamLifecycle(serverSsr, opts, isTerminal, terminate) {
1404
+ const signal = opts?.signal;
822
1405
  let lifetimeTimeoutHandle;
823
- let stopListeningToAbort;
824
- let stopListeningToInjectedHtml;
825
- const readerState = createReaderState(appStream);
826
- const notifyAbort = createAbortNotifier(opts);
827
- const isDone = () => state === MergeState.Done;
828
- let renderFinished = false;
829
- const finishSsrRendering = () => {
830
- if (!serverSsr || renderFinished) return true;
831
- renderFinished = true;
832
- try {
833
- serverSsr.setRenderFinished();
834
- return true;
835
- } catch (error) {
836
- safeError(error);
837
- cleanup(error);
838
- return false;
839
- }
840
- };
841
- const cleanup = (reason, cancelReader = true) => {
842
- if (cleanedUp) return resolvedPromise;
843
- cleanedUp = true;
1406
+ let stopAbortListener;
1407
+ const disarm = () => {
1408
+ stopAbortListener?.();
1409
+ stopAbortListener = void 0;
1410
+ if (signal && serverSsr.hydrationScripts.requestSignal === signal) serverSsr.hydrationScripts.requestSignal = void 0;
844
1411
  if (lifetimeTimeoutHandle !== void 0) {
845
1412
  clearTimeout(lifetimeTimeoutHandle);
846
1413
  lifetimeTimeoutHandle = void 0;
847
1414
  }
848
- stopListeningToAbort?.();
849
- stopListeningToAbort = void 0;
850
- try {
851
- stopListeningToInjectedHtml?.();
852
- } catch {
853
- }
854
- stopListeningToInjectedHtml = void 0;
855
- if (cancelReader) notifyAbort(reason);
856
- const readerDone = cancelReader ? readerState.cancel(reason) : (readerState.release(), resolvedPromise);
857
- if (serverSsr) try {
858
- serverSsr.cleanup();
859
- } catch (error) {
860
- console.error("Error in SSR cleanup:", error);
861
- }
862
- return readerDone;
863
- };
864
- const safeClose = () => {
865
- if (isDone()) return;
866
- state = MergeState.Done;
867
- try {
868
- controller?.close();
869
- } catch {
870
- }
871
- };
872
- const safeError = (error) => {
873
- if (isDone()) return;
874
- state = MergeState.Done;
875
- try {
876
- controller?.error(error);
877
- } catch {
878
- }
879
1415
  };
880
- if (serverSsr) stopListeningToInjectedHtml = serverSsr.onInjectedHtml(() => {
881
- const err = /* @__PURE__ */ new Error("SSR router HTML injected during fast path");
882
- safeError(err);
883
- cleanup(err);
884
- });
885
- const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS;
886
- lifetimeTimeoutHandle = setTimeout(() => {
887
- if (!cleanedUp && !isDone()) {
888
- const err = /* @__PURE__ */ new Error("Stream lifetime exceeded");
889
- console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`);
890
- safeError(err);
891
- cleanup(err);
892
- }
1416
+ const lifetimeMs = getLifetimeMs(opts);
1417
+ lifetimeTimeoutHandle = setUnrefTimeout(() => {
1418
+ if (isTerminal()) return;
1419
+ const error = /* @__PURE__ */ new Error("Stream lifetime exceeded");
1420
+ console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`);
1421
+ terminate("failure", error);
893
1422
  }, lifetimeMs);
894
- const stream = new ReadableStream2({
895
- start(c) {
896
- controller = c;
897
- },
898
- async pull(c) {
899
- if (cleanedUp || isDone()) return;
900
- try {
901
- const { done, value } = await readerState.reader.read();
902
- if (!done) {
903
- if (!cleanedUp && !isDone()) c.enqueue(value);
904
- return;
905
- }
906
- if (cleanedUp || isDone()) return;
907
- if (!finishSsrRendering()) return;
908
- safeClose();
909
- return cleanup(void 0, false);
910
- } catch (error) {
911
- if (cleanedUp) return;
912
- console.error("Error reading appStream:", error);
913
- if (state < MergeState.AppDone) try {
914
- serverSsr?.setRenderFinished();
915
- } catch {
916
- }
917
- safeError(error);
918
- return cleanup(error);
919
- } finally {
920
- if (cleanedUp || isDone()) readerState.release();
921
- }
922
- },
923
- cancel(reason) {
924
- state = MergeState.Done;
925
- return cleanup(reason);
926
- }
1423
+ stopAbortListener = listenForAbort(signal, (reason) => {
1424
+ terminate("failure", reason);
927
1425
  });
928
- stopListeningToAbort = listenToAbort(opts?.signal, (reason) => {
929
- safeError(reason);
930
- cleanup(reason);
1426
+ if (signal) serverSsr.hydrationScripts.requestSignal = signal;
1427
+ serverSsr.onCleanup(() => {
1428
+ if (!isTerminal()) terminate("failure", createCleanupAbortError());
931
1429
  });
932
- return stream;
1430
+ return disarm;
933
1431
  }
934
- function makeMainStream(serverSsr, appStream, opts) {
935
- let stopListeningToInjectedHtml;
936
- let stopListeningToSerializationFinished;
937
- let serializationTimeoutHandle;
938
- let lifetimeTimeoutHandle;
939
- let stopListeningToAbort;
940
- let cleanedUp = false;
941
- let controller;
942
- let closeWhenDrained = false;
943
- let state = MergeState.ReadingBody;
944
- const readerState = createReaderState(appStream);
945
- const notifyAbort = createAbortNotifier(opts);
946
- const pendingWrites = [];
947
- let pendingWriteHead = 0;
948
- let pendingWriteChars = 0;
949
- function clearPending() {
950
- pendingWrites.length = 0;
951
- pendingWriteHead = 0;
952
- pendingWriteChars = 0;
953
- }
954
- let drainResolve = null;
955
- const waitForDrain = () => new Promise((r) => {
956
- drainResolve = r;
957
- });
958
- const signalDrain = () => {
959
- if (drainResolve) {
960
- const r = drainResolve;
961
- drainResolve = null;
962
- r();
963
- }
1432
+ function cleanupFailedStreamCreation(serverSsr, onAbort, error) {
1433
+ try {
1434
+ onAbort?.(error);
1435
+ } catch {
1436
+ }
1437
+ serverSsr.cleanup();
1438
+ }
1439
+ function encodeStringSource(value, offset) {
1440
+ const remaining = value.length - offset;
1441
+ const capacity = Math.min(MAX_APPLICATION_STRING_CHUNK_BYTES, Math.max(MIN_APPLICATION_STRING_CHUNK_BYTES, Math.min(value.length, remaining * 3)));
1442
+ const output = new Uint8Array(capacity);
1443
+ const { read, written } = encodeIntoBoundedChunk(value, offset, output);
1444
+ return {
1445
+ bytes: written === output.length ? output : output.subarray(0, written),
1446
+ read
964
1447
  };
965
- const isDone = () => state === MergeState.Done;
966
- function drainPending() {
967
- if (!controller || isDone()) return;
968
- while (pendingWriteHead < pendingWrites.length) {
969
- const ds = controller.desiredSize;
970
- if (ds !== null && ds <= 0) return;
971
- const next = pendingWrites[pendingWriteHead];
972
- pendingWrites[pendingWriteHead] = "";
973
- pendingWriteHead++;
974
- pendingWriteChars -= next.length;
975
- try {
976
- controller.enqueue(textEncoder.encode(next));
977
- } catch (error) {
978
- safeError(error);
979
- cleanup(error);
980
- return;
981
- }
982
- }
983
- if (pendingWriteHead >= pendingWrites.length) {
984
- pendingWrites.length = 0;
985
- pendingWriteHead = 0;
986
- }
987
- if (closeWhenDrained && pendingWriteHead >= pendingWrites.length) {
988
- closeWhenDrained = false;
989
- safeClose();
990
- cleanup(void 0, false);
991
- }
1448
+ }
1449
+ function transformReadableStreamWithRouter(router, appStream, opts) {
1450
+ const serverSsr = router.serverSsr;
1451
+ if (!serverSsr) throw new Error("Invariant failed: router.serverSsr is required");
1452
+ const hydrationScripts = serverSsr.hydrationScripts;
1453
+ let reader;
1454
+ try {
1455
+ reader = appStream.getReader();
1456
+ } catch (error) {
1457
+ cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error);
1458
+ throw error;
992
1459
  }
993
- function writeChunk(chunk) {
994
- if (cleanedUp || isDone()) return;
995
- if (!chunk.length) return;
996
- if (pendingWriteChars + chunk.length > MAX_PENDING_WRITE_CHARS) {
997
- const err = /* @__PURE__ */ new Error("SSR stream pending output exceeded maximum buffer");
998
- safeError(err);
999
- cleanup(err);
1000
- return;
1001
- }
1002
- pendingWrites.push(chunk);
1003
- pendingWriteChars += chunk.length;
1004
- drainPending();
1460
+ try {
1461
+ opts?.signal?.throwIfAborted();
1462
+ if (hydrationScripts.reserveFastPath()) return makeMergeStream(serverSsr, reader, void 0, opts);
1463
+ const hydrationOutput = hydrationScripts.claimOutput();
1464
+ if (hydrationOutput.state === HydrationScriptOutputState.Failed) throw hydrationOutput.error;
1465
+ return makeMergeStream(serverSsr, reader, hydrationOutput, opts);
1466
+ } catch (error) {
1467
+ cancelReader(reader, error);
1468
+ cleanupFailedStreamCreation(serverSsr, opts?.onAbort, error);
1469
+ throw error;
1005
1470
  }
1006
- function safeClose() {
1007
- if (isDone()) return;
1008
- state = MergeState.Done;
1009
- try {
1010
- controller?.close();
1011
- } catch {
1012
- }
1471
+ }
1472
+ function makeMergeStream(serverSsr, reader, hydrationOutput, opts) {
1473
+ const hydrationScripts = serverSsr.hydrationScripts;
1474
+ let controller;
1475
+ let terminal = false;
1476
+ let appDone = false;
1477
+ let applicationPhase = hydrationOutput ? ApplicationPhase.BeforeBoundary : ApplicationPhase.PassThrough;
1478
+ let insertionBoundary = false;
1479
+ let stopHydrationOutputListener;
1480
+ let appReadPending = false;
1481
+ let settledAppRead;
1482
+ let appBytes;
1483
+ let appOffset = 0;
1484
+ let documentCloseIndex;
1485
+ let appString;
1486
+ let appStringOffset = 0;
1487
+ const useScriptCloseSafePoints = opts?.rendererSafePoint === "script-close";
1488
+ const useRecordEndSafePoints = opts?.rendererSafePoint === "record-end";
1489
+ let barrierMatcher;
1490
+ let safePointMatcher;
1491
+ let closeCarry;
1492
+ let wakeResolve;
1493
+ let disarmLifecycle = () => {
1494
+ };
1495
+ function waitForWake() {
1496
+ return new Promise((resolve) => {
1497
+ wakeResolve = resolve;
1498
+ });
1013
1499
  }
1014
- function safeError(error) {
1015
- if (isDone()) return;
1016
- state = MergeState.Done;
1017
- try {
1018
- controller?.error(error);
1019
- } catch {
1020
- }
1500
+ function wakePump() {
1501
+ const resolve = wakeResolve;
1502
+ wakeResolve = void 0;
1503
+ resolve?.();
1021
1504
  }
1022
- function cleanup(reason, cancelReader = true) {
1023
- if (cleanedUp) return resolvedPromise;
1024
- cleanedUp = true;
1025
- try {
1026
- stopListeningToInjectedHtml?.();
1027
- stopListeningToSerializationFinished?.();
1028
- } catch {
1505
+ function enqueueAppBytes(value) {
1506
+ if (value.length === 0) return false;
1507
+ controller.enqueue(value);
1508
+ return true;
1509
+ }
1510
+ function finishAppChunk() {
1511
+ appBytes = void 0;
1512
+ documentCloseIndex = void 0;
1513
+ if (appString === void 0 && useRecordEndSafePoints && closeCarry === void 0) insertionBoundary = true;
1514
+ }
1515
+ function emitAppRange(end, safePoint, finishCurrentChunk = end === appBytes.length) {
1516
+ const value = appBytes;
1517
+ const output = appOffset === 0 && end === value.length ? value : value.subarray(appOffset, end);
1518
+ appOffset = end;
1519
+ if (safePoint) insertionBoundary = true;
1520
+ if (finishCurrentChunk) finishAppChunk();
1521
+ return enqueueAppBytes(output);
1522
+ }
1523
+ function loadNextAppStringChunk() {
1524
+ const value = appString;
1525
+ const encoded = encodeStringSource(value, appStringOffset);
1526
+ appStringOffset += encoded.read;
1527
+ appBytes = encoded.bytes;
1528
+ appOffset = 0;
1529
+ if (appStringOffset === value.length) appString = void 0;
1530
+ }
1531
+ function processUntilBarrier() {
1532
+ const value = appBytes;
1533
+ if (!hydrationScripts.isInitialTaken()) return emitAppRange(value.length, false);
1534
+ const matchEnd = advanceByteMatcher(barrierMatcher ??= {
1535
+ pattern: HYDRATION_SCRIPT_BOUNDARY_BYTES,
1536
+ anchorIndex: HYDRATION_SCRIPT_BOUNDARY_ANCHOR_INDEX,
1537
+ matched: 0
1538
+ }, value, appOffset);
1539
+ if (matchEnd === void 0) return emitAppRange(value.length, false);
1540
+ applicationPhase = ApplicationPhase.Merge;
1541
+ hydrationScripts.liftBarrier();
1542
+ return emitAppRange(matchEnd, true);
1543
+ }
1544
+ function enterHeldClose(consumed, prefix) {
1545
+ appOffset = consumed;
1546
+ applicationPhase = ApplicationPhase.HeldClose;
1547
+ if (safePointMatcher) safePointMatcher.matched = 0;
1548
+ insertionBoundary = true;
1549
+ if (appOffset === appBytes.length) finishAppChunk();
1550
+ return prefix ? enqueueAppBytes(prefix) : false;
1551
+ }
1552
+ function holdDocumentClose(matchStart) {
1553
+ const value = appBytes;
1554
+ return enterHeldClose(matchStart + DOCUMENT_CLOSE_BYTES.length, matchStart === appOffset ? void 0 : value.subarray(appOffset, matchStart));
1555
+ }
1556
+ function processUntilSafePoint(endIndex) {
1557
+ const matchEnd = findSafePointEnd(appBytes, appOffset, endIndex);
1558
+ if (matchEnd === void 0) return false;
1559
+ return emitAppRange(matchEnd, true);
1560
+ }
1561
+ function findSafePointEnd(value, startIndex, endIndex) {
1562
+ const hydrationState = hydrationOutput.state;
1563
+ if (endIndex === startIndex || hydrationState === HydrationScriptOutputState.Done) return;
1564
+ const scanValue = endIndex === value.length ? value : value.subarray(0, endIndex);
1565
+ const matcher = safePointMatcher ??= {
1566
+ pattern: SCRIPT_CLOSE_BYTES,
1567
+ anchorIndex: SCRIPT_CLOSE_ANCHOR_INDEX,
1568
+ matched: 0
1569
+ };
1570
+ const waiting = hydrationState === HydrationScriptOutputState.Waiting;
1571
+ const matchEnd = advanceByteMatcher(matcher, scanValue, startIndex, waiting);
1572
+ if (matchEnd === void 0) return;
1573
+ if (waiting) matcher.matched = 0;
1574
+ return matchEnd;
1575
+ }
1576
+ function processCloseCarry() {
1577
+ const value = appBytes;
1578
+ const carry = closeCarry;
1579
+ const headLength = Math.min(value.length - appOffset, DOCUMENT_CLOSE_BYTES.length);
1580
+ const combined = new Uint8Array(carry.length + headLength);
1581
+ combined.set(carry);
1582
+ combined.set(value.subarray(appOffset, appOffset + headLength), carry.length);
1583
+ const matchStart = findExactBytes(combined, DOCUMENT_CLOSE_BYTES, 0, DOCUMENT_CLOSE_ANCHOR_INDEX);
1584
+ const partial = matchStart < 0 ? getExactBytesPrefixAtEnd(combined, DOCUMENT_CLOSE_BYTES) : void 0;
1585
+ const safeEnd = matchStart >= 0 ? matchStart : partial ?? combined.length;
1586
+ if (useScriptCloseSafePoints) {
1587
+ const safePointEnd = findSafePointEnd(combined, 0, safeEnd);
1588
+ if (safePointEnd !== void 0) {
1589
+ appOffset += safePointEnd - carry.length;
1590
+ closeCarry = void 0;
1591
+ insertionBoundary = true;
1592
+ if (appOffset === value.length) finishAppChunk();
1593
+ return enqueueAppBytes(combined.subarray(0, safePointEnd));
1594
+ }
1029
1595
  }
1030
- stopListeningToInjectedHtml = void 0;
1031
- stopListeningToSerializationFinished = void 0;
1032
- stopListeningToAbort?.();
1033
- stopListeningToAbort = void 0;
1034
- if (serializationTimeoutHandle !== void 0) {
1035
- clearTimeout(serializationTimeoutHandle);
1036
- serializationTimeoutHandle = void 0;
1596
+ if (matchStart >= 0) {
1597
+ closeCarry = void 0;
1598
+ return enterHeldClose(appOffset + matchStart + DOCUMENT_CLOSE_BYTES.length - carry.length, matchStart === 0 ? void 0 : combined.subarray(0, matchStart));
1037
1599
  }
1038
- if (lifetimeTimeoutHandle !== void 0) {
1039
- clearTimeout(lifetimeTimeoutHandle);
1040
- lifetimeTimeoutHandle = void 0;
1600
+ closeCarry = partial === void 0 ? void 0 : combined.slice(partial);
1601
+ appOffset += headLength;
1602
+ return enqueueAppBytes(safeEnd === combined.length ? combined : combined.subarray(0, safeEnd));
1603
+ }
1604
+ function processUntilDocumentClose() {
1605
+ const value = appBytes;
1606
+ if (closeCarry) {
1607
+ if (processCloseCarry()) return true;
1608
+ if (applicationPhase === ApplicationPhase.HeldClose) return false;
1609
+ if (appOffset >= value.length) {
1610
+ finishAppChunk();
1611
+ return false;
1612
+ }
1041
1613
  }
1042
- clearPendingRouterHtml();
1043
- leftover = "";
1044
- pendingTail = "";
1045
- clearPending();
1046
- if (cancelReader) notifyAbort(reason);
1047
- const readerDone = cancelReader ? readerState.cancel(reason) : (readerState.release(), resolvedPromise);
1048
- signalDrain();
1049
- try {
1050
- serverSsr.cleanup();
1051
- } catch (error) {
1052
- console.error("Error in SSR cleanup:", error);
1614
+ const matchStart = documentCloseIndex ??= findExactBytes(value, DOCUMENT_CLOSE_BYTES, appOffset, DOCUMENT_CLOSE_ANCHOR_INDEX);
1615
+ if (matchStart >= 0) {
1616
+ if (useScriptCloseSafePoints && processUntilSafePoint(matchStart)) return true;
1617
+ return holdDocumentClose(matchStart);
1053
1618
  }
1054
- return readerDone;
1055
- }
1056
- const textDecoder = new TextDecoder();
1057
- const pendingRouterHtml = [];
1058
- let pendingRouterHtmlChars = 0;
1059
- let leftover = "";
1060
- let pendingTail = "";
1061
- let streamBarrierLifted = false;
1062
- let streamBarrierMarkerSeen = false;
1063
- let serializationFinished = false;
1064
- function noteBarrierMarker(chunk) {
1065
- if (streamBarrierMarkerSeen) return;
1066
- if (chunk.includes("$tsr-stream-barrier")) streamBarrierMarkerSeen = true;
1067
- }
1068
- function liftBarrierAfterBoundary() {
1069
- if (streamBarrierLifted) return;
1070
- if (!streamBarrierMarkerSeen) return;
1071
- streamBarrierLifted = true;
1072
- serverSsr.liftScriptBarrier();
1073
- }
1074
- const stream = new ReadableStream2({
1075
- start(c) {
1076
- controller = c;
1077
- drainPending();
1078
- },
1079
- pull() {
1080
- drainPending();
1081
- signalDrain();
1082
- },
1083
- cancel(reason) {
1084
- state = MergeState.Done;
1085
- return cleanup(reason);
1619
+ const partial = getExactBytesPrefixAtEnd(value, DOCUMENT_CLOSE_BYTES, appOffset);
1620
+ const safeEnd = partial ?? value.length;
1621
+ if (useScriptCloseSafePoints && processUntilSafePoint(safeEnd)) return true;
1622
+ closeCarry = partial === void 0 ? void 0 : value.slice(partial);
1623
+ return emitAppRange(safeEnd, false, true);
1624
+ }
1625
+ function processAppChunk() {
1626
+ if (appOffset >= appBytes.length) {
1627
+ finishAppChunk();
1628
+ return false;
1086
1629
  }
1087
- });
1088
- function drainRouterHtml() {
1089
- if (cleanedUp || isDone()) return;
1090
- let html;
1091
- try {
1092
- html = serverSsr.takeBufferedHtml();
1093
- } catch (error) {
1094
- safeError(error);
1095
- cleanup(error);
1630
+ insertionBoundary = false;
1631
+ if (applicationPhase === ApplicationPhase.BeforeBoundary) return processUntilBarrier();
1632
+ if (applicationPhase === ApplicationPhase.Merge) return processUntilDocumentClose();
1633
+ const value = appBytes;
1634
+ if (useScriptCloseSafePoints && processUntilSafePoint(value.length)) return true;
1635
+ return emitAppRange(value.length, false);
1636
+ }
1637
+ function terminate(kind, reason) {
1638
+ if (terminal) return;
1639
+ terminal = true;
1640
+ stopHydrationOutputListener?.();
1641
+ stopHydrationOutputListener = void 0;
1642
+ disarmLifecycle();
1643
+ settledAppRead = void 0;
1644
+ appBytes = void 0;
1645
+ documentCloseIndex = void 0;
1646
+ appString = void 0;
1647
+ closeCarry = void 0;
1648
+ wakePump();
1649
+ return finalizeSsrStream(kind, reason, controller, reader, serverSsr, opts?.onAbort);
1650
+ }
1651
+ function startAppRead() {
1652
+ if (appReadPending || settledAppRead || terminal) return;
1653
+ appReadPending = true;
1654
+ reader.read().then((result) => {
1655
+ appReadPending = false;
1656
+ if (!terminal) {
1657
+ if (result.done) acceptAppRead(result);
1658
+ else settledAppRead = result;
1659
+ wakePump();
1660
+ }
1661
+ }, (error) => {
1662
+ appReadPending = false;
1663
+ if (!terminal) handlePumpError(error);
1664
+ });
1665
+ }
1666
+ function acceptAppRead(result) {
1667
+ if (result.done) {
1668
+ appDone = true;
1669
+ insertionBoundary = closeCarry === void 0;
1670
+ hydrationScripts.startSerializationTimeout(opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS);
1671
+ serverSsr.setRenderFinished();
1096
1672
  return;
1097
1673
  }
1098
- if (!html) return;
1099
- if (state >= MergeState.Draining) {
1100
- const err = /* @__PURE__ */ new Error("SSR router HTML injected after stream finalization");
1101
- safeError(err);
1102
- cleanup(err);
1674
+ const value = result.value;
1675
+ if (typeof value === "string") {
1676
+ if (value.length === 0) return;
1677
+ appString = value;
1678
+ appStringOffset = 0;
1679
+ insertionBoundary = false;
1680
+ loadNextAppStringChunk();
1103
1681
  return;
1104
1682
  }
1105
- if (state === MergeState.HoldingTail) {
1106
- flushPendingRouterHtml();
1107
- writeChunk(html);
1108
- } else {
1109
- if (pendingRouterHtmlChars + html.length > MAX_ROUTER_HTML_CHARS) {
1110
- const err = /* @__PURE__ */ new Error("SSR router HTML exceeded maximum buffer");
1111
- safeError(err);
1112
- cleanup(err);
1113
- return;
1114
- }
1115
- pendingRouterHtml.push(html);
1116
- pendingRouterHtmlChars += html.length;
1117
- }
1118
- }
1119
- function flushPendingRouterHtml() {
1120
- if (!pendingRouterHtml.length) return;
1121
- for (const html of pendingRouterHtml) writeChunk(html);
1122
- clearPendingRouterHtml();
1123
- }
1124
- function clearPendingRouterHtml() {
1125
- pendingRouterHtml.length = 0;
1126
- pendingRouterHtmlChars = 0;
1127
- }
1128
- function appendTail(chunk) {
1129
- pendingTail += chunk;
1130
- if (pendingTail.length > MAX_TAIL_CHARS) throw new Error("SSR stream tail exceeded maximum buffer");
1131
- }
1132
- function waitForBackpressure() {
1133
- return !!(controller && controller.desiredSize !== null && controller.desiredSize <= 0);
1134
- }
1135
- function startSerializationTimeout() {
1136
- if (cleanedUp || isDone()) return;
1137
- if (serializationTimeoutHandle !== void 0) return;
1138
- const timeoutMs2 = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS;
1139
- serializationTimeoutHandle = setTimeout(() => {
1140
- if (!cleanedUp && !isDone()) {
1141
- const err = /* @__PURE__ */ new Error("Serialization timeout after app render finished");
1142
- console.error("Serialization timeout after app render finished");
1143
- safeError(err);
1144
- cleanup(err);
1145
- }
1146
- }, timeoutMs2);
1147
- }
1148
- function tryFinish() {
1149
- if (state !== MergeState.AppDone || !serializationFinished) return;
1150
- if (cleanedUp || isDone()) return;
1151
- if (serializationTimeoutHandle !== void 0) {
1152
- clearTimeout(serializationTimeoutHandle);
1153
- serializationTimeoutHandle = void 0;
1683
+ if (value.byteLength === 0) return;
1684
+ appBytes = value;
1685
+ appOffset = 0;
1686
+ insertionBoundary = false;
1687
+ }
1688
+ async function loadNextAppChunk() {
1689
+ if (appString !== void 0) {
1690
+ loadNextAppStringChunk();
1691
+ return;
1154
1692
  }
1155
- drainRouterHtml();
1156
- if (cleanedUp || isDone()) return;
1157
- const decoderRemainder = textDecoder.decode();
1158
- if (leftover) writeChunk(leftover);
1159
- if (cleanedUp || isDone()) return;
1160
- if (decoderRemainder) writeChunk(decoderRemainder);
1161
- if (cleanedUp || isDone()) return;
1162
- flushPendingRouterHtml();
1163
- if (cleanedUp || isDone()) return;
1164
- if (pendingTail) writeChunk(pendingTail);
1165
- if (cleanedUp || isDone()) return;
1166
- leftover = "";
1167
- pendingTail = "";
1168
- state = MergeState.Draining;
1169
- closeWhenDrained = true;
1170
- drainPending();
1171
- }
1172
- function finishAppRendering() {
1173
- if (state >= MergeState.AppDone) return;
1174
- state = MergeState.AppDone;
1175
- try {
1176
- serverSsr.setRenderFinished();
1177
- } catch (error) {
1178
- safeError(error);
1179
- cleanup(error);
1693
+ if (settledAppRead) {
1694
+ const settled = settledAppRead;
1695
+ settledAppRead = void 0;
1696
+ acceptAppRead(settled);
1180
1697
  return;
1181
1698
  }
1182
- drainRouterHtml();
1183
- if (cleanedUp || isDone()) return;
1184
- serializationFinished = serializationFinished || serverSsr.isSerializationFinished();
1185
- if (serializationFinished) tryFinish();
1186
- else startSerializationTimeout();
1187
- }
1188
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS;
1189
- const lifetimeMs = opts?.lifetimeMs ?? timeoutMs * 2;
1190
- lifetimeTimeoutHandle = setTimeout(() => {
1191
- if (!cleanedUp && !isDone()) {
1192
- const err = /* @__PURE__ */ new Error("Stream lifetime exceeded");
1193
- console.warn(`SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`);
1194
- safeError(err);
1195
- cleanup(err);
1699
+ if (!(applicationPhase !== ApplicationPhase.BeforeBoundary && insertionBoundary && hydrationOutput.state !== HydrationScriptOutputState.Done) && !appReadPending) {
1700
+ const result = await reader.read();
1701
+ if (terminal) return;
1702
+ acceptAppRead(result);
1703
+ return;
1196
1704
  }
1197
- }, lifetimeMs);
1198
- stopListeningToInjectedHtml = serverSsr.onInjectedHtml(() => {
1199
- drainRouterHtml();
1200
- });
1201
- stopListeningToSerializationFinished = serverSsr.onSerializationFinished(() => {
1202
- serializationFinished = true;
1203
- drainRouterHtml();
1204
- tryFinish();
1205
- });
1206
- drainRouterHtml();
1207
- if (cleanedUp || isDone()) return stream;
1208
- serializationFinished = serializationFinished || serverSsr.isSerializationFinished();
1209
- if (serializationFinished) {
1210
- drainRouterHtml();
1211
- if (cleanedUp || isDone()) return stream;
1212
- }
1213
- stopListeningToAbort = listenToAbort(opts?.signal, (reason) => {
1214
- safeError(reason);
1215
- cleanup(reason);
1216
- });
1217
- if (cleanedUp || isDone()) return stream;
1218
- (async () => {
1705
+ const wake = waitForWake();
1706
+ startAppRead();
1707
+ await wake;
1708
+ }
1709
+ async function pumpPassThrough() {
1219
1710
  try {
1220
- while (true) {
1221
- if (waitForBackpressure()) {
1222
- await waitForDrain();
1223
- if (cleanedUp || isDone()) return;
1711
+ for (; ; ) {
1712
+ if (appBytes) {
1713
+ const remainder = appOffset === 0 ? appBytes : appBytes.subarray(appOffset);
1714
+ appBytes = void 0;
1715
+ if (enqueueAppBytes(remainder)) return;
1716
+ continue;
1224
1717
  }
1225
- const { done, value } = await readerState.reader.read();
1226
- if (done) break;
1227
- if (cleanedUp || isDone()) return;
1228
- const text = typeof value === "string" ? value : textDecoder.decode(value, { stream: true });
1229
- const chunkString = leftover ? leftover + text : text;
1230
- if (state >= MergeState.HoldingTail) {
1231
- appendTail(chunkString);
1232
- leftover = "";
1718
+ if (appString !== void 0) {
1719
+ loadNextAppStringChunk();
1233
1720
  continue;
1234
1721
  }
1235
- const boundary = findHtmlBoundary(chunkString);
1236
- if (boundary < -1) {
1237
- const bodyEndIndex = -boundary - 2;
1238
- state = MergeState.HoldingTail;
1239
- appendTail(chunkString.slice(bodyEndIndex));
1240
- const bodyChunk = chunkString.slice(0, bodyEndIndex);
1241
- writeChunk(bodyChunk);
1242
- if (cleanedUp || isDone()) return;
1243
- noteBarrierMarker(bodyChunk);
1244
- liftBarrierAfterBoundary();
1245
- if (cleanedUp || isDone()) return;
1246
- flushPendingRouterHtml();
1247
- leftover = "";
1722
+ if (appDone) {
1723
+ terminate("complete");
1724
+ return;
1725
+ }
1726
+ if (appReadPending) {
1727
+ await waitForWake();
1248
1728
  continue;
1249
1729
  }
1250
- const lastClosingTagEnd = boundary;
1251
- if (lastClosingTagEnd > 0) {
1252
- const safeChunk = chunkString.slice(0, lastClosingTagEnd);
1253
- writeChunk(safeChunk);
1254
- if (cleanedUp || isDone()) return;
1255
- noteBarrierMarker(safeChunk);
1256
- liftBarrierAfterBoundary();
1257
- if (cleanedUp || isDone()) return;
1258
- flushPendingRouterHtml();
1259
- leftover = chunkString.slice(lastClosingTagEnd);
1260
- if (leftover.length > MAX_LEFTOVER_CHARS) {
1261
- noteBarrierMarker(leftover);
1262
- writeChunk(leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS));
1263
- leftover = leftover.slice(-2048);
1264
- }
1265
- } else {
1266
- const combined = chunkString;
1267
- if (combined.length > MAX_LEFTOVER_CHARS) {
1268
- noteBarrierMarker(combined);
1269
- const flushUpto = combined.length - MAX_LEFTOVER_CHARS;
1270
- writeChunk(combined.slice(0, flushUpto));
1271
- leftover = combined.slice(flushUpto);
1272
- } else leftover = combined;
1730
+ let result = settledAppRead;
1731
+ if (result) settledAppRead = void 0;
1732
+ else {
1733
+ result = await reader.read();
1734
+ if (terminal) return;
1735
+ }
1736
+ if (result.done || typeof result.value === "string") {
1737
+ acceptAppRead(result);
1738
+ continue;
1739
+ }
1740
+ if (result.value.byteLength > 0) {
1741
+ controller.enqueue(result.value);
1742
+ return;
1273
1743
  }
1274
1744
  }
1275
- if (cleanedUp || isDone()) return;
1276
- finishAppRendering();
1277
1745
  } catch (error) {
1278
- if (cleanedUp) return;
1279
- console.error("Error reading appStream:", error);
1280
- if (state < MergeState.AppDone) try {
1281
- serverSsr.setRenderFinished();
1282
- } catch {
1746
+ handlePumpError(error);
1747
+ }
1748
+ }
1749
+ async function pump() {
1750
+ const output = hydrationOutput;
1751
+ while (!terminal) {
1752
+ const hydrationState = output.state;
1753
+ if (hydrationState === HydrationScriptOutputState.Active) {
1754
+ controller.enqueue(output.pullChunk());
1755
+ return;
1283
1756
  }
1284
- safeError(error);
1285
- cleanup(error);
1286
- } finally {
1287
- readerState.release();
1757
+ if (applicationPhase !== ApplicationPhase.BeforeBoundary && insertionBoundary && hydrationState === HydrationScriptOutputState.Ready) {
1758
+ if (!appDone && !appBytes && appString === void 0) startAppRead();
1759
+ controller.enqueue(output.pullChunk());
1760
+ return;
1761
+ }
1762
+ if (applicationPhase === ApplicationPhase.Merge && hydrationState === HydrationScriptOutputState.Done && closeCarry === void 0 && hydrationScripts.reserveFastPath(output)) {
1763
+ applicationPhase = ApplicationPhase.PassThrough;
1764
+ stopHydrationOutputListener?.();
1765
+ stopHydrationOutputListener = void 0;
1766
+ return pumpPassThrough();
1767
+ }
1768
+ if (appBytes) {
1769
+ if (processAppChunk()) return;
1770
+ continue;
1771
+ }
1772
+ if (appDone) {
1773
+ if (applicationPhase === ApplicationPhase.BeforeBoundary) {
1774
+ hydrationScripts.skipInitialTake();
1775
+ applicationPhase = ApplicationPhase.Merge;
1776
+ insertionBoundary = true;
1777
+ continue;
1778
+ }
1779
+ if (closeCarry) {
1780
+ const carry = closeCarry;
1781
+ closeCarry = void 0;
1782
+ insertionBoundary = true;
1783
+ if (enqueueAppBytes(carry)) return;
1784
+ continue;
1785
+ }
1786
+ if (hydrationState === HydrationScriptOutputState.Waiting) {
1787
+ await waitForWake();
1788
+ continue;
1789
+ }
1790
+ if (applicationPhase === ApplicationPhase.HeldClose) {
1791
+ controller.enqueue(DOCUMENT_CLOSE_BYTES.slice());
1792
+ terminate("complete");
1793
+ return;
1794
+ }
1795
+ terminate("complete");
1796
+ return;
1797
+ }
1798
+ await loadNextAppChunk();
1799
+ }
1800
+ }
1801
+ function handlePumpError(error) {
1802
+ if (terminal) return;
1803
+ console.error("Error processing appStream:", error);
1804
+ terminate("failure", error);
1805
+ }
1806
+ const stream = new ReadableStream({
1807
+ start(c) {
1808
+ controller = c;
1809
+ },
1810
+ pull() {
1811
+ return applicationPhase === ApplicationPhase.PassThrough ? pumpPassThrough() : pump().catch(handlePumpError);
1812
+ },
1813
+ cancel(reason) {
1814
+ return terminate("cancel", reason);
1815
+ }
1816
+ });
1817
+ if (hydrationOutput) stopHydrationOutputListener = hydrationOutput.subscribe(() => {
1818
+ if (hydrationOutput.state === HydrationScriptOutputState.Failed) {
1819
+ terminate("failure", hydrationOutput.error);
1820
+ return;
1288
1821
  }
1289
- })().catch((error) => {
1290
- if (cleanedUp) return;
1291
- console.error("Error in stream transform:", error);
1292
- safeError(error);
1293
- cleanup(error);
1822
+ wakePump();
1294
1823
  });
1824
+ disarmLifecycle = armStreamLifecycle(serverSsr, opts, () => terminal, terminate);
1295
1825
  return stream;
1296
1826
  }
1297
1827
 
1298
- // node_modules/.pnpm/@tanstack+react-router@1.170.32_react-dom@19.3.0_react@19.3.0__react@19.3.0/node_modules/@tanstack/react-router/dist/esm/ssr/renderRouterToStream.js
1828
+ // node_modules/.pnpm/@tanstack+react-router@1.170.40_react-dom@19.3.0_react@19.3.0__react@19.3.0/node_modules/@tanstack/react-router/dist/esm/ssr/renderRouterToStream.js
1299
1829
  import ReactDOMServer from "react-dom/server";
1300
- import { PassThrough } from "node:stream";
1830
+ import { PassThrough, Readable } from "node:stream";
1301
1831
 
1302
1832
  // node_modules/.pnpm/isbot@5.2.1/node_modules/isbot/index.mjs
1303
1833
  var fullPattern = " daum[ /]| deusu/|(?:^|[^g])news(?!sapphire)|(?<! channel/|google/)google(?!(?:wv|app|/google| pixel))|(?<! cu)bots?(?:\\b|_)|(?<!cam)scan|(?<!lib)http|24x7|;\\s\\w+;$|@[a-z][\\w-]+\\.|\\(\\)|\\.com\\b|\\b\\w+\\.ai|\\bbw/|\\bdlc\\b|\\bort/|\\bperl\\b|\\btime/|\\||^[<\\(;]|^[\\w \\.\\-\\(?:\\):%]+(?:/v?\\d+(?:\\.\\d+)?(?:\\.\\d{1,10})*?)?(?:,|$)|^[\\w\\-]+/[\\w]+$|^[^ ]{50,}$|^\\d+\\b|^\\w*search\\b|^\\w+/[\\w\\(\\)]*$|^\\w+/\\d\\.\\d\\s\\([\\w@]+\\)$|^active|^ad muncher|^amaya|^apache/|^avsdevicesdk/|^azure|^biglotron|^blackbox exporter|^bot|^clamav[ /]|^claude-code/|^client/|^cobweb/|^custom|^ddg[_-]android|^discourse|^dispatch/\\d|^downcast/|^duckduckgo|^email|^exodusmovement|^facebook|^getright/|^gozilla/|^hobbit|^hotzonu|^hwcdn/|^igetter/|^jeode/|^jetty/|^jigsaw|^microsoft bits|^movabletype|^mozilla/\\d\\.\\d\\s[\\w\\.-]+$|^mozilla/\\d\\.\\d\\s\\((?:compatible;)?(?:\\s?[\\w\\d-.]+\\/\\d+\\.\\d+)?\\)$|^navermailapp|^netsurf|^offline|^openai/|^owler|^php|^postman|^ps_daily/|^python|^rank|^read|^reed|^remove\\.bg/|^rest|^rss|^snapchat|^sora |^space bison|^stape/|^svn|^swcd |^taringa|^thumbor/|^track|^w3c|^webbandit/|^webcopier|^wget|^whatsapp|^wordpress|^xenu link sleuth|^yahoo|^yandex|^zdm/\\d|^zoom marketplace/|abuse|advisor|agent\\b|analyzer|archive|ask jeeves/teoma|attracta|audit|bluecoat drtr|browsex|burpcollaborator|capture|catch|check\\b|checker|chrome-lighthouse|chromeframe|classifier|cloudflare|collapsify\\b|convertify|cookiehubverify/|crawl|cursor/|cypress/|dareboost|datanyze|dejaclick|detect|discovery|dmbrowser|download|exaleadcloudview|feed|fetcher|firephp|foregenix|functionize|grab|hardenize\\b|headless|hotjar|httrack|hubspot marketing grader|ibisbrowser|infrawatch|insight|inspect|iplabel|java(?!;)|library|linkcheck|linktiger|mail\\.ru/|manager|manus-user/|marketgoo/|measure|monitor\\b|neustar wpm|node\\b|nutch|offbyone|openvas|optimize|pageburst|pagespeed|parser|phantomjs|pingdom|playwright|powermarks|preview|productfinder|prospectingstudio|proxy|ptst[ /]\\d|radar|readable/|retriever|rexx;|rigor|rss\\b|scrape|securityheaders|selenium|server|silktide|sindup/|sogou|sparkler/|speedcurve|spider|splash|statuscake|supercleaner|synapse|synthetic|testlocally|tools|torrent|transcoder|upday/|url|validator|virtuoso|wappalyzer|watchtowr|webglance|webkit2png|whatcms/|xtate/";
@@ -1320,113 +1850,87 @@ function isBot(userAgent) {
1320
1850
  }
1321
1851
  var isbot = isBot;
1322
1852
 
1323
- // node_modules/.pnpm/@tanstack+react-router@1.170.32_react-dom@19.3.0_react@19.3.0__react@19.3.0/node_modules/@tanstack/react-router/dist/esm/ssr/renderRouterToStream.js
1324
- var noop2 = () => {
1325
- };
1326
- async function waitForReadyOrAbort(ready, signal) {
1327
- let cleanup = noop2;
1328
- try {
1329
- await Promise.race([ready, new Promise((resolve) => {
1330
- const onAbort = () => resolve();
1331
- cleanup = () => signal.removeEventListener("abort", onAbort);
1332
- signal.addEventListener("abort", onAbort, { once: true });
1333
- if (signal.aborted) resolve();
1334
- })]);
1335
- } finally {
1336
- cleanup();
1337
- }
1338
- }
1339
- var isAbortError = (request, error) => request.signal.aborted && error === request.signal.reason || error instanceof Error && error.name === "AbortError";
1853
+ // node_modules/.pnpm/@tanstack+react-router@1.170.40_react-dom@19.3.0_react@19.3.0__react@19.3.0/node_modules/@tanstack/react-router/dist/esm/ssr/renderRouterToStream.js
1340
1854
  var renderRouterToStream = async ({ request, router, responseHeaders, children }) => {
1341
- if (typeof ReactDOMServer.renderToReadableStream === "function") {
1342
- const stream = await ReactDOMServer.renderToReadableStream(children, {
1343
- signal: request.signal,
1344
- nonce: router.options.ssr?.nonce,
1345
- progressiveChunkSize: Number.POSITIVE_INFINITY,
1346
- onError: (error, info) => {
1347
- if (!isAbortError(request, error)) console.error("Error in renderToReadableStream:", error, info);
1348
- }
1349
- });
1350
- if (isbot(request.headers.get("User-Agent"))) await waitForReadyOrAbort(stream.allReady, request.signal);
1351
- const responseStream = transformReadableStreamWithRouter(router, stream, {
1352
- signal: request.signal,
1353
- onAbort: () => stream.cancel().catch(() => {
1354
- })
1355
- });
1356
- return createSsrStreamResponse(router, new Response(responseStream, {
1357
- status: router._serverResult?.type === "render" ? router._serverResult.status : 200,
1358
- headers: responseHeaders
1359
- }));
1855
+ const signal = request.signal;
1856
+ if (signal.aborted) {
1857
+ router.serverSsr?.cleanup();
1858
+ throw signal.reason;
1360
1859
  }
1361
- if (typeof ReactDOMServer.renderToPipeableStream === "function") {
1362
- const reactAppPassthrough = new PassThrough();
1363
- let pipeable;
1364
- let responseAttached = false;
1365
- let aborted = false;
1366
- let endedBeforeAttach = false;
1367
- let pendingAbortReason;
1368
- const toError = (reason) => reason instanceof Error ? reason : new Error(String(reason ?? "SSR aborted"));
1369
- const destroyError = (reason) => reason === void 0 ? void 0 : toError(reason);
1370
- const pendingDestroyError = () => pendingAbortReason === void 0 ? toError(pendingAbortReason) : destroyError(pendingAbortReason);
1371
- const finishPassThrough = (reason, opts) => {
1372
- if (reactAppPassthrough.destroyed) return;
1373
- if (responseAttached) reactAppPassthrough.destroy(opts?.defaultError ? toError(reason) : destroyError(reason));
1374
- else endedBeforeAttach = true;
1375
- };
1376
- const abortPipeable = (reason, opts) => {
1377
- if (aborted) return;
1378
- aborted = true;
1379
- pendingAbortReason = reason;
1380
- const err = toError(reason);
1381
- try {
1382
- pipeable?.abort(err);
1383
- } catch {
1384
- }
1385
- finishPassThrough(reason, opts);
1386
- };
1387
- if (request.signal.aborted) abortPipeable(request.signal.reason);
1388
- else {
1389
- const onRequestAbort = () => abortPipeable(request.signal.reason);
1390
- request.signal.addEventListener("abort", onRequestAbort, { once: true });
1391
- router.serverSsr?.onCleanup(() => {
1392
- request.signal.removeEventListener("abort", onRequestAbort);
1393
- });
1394
- }
1395
- try {
1396
- pipeable = ReactDOMServer.renderToPipeableStream(children, {
1860
+ let rendererTeardown = false;
1861
+ const bot = isbot(request.headers.get("User-Agent"));
1862
+ const onError2 = (renderer) => (error, info) => {
1863
+ if (!rendererTeardown && !signal.aborted) console.error(`Error in ${renderer}:`, error, info);
1864
+ };
1865
+ try {
1866
+ if (typeof ReactDOMServer.renderToReadableStream === "function") {
1867
+ const stream = await ReactDOMServer.renderToReadableStream(children, {
1868
+ signal,
1397
1869
  nonce: router.options.ssr?.nonce,
1398
1870
  progressiveChunkSize: Number.POSITIVE_INFINITY,
1399
- ...isbot(request.headers.get("User-Agent")) ? { onAllReady() {
1400
- pipeable.pipe(reactAppPassthrough);
1401
- } } : { onShellReady() {
1402
- pipeable.pipe(reactAppPassthrough);
1403
- } },
1404
- onError: (error, info) => {
1405
- if (!isAbortError(request, error)) console.error("Error in renderToPipeableStream:", error, info);
1406
- abortPipeable(error, { defaultError: true });
1871
+ onError: onError2("renderToReadableStream")
1872
+ });
1873
+ const rendererAbort = bot ? new AbortController() : void 0;
1874
+ const responseStream = transformReadableStreamWithRouter(router, stream, {
1875
+ rendererSafePoint: "script-close",
1876
+ signal,
1877
+ onAbort: (reason) => {
1878
+ rendererTeardown = true;
1879
+ rendererAbort?.abort(reason);
1407
1880
  }
1408
1881
  });
1409
- } catch (e) {
1410
- console.error("Error in renderToPipeableStream:", e);
1411
- router.serverSsr?.cleanup();
1412
- throw e;
1882
+ if (rendererAbort) await waitForReason(stream.allReady, rendererAbort.signal);
1883
+ return createSsrStreamResponse(router, new Response(responseStream, {
1884
+ status: getSsrStatus(router),
1885
+ headers: responseHeaders
1886
+ }));
1413
1887
  }
1414
- const responseStream = transformPipeableStreamWithRouter(router, reactAppPassthrough, {
1415
- signal: request.signal,
1416
- onAbort: abortPipeable
1417
- });
1418
- responseAttached = true;
1419
- if (endedBeforeAttach) reactAppPassthrough.destroy(pendingDestroyError());
1420
- if (aborted && pipeable) try {
1421
- pipeable.abort(toError(pendingAbortReason));
1422
- } catch {
1888
+ if (typeof ReactDOMServer.renderToPipeableStream === "function") {
1889
+ const reactAppPassthrough = new PassThrough();
1890
+ let pipeable;
1891
+ let resolveReady;
1892
+ const ready = new Promise((resolve) => {
1893
+ resolveReady = resolve;
1894
+ });
1895
+ const rendererAbort = new AbortController();
1896
+ const abortPipeable = (reason) => {
1897
+ if (rendererTeardown) return;
1898
+ rendererTeardown = true;
1899
+ rendererAbort.abort(reason);
1900
+ try {
1901
+ pipeable?.abort(reason);
1902
+ } catch {
1903
+ }
1904
+ };
1905
+ try {
1906
+ pipeable = ReactDOMServer.renderToPipeableStream(children, {
1907
+ nonce: router.options.ssr?.nonce,
1908
+ progressiveChunkSize: Number.POSITIVE_INFINITY,
1909
+ ...bot ? { onAllReady: resolveReady } : { onShellReady: resolveReady },
1910
+ onError: onError2("renderToPipeableStream"),
1911
+ onShellError: (error) => rendererAbort.abort(error)
1912
+ });
1913
+ const responseStream = transformReadableStreamWithRouter(router, Readable.toWeb(reactAppPassthrough), {
1914
+ rendererSafePoint: "script-close",
1915
+ signal,
1916
+ onAbort: abortPipeable
1917
+ });
1918
+ await waitForReason(ready, rendererAbort.signal);
1919
+ pipeable.pipe(reactAppPassthrough);
1920
+ return createSsrStreamResponse(router, new Response(responseStream, {
1921
+ status: getSsrStatus(router),
1922
+ headers: responseHeaders
1923
+ }));
1924
+ } catch (error) {
1925
+ abortPipeable(error);
1926
+ throw error;
1927
+ }
1423
1928
  }
1424
- return createSsrStreamResponse(router, new Response(responseStream, {
1425
- status: router._serverResult?.type === "render" ? router._serverResult.status : 200,
1426
- headers: responseHeaders
1427
- }));
1929
+ throw new Error("No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.");
1930
+ } catch (error) {
1931
+ router.serverSsr?.cleanup();
1932
+ throw error;
1428
1933
  }
1429
- throw new Error("No renderToReadableStream or renderToPipeableStream found in react-dom/server. Ensure you are using a version of react-dom that supports streaming.");
1430
1934
  };
1431
1935
 
1432
1936
  // web/app/dist/server/server.js
@@ -2024,7 +2528,7 @@ function getResponse() {
2024
2528
  }
2025
2529
  var HEADERS = { TSS_SHELL: "X-TSS_SHELL" };
2026
2530
  async function getStartManifest(matchedRoutes) {
2027
- const { tsrStartManifest } = await import("./_tanstack-start-manifest_v-vL58CVrY-7SDCWIHD.js");
2531
+ const { tsrStartManifest } = await import("./_tanstack-start-manifest_v-CaT-3S-N-VAOGUHEJ.js");
2028
2532
  const startManifest = tsrStartManifest();
2029
2533
  let routes = startManifest.routes;
2030
2534
  routes[rootRouteId];
@@ -2044,50 +2548,23 @@ async function getStartManifest(matchedRoutes) {
2044
2548
  };
2045
2549
  }
2046
2550
  var manifest = {};
2047
- async function getServerFnById(id, access) {
2048
- const serverFnInfo = manifest[id];
2049
- if (!serverFnInfo) throw new Error("Server function info not found for " + id);
2050
- const fnModule = serverFnInfo.module ?? await serverFnInfo.importer();
2051
- if (!fnModule) throw new Error("Server function module not resolved for " + id);
2052
- const action = fnModule[serverFnInfo.functionName];
2053
- if (!action) throw new Error("Server function module export not resolved for serverFn ID: " + id);
2054
- return action;
2055
- }
2056
- var TSS_FORMDATA_CONTEXT = "__TSS_CONTEXT";
2057
- var TSS_SERVER_FUNCTION = /* @__PURE__ */ Symbol.for("TSS_SERVER_FUNCTION");
2058
- var X_TSS_SERIALIZED = "x-tss-serialized";
2059
- var X_TSS_RAW_RESPONSE = "x-tss-raw";
2060
- var TSS_CONTENT_TYPE_FRAMED = "application/x-tss-framed";
2061
- var FrameType = {
2062
- /** Seroval JSON chunk (NDJSON line) */
2063
- JSON: 0,
2064
- /** Raw stream data chunk */
2065
- CHUNK: 1,
2066
- /** Raw stream end (EOF) */
2067
- END: 2,
2068
- /** Raw stream error */
2069
- ERROR: 3
2070
- };
2071
- var TSS_CONTENT_TYPE_FRAMED_VERSIONED = `${TSS_CONTENT_TYPE_FRAMED}; v=1`;
2072
- function isSafeKey(key) {
2073
- return key !== "__proto__" && key !== "constructor" && key !== "prototype";
2074
- }
2075
- function safeObjectMerge(target, source) {
2076
- const result = /* @__PURE__ */ Object.create(null);
2077
- if (target) {
2078
- for (const key of Object.keys(target)) if (isSafeKey(key)) result[key] = target[key];
2079
- }
2080
- if (source && typeof source === "object") {
2081
- for (const key of Object.keys(source)) if (isSafeKey(key)) result[key] = source[key];
2082
- }
2083
- return result;
2084
- }
2085
- function createNullProtoObject(source) {
2086
- if (!source) return /* @__PURE__ */ Object.create(null);
2087
- const obj = /* @__PURE__ */ Object.create(null);
2088
- for (const key of Object.keys(source)) if (isSafeKey(key)) obj[key] = source[key];
2089
- return obj;
2551
+ async function getServerFnById(id, access) {
2552
+ const serverFnInfo = manifest[id];
2553
+ if (!serverFnInfo) throw new Error("Server function info not found for " + id);
2554
+ const fnModule = serverFnInfo.module ??= await serverFnInfo.importer();
2555
+ if (!fnModule) throw new Error("Server function module not resolved for " + id);
2556
+ const action = fnModule[serverFnInfo.functionName];
2557
+ if (!action) throw new Error("Server function module export not resolved for serverFn ID: " + id);
2558
+ return action;
2090
2559
  }
2560
+ var TSS_FORMDATA_CONTEXT = "__TSS_CONTEXT";
2561
+ var TSS_SERVER_FUNCTION = /* @__PURE__ */ Symbol.for("TSS_SERVER_FUNCTION");
2562
+ var X_TSS_SERIALIZED = "x-tss-serialized";
2563
+ var X_TSS_RAW_RESPONSE = "x-tss-raw";
2564
+ var TSS_CONTENT_TYPE_FRAMED = "application/x-tss-framed";
2565
+ var MAX_FRAME_PAYLOAD_SIZE = 16777216;
2566
+ var MAX_FRAMED_STREAMS = 1024;
2567
+ var TSS_CONTENT_TYPE_FRAMED_VERSIONED = `${TSS_CONTENT_TYPE_FRAMED}; v=1`;
2091
2568
  var GLOBAL_STORAGE_KEY = /* @__PURE__ */ Symbol.for("tanstack-start:start-storage-context");
2092
2569
  var globalObj = globalThis;
2093
2570
  if (!globalObj[GLOBAL_STORAGE_KEY]) globalObj[GLOBAL_STORAGE_KEY] = new AsyncLocalStorage();
@@ -2101,103 +2578,8 @@ function getStartContext(opts) {
2101
2578
  return context;
2102
2579
  }
2103
2580
  var getStartOptions = () => getStartContext().startOptions;
2104
- function flattenMiddlewares(middlewares, maxDepth = 100) {
2105
- const seen = /* @__PURE__ */ new Set();
2106
- const flattened = [];
2107
- const recurse = (middleware, depth) => {
2108
- if (depth > maxDepth) throw new Error(`Middleware nesting depth exceeded maximum of ${maxDepth}. Check for circular references.`);
2109
- middleware.forEach((m) => {
2110
- if (m.options.middleware) recurse(m.options.middleware, depth + 1);
2111
- if (!seen.has(m)) {
2112
- seen.add(m);
2113
- flattened.push(m);
2114
- }
2115
- });
2116
- };
2117
- recurse(middlewares, 0);
2118
- return flattened;
2119
- }
2120
- var createMiddleware = (options, __opts) => {
2121
- const resolvedOptions = {
2122
- type: "request",
2123
- ...__opts || options
2124
- };
2125
- const setValidator = (validator) => {
2126
- return createMiddleware({}, Object.assign(resolvedOptions, {
2127
- validator,
2128
- inputValidator: validator
2129
- }));
2130
- };
2131
- return {
2132
- options: resolvedOptions,
2133
- middleware: (middleware) => {
2134
- return createMiddleware({}, Object.assign(resolvedOptions, { middleware }));
2135
- },
2136
- validator: setValidator,
2137
- inputValidator: setValidator,
2138
- client: (client) => {
2139
- return createMiddleware({}, Object.assign(resolvedOptions, { client }));
2140
- },
2141
- server: (server) => {
2142
- return createMiddleware({}, Object.assign(resolvedOptions, { server }));
2143
- }
2144
- };
2145
- };
2146
- var innerCreateCsrfMiddleware = (opts = {}) => {
2147
- return createMiddleware().server(async (ctx) => {
2148
- const csrfCtx = ctx;
2149
- if (opts.filter && !await opts.filter(csrfCtx)) return ctx.next();
2150
- if (await isCsrfRequestAllowed(opts, csrfCtx)) return ctx.next();
2151
- return getFailureResponse(opts, csrfCtx);
2152
- });
2153
- };
2154
- var createCsrfMiddleware = innerCreateCsrfMiddleware;
2155
- async function isCsrfRequestAllowed(opts, ctx) {
2156
- const result = await getCsrfRequestValidationResult(opts, ctx);
2157
- return result === true || result === void 0 && opts.allowRequestsWithoutOriginCheck === true;
2158
- }
2159
- async function getCsrfRequestValidationResult(opts, ctx) {
2160
- const fetchSite = ctx.request.headers.get("Sec-Fetch-Site");
2161
- if (fetchSite !== null) return matchValue(opts.secFetchSite ?? "same-origin", fetchSite, ctx);
2162
- const origin = ctx.request.headers.get("Origin");
2163
- if (origin !== null) {
2164
- if (opts.origin) return matchValue(opts.origin, origin, ctx);
2165
- return origin === new URL(ctx.request.url).origin;
2166
- }
2167
- const referer = ctx.request.headers.get("Referer");
2168
- if (referer === null || opts.referer === false) return;
2169
- if (typeof opts.referer === "function") return opts.referer(referer, ctx);
2170
- if (opts.origin) {
2171
- const refererOrigin = getOriginFromUrl(referer);
2172
- return refererOrigin !== void 0 && matchValue(opts.origin, refererOrigin, ctx);
2173
- }
2174
- return isRefererSameOrigin(referer, new URL(ctx.request.url).origin);
2175
- }
2176
- async function matchValue(matcher, value, ctx) {
2177
- if (typeof matcher === "function") return matcher(value, ctx);
2178
- if (Array.isArray(matcher)) return matcher.includes(value);
2179
- return value === matcher;
2180
- }
2181
- function getOriginFromUrl(url) {
2182
- try {
2183
- return new URL(url).origin;
2184
- } catch {
2185
- return;
2186
- }
2187
- }
2188
- function isRefererSameOrigin(referer, requestOrigin) {
2189
- if (referer === requestOrigin) return true;
2190
- if (!referer.startsWith(requestOrigin)) return false;
2191
- if (referer.length === requestOrigin.length) return true;
2192
- const code = referer.charCodeAt(requestOrigin.length);
2193
- return code === 47 || code === 63 || code === 35;
2194
- }
2195
- async function getFailureResponse(opts, ctx) {
2196
- if (typeof opts.failureResponse === "function") return opts.failureResponse(ctx);
2197
- return opts.failureResponse?.clone() ?? new Response("Forbidden", { status: 403 });
2198
- }
2199
- function getDefaultSerovalPlugins() {
2200
- return [...getStartOptions()?.serializationAdapters?.map(makeSerovalPlugin) ?? [], ...defaultSerovalPlugins];
2581
+ function getSerovalPlugins(routerPlugins) {
2582
+ return [...getStartOptions()?.serializationAdapters?.map(makeSerovalPlugin) ?? [], ...routerPlugins];
2201
2583
  }
2202
2584
  var SYM_ASYNC_ITERATOR = Symbol.asyncIterator;
2203
2585
  var SYM_HAS_INSTANCE = Symbol.hasInstance;
@@ -2297,6 +2679,8 @@ var NEG_ZERO_NODE = /* @__PURE__ */ createConstantNode(4);
2297
2679
  var INFINITY_NODE = /* @__PURE__ */ createConstantNode(5);
2298
2680
  var NEG_INFINITY_NODE = /* @__PURE__ */ createConstantNode(6);
2299
2681
  var NAN_NODE = /* @__PURE__ */ createConstantNode(7);
2682
+ var MIN_JSON_STRINGIFY_LENGTH = 64;
2683
+ var JSON_ESCAPE_DIFFERENCES = /[\x00-\x07\x0b\x0e-\x1f<\u2028\u2029\ud800-\udfff]/;
2300
2684
  function serializeChar(str) {
2301
2685
  switch (str) {
2302
2686
  case '"':
@@ -2324,6 +2708,7 @@ function serializeChar(str) {
2324
2708
  }
2325
2709
  }
2326
2710
  function serializeString(str) {
2711
+ if (str.length >= MIN_JSON_STRINGIFY_LENGTH && !JSON_ESCAPE_DIFFERENCES.test(str)) return JSON.stringify(str).slice(1, -1);
2327
2712
  let result = "";
2328
2713
  let lastPos = 0;
2329
2714
  let replacement;
@@ -2365,6 +2750,7 @@ function deserializeReplacer(str) {
2365
2750
  }
2366
2751
  }
2367
2752
  function deserializeString(str) {
2753
+ if (typeof str === "string" && !str.includes("\\")) return str;
2368
2754
  return str.replace(/(\\\\|\\"|\\n|\\r|\\b|\\t|\\f|\\u2028|\\u2029|\\x3C)/g, deserializeReplacer);
2369
2755
  }
2370
2756
  var { toString: objectToString } = Object.prototype;
@@ -2638,7 +3024,10 @@ var STREAM_CONSTRUCTOR = () => {
2638
3024
  let count = 0;
2639
3025
  const internal = {
2640
3026
  flush(value, mode, x) {
2641
- for (x = 0; x < count; x++) if (listeners[x]) listeners[x][mode](value);
3027
+ for (x = 0; x < count; x++) {
3028
+ const listener = listeners[x];
3029
+ if (listener) listener[mode](value);
3030
+ }
2642
3031
  },
2643
3032
  up(listener, x, z, current) {
2644
3033
  for (x = 0, z = buffer.length; x < z; x++) {
@@ -2647,16 +3036,20 @@ var STREAM_CONSTRUCTOR = () => {
2647
3036
  else listener.next(current);
2648
3037
  }
2649
3038
  },
2650
- on(listener, temp) {
3039
+ on(listener, temp = 0) {
3040
+ let subscribed = alive;
2651
3041
  if (alive) {
2652
- temp = count++;
3042
+ for (temp = 0; temp < count; temp++) if (!listeners[temp]) break;
3043
+ if (temp === count) count++;
2653
3044
  listeners[temp] = listener;
2654
3045
  }
2655
3046
  internal.up(listener);
2656
3047
  return () => {
2657
- if (alive) {
2658
- listeners[temp] = listeners[count];
2659
- listeners[count--] = void 0;
3048
+ if (alive && subscribed) {
3049
+ subscribed = false;
3050
+ listeners[temp] = void 0;
3051
+ while (count > 0 && !listeners[count - 1]) count--;
3052
+ listeners.length = count;
2660
3053
  }
2661
3054
  };
2662
3055
  }
@@ -2840,25 +3233,42 @@ var SPECIAL_REFS = {
2840
3233
  [4]: {},
2841
3234
  [5]: {}
2842
3235
  };
2843
- function isStream(value) {
3236
+ function isStream2(value) {
2844
3237
  return "__SEROVAL_STREAM__" in value;
2845
3238
  }
2846
- function createStream() {
3239
+ function createStream2() {
2847
3240
  return STREAM_CONSTRUCTOR();
2848
3241
  }
2849
- function createStreamFromAsyncIterable(iterable) {
2850
- const stream = createStream();
3242
+ function createStreamFromAsyncIterable(iterable, cleanups) {
3243
+ const stream = createStream2();
2851
3244
  const iterator = iterable[SYM_ASYNC_ITERATOR]();
3245
+ let cancelled = false;
3246
+ let done = false;
3247
+ cleanups === null || cleanups === void 0 || cleanups.push(() => {
3248
+ if (!(done || cancelled)) {
3249
+ cancelled = true;
3250
+ Promise.resolve().then(() => {
3251
+ var _iterator$return;
3252
+ return (_iterator$return = iterator.return) === null || _iterator$return === void 0 ? void 0 : _iterator$return.call(iterator);
3253
+ }).catch(() => {
3254
+ });
3255
+ }
3256
+ });
2852
3257
  async function push() {
2853
3258
  try {
2854
- const value = await iterator.next();
2855
- if (value.done) stream.return(value.value);
2856
- else {
3259
+ while (!cancelled) {
3260
+ const value = await iterator.next();
3261
+ if (cancelled) return;
3262
+ if (value.done) {
3263
+ done = true;
3264
+ stream.return(value.value);
3265
+ break;
3266
+ }
2857
3267
  stream.next(value.value);
2858
- await push();
2859
3268
  }
2860
3269
  } catch (error) {
2861
- stream.throw(error);
3270
+ done = true;
3271
+ if (!cancelled) stream.throw(error);
2862
3272
  }
2863
3273
  }
2864
3274
  push().catch(() => {
@@ -2877,13 +3287,15 @@ async function promiseToResult(current) {
2877
3287
  }
2878
3288
  }
2879
3289
  function createBaseParserContext(mode, options) {
3290
+ var _options$compactArray;
2880
3291
  return {
2881
3292
  plugins: options.plugins,
2882
3293
  mode,
2883
3294
  marked: /* @__PURE__ */ new Set(),
2884
3295
  features: 127 ^ (options.disabledFeatures || 0),
2885
3296
  refs: options.refs || /* @__PURE__ */ new Map(),
2886
- depthLimit: options.depthLimit || 1e3
3297
+ depthLimit: options.depthLimit || 1e3,
3298
+ compactArrayBufferViews: (_options$compactArray = options.compactArrayBufferViews) !== null && _options$compactArray !== void 0 ? _options$compactArray : false
2887
3299
  };
2888
3300
  }
2889
3301
  function markParserRef(ctx, id) {
@@ -2950,11 +3362,22 @@ function createMapNode(ctx, id, k, v) {
2950
3362
  function createPromiseConstructorNode(ctx, id, resolver) {
2951
3363
  return createSerovalNode(22, id, resolver, void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 1), void 0, void 0, void 0);
2952
3364
  }
2953
- function createArrayBufferNode(ctx, id, current) {
3365
+ function getArrayBufferView(ctx, current) {
3366
+ if (!ctx.compactArrayBufferViews) return current;
3367
+ const buffer = new Uint8Array(current.buffer, current.byteOffset, current.byteLength).slice().buffer;
3368
+ const Constructor = current.constructor;
3369
+ return new Constructor(buffer);
3370
+ }
3371
+ function encodeArrayBuffer(current) {
3372
+ if (typeof Buffer !== "undefined") return Buffer.from(current).toString("base64");
2954
3373
  const bytes = new Uint8Array(current);
3374
+ if (typeof bytes.toBase64 === "function") return bytes.toBase64();
2955
3375
  let result = "";
2956
3376
  for (let i = 0, len = bytes.length; i < len; i++) result += String.fromCharCode(bytes[i]);
2957
- return createSerovalNode(19, id, serializeString(btoa(result)), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5), void 0, void 0, void 0);
3377
+ return btoa(result);
3378
+ }
3379
+ function createArrayBufferNode(ctx, id, current) {
3380
+ return createSerovalNode(19, id, encodeArrayBuffer(current), void 0, void 0, void 0, void 0, void 0, parseSpecialReference(ctx, 5), void 0, void 0, void 0);
2958
3381
  }
2959
3382
  function createAsyncParserContext(mode, options) {
2960
3383
  return {
@@ -3016,12 +3439,15 @@ async function parseBoxed$1(ctx, depth, id, current) {
3016
3439
  return createBoxedNode(id, await parseAsync(ctx, depth, current.valueOf()));
3017
3440
  }
3018
3441
  async function parseTypedArray$1(ctx, depth, id, current) {
3442
+ current = getArrayBufferView(ctx.base, current);
3019
3443
  return createTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3020
3444
  }
3021
3445
  async function parseBigIntTypedArray$1(ctx, depth, id, current) {
3446
+ current = getArrayBufferView(ctx.base, current);
3022
3447
  return createBigIntTypedArrayNode(id, current, await parseAsync(ctx, depth, current.buffer));
3023
3448
  }
3024
3449
  async function parseDataView$1(ctx, depth, id, current) {
3450
+ current = getArrayBufferView(ctx.base, current);
3025
3451
  return createDataViewNode(id, current, await parseAsync(ctx, depth, current.buffer));
3026
3452
  }
3027
3453
  async function parseError$1(ctx, depth, id, current) {
@@ -3103,7 +3529,7 @@ async function parseSequence$1(ctx, depth, id, current) {
3103
3529
  }
3104
3530
  async function parseObjectAsync(ctx, depth, id, current) {
3105
3531
  if (Array.isArray(current)) return parseArray$1(ctx, depth, id, current);
3106
- if (isStream(current)) return parseStream$1(ctx, depth, id, current);
3532
+ if (isStream2(current)) return parseStream$1(ctx, depth, id, current);
3107
3533
  if (isSequence(current)) return parseSequence$1(ctx, depth, id, current);
3108
3534
  let currentClass = current.constructor;
3109
3535
  if (currentClass !== void 0 && typeof currentClass !== "function") {
@@ -3293,7 +3719,8 @@ function isValidSymbol(symbol) {
3293
3719
  return false;
3294
3720
  }
3295
3721
  }
3296
- var MAX_BASE64_LENGTH = 1e6;
3722
+ var DEFAULT_MAX_BASE64_LENGTH = 1e6;
3723
+ var MIN_NATIVE_BASE64_LENGTH = 512;
3297
3724
  var MAX_BIGINT_LENGTH = 1e4;
3298
3725
  var MAX_REGEXP_SOURCE_LENGTH = 2e4;
3299
3726
  function applyObjectFlag(obj, flag) {
@@ -3310,7 +3737,9 @@ function applyObjectFlag(obj, flag) {
3310
3737
  }
3311
3738
  var DEFAULT_DEPTH_LIMIT = 1e3;
3312
3739
  function createBaseDeserializerContext(mode, options) {
3313
- var _options$features;
3740
+ var _options$maxBase64Len, _options$features;
3741
+ const maxBase64Length = (_options$maxBase64Len = options.maxBase64Length) !== null && _options$maxBase64Len !== void 0 ? _options$maxBase64Len : DEFAULT_MAX_BASE64_LENGTH;
3742
+ if (!Number.isSafeInteger(maxBase64Length) || maxBase64Length < 0) throw new RangeError("maxBase64Length must be a non-negative safe integer");
3314
3743
  const refs = options.refs || /* @__PURE__ */ new Map();
3315
3744
  if (!("types" in refs)) Object.assign(refs, { types: /* @__PURE__ */ new Map() });
3316
3745
  return {
@@ -3318,7 +3747,8 @@ function createBaseDeserializerContext(mode, options) {
3318
3747
  plugins: options.plugins,
3319
3748
  refs,
3320
3749
  features: (_options$features = options.features) !== null && _options$features !== void 0 ? _options$features : 127 ^ (options.disabledFeatures || 0),
3321
- depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT
3750
+ depthLimit: options.depthLimit || DEFAULT_DEPTH_LIMIT,
3751
+ maxBase64Length
3322
3752
  };
3323
3753
  }
3324
3754
  function createVanillaDeserializerContext(options) {
@@ -3476,22 +3906,33 @@ function deserializeMap(ctx, depth, node) {
3476
3906
  return result;
3477
3907
  }
3478
3908
  function deserializeArrayBuffer(ctx, node) {
3479
- if (node.s.length > MAX_BASE64_LENGTH) throw new SerovalMalformedNodeError(node);
3480
- return assignIndexedValue$1(ctx, node.i, ARRAY_BUFFER_CONSTRUCTOR(deserializeString(node.s)));
3909
+ if (typeof node.s !== "string") throw new SerovalMalformedNodeError(node);
3910
+ if (node.s.length > ctx.base.maxBase64Length) throw new RangeError("ArrayBuffer exceeds maxBase64Length (" + ctx.base.maxBase64Length + ")");
3911
+ const source = deserializeString(node.s);
3912
+ let buffer;
3913
+ if (source.length < MIN_NATIVE_BASE64_LENGTH || typeof Buffer === "undefined") buffer = ARRAY_BUFFER_CONSTRUCTOR(source);
3914
+ else {
3915
+ const decoded = atob(source);
3916
+ buffer = new ArrayBuffer(decoded.length);
3917
+ Buffer.from(buffer).write(decoded, "latin1");
3918
+ }
3919
+ return assignIndexedValue$1(ctx, node.i, buffer);
3481
3920
  }
3482
3921
  function deserializeTypedArray(ctx, depth, node) {
3483
3922
  var _node$b;
3484
3923
  const construct = getTypedArrayConstructor(node.c);
3485
3924
  const source = deserialize$1(ctx, depth, node.f);
3925
+ if (!(source instanceof ArrayBuffer)) throw new SerovalMalformedNodeError(node);
3486
3926
  const offset = (_node$b = node.b) !== null && _node$b !== void 0 ? _node$b : 0;
3487
- if (offset < 0 || offset > source.byteLength || node.l > MAX_BASE64_LENGTH) throw new SerovalMalformedNodeError(node);
3927
+ if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
3488
3928
  return assignIndexedValue$1(ctx, node.i, new construct(source, offset, node.l));
3489
3929
  }
3490
3930
  function deserializeDataView(ctx, depth, node) {
3491
3931
  var _node$b2;
3492
3932
  const source = deserialize$1(ctx, depth, node.f);
3933
+ if (!(source instanceof ArrayBuffer)) throw new SerovalMalformedNodeError(node);
3493
3934
  const offset = (_node$b2 = node.b) !== null && _node$b2 !== void 0 ? _node$b2 : 0;
3494
- if (offset < 0 || offset > source.byteLength || node.l > MAX_BASE64_LENGTH) throw new SerovalMalformedNodeError(node);
3935
+ if (offset < 0 || offset > source.byteLength) throw new SerovalMalformedNodeError(node);
3495
3936
  return assignIndexedValue$1(ctx, node.i, new DataView(source, offset, node.l));
3496
3937
  }
3497
3938
  function deserializeDictionary(ctx, depth, node, result) {
@@ -3550,14 +3991,20 @@ function deserializePromiseFulfill(ctx, depth, node) {
3550
3991
  }
3551
3992
  function deserializeIteratorFactoryInstance(ctx, depth, node) {
3552
3993
  deserialize$1(ctx, depth, node.a[0]);
3553
- return sequenceToIterator(deserialize$1(ctx, depth, node.a[1]));
3994
+ const source = deserialize$1(ctx, depth, node.a[1]);
3995
+ validateNodeType(ctx, node, node.a[1].i, 35);
3996
+ if (!source) throw new SerovalMalformedNodeError(node.a[1]);
3997
+ return sequenceToIterator(source);
3554
3998
  }
3555
3999
  function deserializeAsyncIteratorFactoryInstance(ctx, depth, node) {
3556
4000
  deserialize$1(ctx, depth, node.a[0]);
3557
- return streamToAsyncIterable(deserialize$1(ctx, depth, node.a[1]));
4001
+ const source = deserialize$1(ctx, depth, node.a[1]);
4002
+ validateNodeType(ctx, node, node.a[1].i, 31);
4003
+ if (!source) throw new SerovalMalformedNodeError(node.a[1]);
4004
+ return streamToAsyncIterable(source);
3558
4005
  }
3559
4006
  function deserializeStreamConstructor(ctx, depth, node) {
3560
- const result = assignIndexedValue$1(ctx, node.i, createStream());
4007
+ const result = assignIndexedValue$1(ctx, node.i, createStream2());
3561
4008
  assignNodeType(ctx, node.i, 31);
3562
4009
  const items = node.a;
3563
4010
  const len = items.length;
@@ -3599,6 +4046,7 @@ function deserializeAsyncIteratorFactory(ctx, depth, node) {
3599
4046
  }
3600
4047
  function deserializeSequence(ctx, depth, node) {
3601
4048
  const result = assignIndexedValue$1(ctx, node.i, createSequence([], node.s, node.l));
4049
+ assignNodeType(ctx, node.i, 35);
3602
4050
  for (let i = 0, len = node.a.length; i < len; i++) result.v[i] = deserialize$1(ctx, depth, node.a[i]);
3603
4051
  return result;
3604
4052
  }
@@ -3768,7 +4216,7 @@ function parseProperties(ctx, depth, properties) {
3768
4216
  }
3769
4217
  if (SYM_ASYNC_ITERATOR in properties) {
3770
4218
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_ASYNC_ITERATOR));
3771
- valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream() : createStreamFromAsyncIterable(properties))));
4219
+ valueNodes.push(createAsyncIteratorFactoryInstanceNode(parseAsyncIteratorFactory(ctx.base), parseSOS(ctx, depth, ctx.type === 1 ? createStream2() : createStreamFromAsyncIterable(properties, ctx.state.cleanups))));
3772
4220
  }
3773
4221
  if (SYM_TO_STRING_TAG in properties) {
3774
4222
  keyNodes.push(parseWellKnownSymbol(ctx.base, SYM_TO_STRING_TAG));
@@ -3790,12 +4238,15 @@ function parseBoxed(ctx, depth, id, current) {
3790
4238
  return createBoxedNode(id, parseSOS(ctx, depth, current.valueOf()));
3791
4239
  }
3792
4240
  function parseTypedArray(ctx, depth, id, current) {
4241
+ current = getArrayBufferView(ctx.base, current);
3793
4242
  return createTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
3794
4243
  }
3795
4244
  function parseBigIntTypedArray(ctx, depth, id, current) {
4245
+ current = getArrayBufferView(ctx.base, current);
3796
4246
  return createBigIntTypedArrayNode(id, current, parseSOS(ctx, depth, current.buffer));
3797
4247
  }
3798
4248
  function parseDataView(ctx, depth, id, current) {
4249
+ current = getArrayBufferView(ctx.base, current);
3799
4250
  return createDataViewNode(id, current, parseSOS(ctx, depth, current.buffer));
3800
4251
  }
3801
4252
  function parseError(ctx, depth, id, current) {
@@ -3964,7 +4415,7 @@ function parseObjectPhase2(ctx, depth, id, current, currentClass) {
3964
4415
  }
3965
4416
  function parseObject(ctx, depth, id, current) {
3966
4417
  if (Array.isArray(current)) return parseArray(ctx, depth, id, current);
3967
- if (isStream(current)) return parseStream(ctx, depth, id, current);
4418
+ if (isStream2(current)) return parseStream(ctx, depth, id, current);
3968
4419
  if (isSequence(current)) return parseSequence(ctx, depth, id, current);
3969
4420
  let currentClass = current.constructor;
3970
4421
  if (currentClass !== void 0 && typeof currentClass !== "function") {
@@ -4062,15 +4513,19 @@ function destroyStreamParse(ctx) {
4062
4513
  }
4063
4514
  }
4064
4515
  async function toCrossJSONAsync(source, options = {}) {
4516
+ const plugins = resolvePlugins(options.plugins);
4065
4517
  return await parseTopAsync(createAsyncParserContext(2, {
4066
- plugins: resolvePlugins(options.plugins),
4518
+ compactArrayBufferViews: options.compactArrayBufferViews,
4519
+ plugins,
4067
4520
  disabledFeatures: options.disabledFeatures,
4068
4521
  refs: options.refs
4069
4522
  }), source);
4070
4523
  }
4071
4524
  function toCrossJSONStream(source, options) {
4525
+ const plugins = resolvePlugins(options.plugins);
4072
4526
  const ctx = createStreamParserContext({
4073
- plugins: resolvePlugins(options.plugins),
4527
+ compactArrayBufferViews: options.compactArrayBufferViews,
4528
+ plugins,
4074
4529
  refs: options.refs,
4075
4530
  disabledFeatures: options.disabledFeatures,
4076
4531
  depthLimit: options.depthLimit,
@@ -4087,15 +4542,18 @@ function fromJSON(source, options = {}) {
4087
4542
  const disabledFeatures = options.disabledFeatures || 0;
4088
4543
  const sourceFeatures = (_source$f = source.f) !== null && _source$f !== void 0 ? _source$f : 127;
4089
4544
  return deserializeTop(createVanillaDeserializerContext({
4545
+ maxBase64Length: options.maxBase64Length,
4090
4546
  plugins,
4091
4547
  markedRefs: source.m,
4092
4548
  features: sourceFeatures & ~disabledFeatures,
4093
4549
  disabledFeatures
4094
4550
  }), source.t);
4095
4551
  }
4096
- var textEncoder2 = new TextEncoder();
4552
+ var textEncoder$1 = new TextEncoder();
4097
4553
  var EMPTY_PAYLOAD = /* @__PURE__ */ new Uint8Array(0);
4554
+ var MAX_ERROR_MESSAGE_CODE_UNITS = 4096;
4098
4555
  function encodeFrame(type, streamId, payload) {
4556
+ if (payload.byteLength > 16777216) throw new RangeError(`Frame payload exceeds ${MAX_FRAME_PAYLOAD_SIZE} bytes`);
4099
4557
  const frame = new Uint8Array(9 + payload.length);
4100
4558
  frame[0] = type;
4101
4559
  frame[1] = streamId >>> 24 & 255;
@@ -4109,119 +4567,303 @@ function encodeFrame(type, streamId, payload) {
4109
4567
  frame.set(payload, 9);
4110
4568
  return frame;
4111
4569
  }
4112
- function encodeJSONFrame(json) {
4113
- return encodeFrame(FrameType.JSON, 0, textEncoder2.encode(json));
4114
- }
4115
- function encodeChunkFrame(streamId, chunk) {
4116
- return encodeFrame(FrameType.CHUNK, streamId, chunk);
4117
- }
4118
- function encodeEndFrame(streamId) {
4119
- return encodeFrame(FrameType.END, streamId, EMPTY_PAYLOAD);
4120
- }
4121
- function encodeErrorFrame(streamId, error) {
4122
- const message = error instanceof Error ? error.message : String(error ?? "Unknown error");
4123
- return encodeFrame(FrameType.ERROR, streamId, textEncoder2.encode(message));
4570
+ function encodeErrorPayload(error) {
4571
+ const originalMessage = error instanceof Error ? error.message : String(error ?? "Unknown error");
4572
+ const message = originalMessage.length > MAX_ERROR_MESSAGE_CODE_UNITS ? `${originalMessage.slice(0, MAX_ERROR_MESSAGE_CODE_UNITS)}\u2026` : originalMessage;
4573
+ return textEncoder$1.encode(message);
4124
4574
  }
4125
- function createMultiplexedStream(jsonStream, rawStreams, lateStreamSource) {
4575
+ function createMultiplexedStream(recordStream, options = {}) {
4126
4576
  let controller;
4127
- let cancelled = false;
4128
- const readers = [];
4129
- const enqueue = (frame) => {
4130
- if (cancelled) return false;
4577
+ let stopped = false;
4578
+ let activePumps = 0;
4579
+ let wakeDemand;
4580
+ let admission;
4581
+ const readers = /* @__PURE__ */ new Set();
4582
+ const pendingRawStreams = /* @__PURE__ */ new Set();
4583
+ const abortOutput = () => errorOutput(options.signal?.reason);
4584
+ const wakeAdmission = () => {
4585
+ const wake = wakeDemand;
4586
+ wakeDemand = void 0;
4587
+ wake?.();
4588
+ };
4589
+ const cancelReader2 = (reader, reason) => {
4590
+ reader.cancel(reason).catch(() => {
4591
+ });
4592
+ };
4593
+ const cancelStream = (stream, reason) => {
4594
+ stream.cancel(reason).catch(() => {
4595
+ });
4596
+ };
4597
+ const stop = (reason) => {
4598
+ if (stopped) return false;
4599
+ stopped = [reason];
4600
+ options.signal?.removeEventListener("abort", abortOutput);
4601
+ wakeAdmission();
4602
+ for (const reader of readers) cancelReader2(reader, reason);
4603
+ for (const stream of pendingRawStreams) cancelStream(stream, reason);
4604
+ pendingRawStreams.clear();
4605
+ return true;
4606
+ };
4607
+ const errorOutput = (error) => {
4608
+ if (!stop(error)) return;
4131
4609
  try {
4132
- controller.enqueue(frame);
4133
- return true;
4610
+ controller.error(error);
4134
4611
  } catch {
4135
- return false;
4136
4612
  }
4137
4613
  };
4138
- const errorOutput = (error) => {
4139
- if (cancelled) return;
4140
- cancelled = true;
4614
+ const waitForDemand = async () => {
4615
+ while (!stopped && (controller.desiredSize ?? 0) <= 0) await new Promise((resolve) => {
4616
+ wakeDemand = resolve;
4617
+ });
4618
+ return !stopped;
4619
+ };
4620
+ const admitFrame = (type, streamId, payload) => {
4621
+ if (stopped) return false;
4622
+ if (!admission && (controller.desiredSize ?? 0) > 0) {
4623
+ controller.enqueue(encodeFrame(type, streamId, payload));
4624
+ return true;
4625
+ }
4626
+ const runAdmission = async () => {
4627
+ if (!await waitForDemand()) return false;
4628
+ controller.enqueue(encodeFrame(type, streamId, payload));
4629
+ return true;
4630
+ };
4631
+ const result = admission ? admission.then(runAdmission) : runAdmission();
4632
+ const clearAdmission = () => {
4633
+ if (admission === tail) admission = void 0;
4634
+ };
4635
+ const tail = result.then(clearAdmission, clearAdmission);
4636
+ admission = tail;
4637
+ return result;
4638
+ };
4639
+ const maybeClose = () => {
4640
+ if (activePumps !== 0 || !stop()) return;
4141
4641
  try {
4142
- controller.error(error);
4642
+ controller.close();
4143
4643
  } catch {
4144
4644
  }
4145
- for (const reader of readers) reader.cancel().catch(() => {
4146
- });
4147
4645
  };
4148
- async function pumpRawStream(streamId, stream) {
4149
- const reader = stream.getReader();
4150
- readers.push(reader);
4151
- try {
4152
- while (!cancelled) {
4153
- const { done, value } = await reader.read();
4154
- if (done) {
4155
- enqueue(encodeEndFrame(streamId));
4156
- return;
4157
- }
4158
- if (!enqueue(encodeChunkFrame(streamId, value))) return;
4159
- }
4160
- } catch (error) {
4161
- enqueue(encodeErrorFrame(streamId, error));
4162
- } finally {
4163
- reader.releaseLock();
4164
- }
4646
+ const startPump = (pump) => {
4647
+ activePumps++;
4648
+ pump().then(() => {
4649
+ activePumps--;
4650
+ maybeClose();
4651
+ }, (error) => {
4652
+ activePumps--;
4653
+ errorOutput(error);
4654
+ });
4655
+ };
4656
+ async function pumpRawStream(streamId, stream) {
4657
+ const reader = stream.getReader();
4658
+ readers.add(reader);
4659
+ try {
4660
+ while (!stopped) {
4661
+ const { done, value } = await reader.read();
4662
+ if (stopped) return;
4663
+ if (done) {
4664
+ const frameAdmission = admitFrame(2, streamId, EMPTY_PAYLOAD);
4665
+ if (frameAdmission !== true) await frameAdmission;
4666
+ return;
4667
+ }
4668
+ if (!(value instanceof Uint8Array)) throw new TypeError("RawStream chunks must be Uint8Array");
4669
+ let offset = 0;
4670
+ do {
4671
+ const frameAdmission = admitFrame(1, streamId, value.byteLength <= 16777216 ? value : value.subarray(offset, offset + MAX_FRAME_PAYLOAD_SIZE));
4672
+ if (frameAdmission !== true && (frameAdmission === false || !await frameAdmission)) return;
4673
+ offset += MAX_FRAME_PAYLOAD_SIZE;
4674
+ } while (offset < value.byteLength);
4675
+ }
4676
+ } catch (error) {
4677
+ if (!stopped) {
4678
+ const frameAdmission = admitFrame(3, streamId, encodeErrorPayload(error));
4679
+ if (frameAdmission !== true) await frameAdmission;
4680
+ }
4681
+ } finally {
4682
+ readers.delete(reader);
4683
+ reader.releaseLock();
4684
+ }
4685
+ }
4686
+ async function pumpRecords() {
4687
+ const reader = recordStream.getReader();
4688
+ readers.add(reader);
4689
+ try {
4690
+ while (!stopped) {
4691
+ const { done, value } = await reader.read();
4692
+ if (stopped) {
4693
+ if (!done) for (const registration of value.rawStreams) cancelStream(registration.stream, stopped[0]);
4694
+ return;
4695
+ }
4696
+ if (done) return;
4697
+ for (const registration of value.rawStreams) pendingRawStreams.add(registration.stream);
4698
+ const frameAdmission = admitFrame(0, 0, value.json);
4699
+ if (frameAdmission !== true && (frameAdmission === false || !await frameAdmission)) return;
4700
+ for (const registration of value.rawStreams) {
4701
+ pendingRawStreams.delete(registration.stream);
4702
+ startPump(pumpRawStream.bind(void 0, registration.id, registration.stream));
4703
+ }
4704
+ }
4705
+ } catch (error) {
4706
+ if (!stopped) errorOutput(error);
4707
+ } finally {
4708
+ readers.delete(reader);
4709
+ reader.releaseLock();
4710
+ }
4711
+ }
4712
+ return new ReadableStream({
4713
+ start(ctrl) {
4714
+ controller = ctrl;
4715
+ if (options.signal?.aborted) {
4716
+ cancelStream(recordStream, options.signal.reason);
4717
+ errorOutput(options.signal.reason);
4718
+ return;
4719
+ }
4720
+ options.signal?.addEventListener("abort", abortOutput, { once: true });
4721
+ startPump(pumpRecords);
4722
+ },
4723
+ pull() {
4724
+ wakeAdmission();
4725
+ },
4726
+ cancel(reason) {
4727
+ if (stop(reason)) options.onCancel?.(reason);
4728
+ }
4729
+ });
4730
+ }
4731
+ function isSafeKey(key) {
4732
+ return key !== "__proto__" && key !== "constructor" && key !== "prototype";
4733
+ }
4734
+ function safeObjectMerge(target, source) {
4735
+ const result = /* @__PURE__ */ Object.create(null);
4736
+ if (target) {
4737
+ for (const key of Object.keys(target)) if (isSafeKey(key)) result[key] = target[key];
4738
+ }
4739
+ if (source && typeof source === "object") {
4740
+ for (const key of Object.keys(source)) if (isSafeKey(key)) result[key] = source[key];
4741
+ }
4742
+ return result;
4743
+ }
4744
+ function createNullProtoObject(source) {
4745
+ if (!source) return /* @__PURE__ */ Object.create(null);
4746
+ const obj = /* @__PURE__ */ Object.create(null);
4747
+ for (const key of Object.keys(source)) if (isSafeKey(key)) obj[key] = source[key];
4748
+ return obj;
4749
+ }
4750
+ function flattenMiddlewares(middlewares, maxDepth = 100) {
4751
+ const seen = /* @__PURE__ */ new Set();
4752
+ const flattened = [];
4753
+ const recurse = (middleware, depth) => {
4754
+ if (depth > maxDepth) throw new Error(`Middleware nesting depth exceeded maximum of ${maxDepth}. Check for circular references.`);
4755
+ middleware.forEach((m) => {
4756
+ if (m.options.middleware) recurse(m.options.middleware, depth + 1);
4757
+ if (!seen.has(m)) {
4758
+ seen.add(m);
4759
+ flattened.push(m);
4760
+ }
4761
+ });
4762
+ };
4763
+ recurse(middlewares, 0);
4764
+ return flattened;
4765
+ }
4766
+ var createMiddleware = (options, __opts) => {
4767
+ const resolvedOptions = {
4768
+ type: "request",
4769
+ ...__opts || options
4770
+ };
4771
+ const setValidator = (validator) => {
4772
+ return createMiddleware({}, Object.assign(resolvedOptions, {
4773
+ validator,
4774
+ inputValidator: validator
4775
+ }));
4776
+ };
4777
+ return {
4778
+ options: resolvedOptions,
4779
+ middleware: (middleware) => {
4780
+ return createMiddleware({}, Object.assign(resolvedOptions, { middleware }));
4781
+ },
4782
+ validator: setValidator,
4783
+ inputValidator: setValidator,
4784
+ client: (client) => {
4785
+ return createMiddleware({}, Object.assign(resolvedOptions, { client }));
4786
+ },
4787
+ server: (server) => {
4788
+ return createMiddleware({}, Object.assign(resolvedOptions, { server }));
4789
+ }
4790
+ };
4791
+ };
4792
+ var innerCreateCsrfMiddleware = (opts = {}) => {
4793
+ return createMiddleware().server(async (ctx) => {
4794
+ const csrfCtx = ctx;
4795
+ if (opts.filter && !await opts.filter(csrfCtx)) return ctx.next();
4796
+ if (await isCsrfRequestAllowed(opts, csrfCtx)) return ctx.next();
4797
+ return getFailureResponse(opts, csrfCtx);
4798
+ });
4799
+ };
4800
+ var createCsrfMiddleware = innerCreateCsrfMiddleware;
4801
+ async function isCsrfRequestAllowed(opts, ctx) {
4802
+ const result = await getCsrfRequestValidationResult(opts, ctx);
4803
+ return result === true || result === void 0 && opts.allowRequestsWithoutOriginCheck === true;
4804
+ }
4805
+ async function getCsrfRequestValidationResult(opts, ctx) {
4806
+ const fetchSite = ctx.request.headers.get("Sec-Fetch-Site");
4807
+ if (fetchSite !== null) return matchValue(opts.secFetchSite ?? "same-origin", fetchSite, ctx);
4808
+ const origin = ctx.request.headers.get("Origin");
4809
+ if (origin !== null) {
4810
+ if (opts.origin) return matchValue(opts.origin, origin, ctx);
4811
+ return origin === new URL(ctx.request.url).origin;
4165
4812
  }
4166
- async function pumpJSON() {
4167
- const reader = jsonStream.getReader();
4168
- readers.push(reader);
4169
- try {
4170
- while (!cancelled) {
4171
- const { done, value } = await reader.read();
4172
- if (done) return;
4173
- if (!enqueue(encodeJSONFrame(value))) return;
4174
- }
4175
- } catch (error) {
4176
- errorOutput(error);
4177
- throw error;
4178
- } finally {
4179
- reader.releaseLock();
4180
- }
4813
+ const referer = ctx.request.headers.get("Referer");
4814
+ if (referer === null || opts.referer === false) return;
4815
+ if (typeof opts.referer === "function") return opts.referer(referer, ctx);
4816
+ if (opts.origin) {
4817
+ const refererOrigin = getOriginFromUrl(referer);
4818
+ return refererOrigin !== void 0 && matchValue(opts.origin, refererOrigin, ctx);
4181
4819
  }
4182
- async function pumpLateStreams() {
4183
- if (!lateStreamSource) return [];
4184
- const lateStreamPumps = [];
4185
- const reader = lateStreamSource.getReader();
4186
- readers.push(reader);
4187
- try {
4188
- while (!cancelled) {
4189
- const { done, value } = await reader.read();
4190
- if (done) break;
4191
- lateStreamPumps.push(pumpRawStream(value.id, value.stream));
4192
- }
4193
- } finally {
4194
- reader.releaseLock();
4195
- }
4196
- return lateStreamPumps;
4820
+ return isRefererSameOrigin(referer, new URL(ctx.request.url).origin);
4821
+ }
4822
+ async function matchValue(matcher, value, ctx) {
4823
+ if (typeof matcher === "function") return matcher(value, ctx);
4824
+ if (Array.isArray(matcher)) return matcher.includes(value);
4825
+ return value === matcher;
4826
+ }
4827
+ function getOriginFromUrl(url) {
4828
+ try {
4829
+ return new URL(url).origin;
4830
+ } catch {
4831
+ return;
4197
4832
  }
4198
- return new ReadableStream({
4199
- async start(ctrl) {
4200
- controller = ctrl;
4201
- const pumps = [pumpJSON()];
4202
- for (const [streamId, stream] of rawStreams) pumps.push(pumpRawStream(streamId, stream));
4203
- if (lateStreamSource) pumps.push(pumpLateStreams());
4204
- try {
4205
- const latePumps = (await Promise.all(pumps)).find(Array.isArray);
4206
- if (latePumps && latePumps.length > 0) await Promise.all(latePumps);
4207
- if (!cancelled) try {
4208
- controller.close();
4209
- } catch {
4210
- }
4211
- } catch {
4212
- }
4213
- },
4214
- cancel() {
4215
- cancelled = true;
4216
- for (const reader of readers) reader.cancel().catch(() => {
4217
- });
4218
- readers.length = 0;
4219
- }
4220
- });
4833
+ }
4834
+ function isRefererSameOrigin(referer, requestOrigin) {
4835
+ if (referer === requestOrigin) return true;
4836
+ if (!referer.startsWith(requestOrigin)) return false;
4837
+ if (referer.length === requestOrigin.length) return true;
4838
+ const code = referer.charCodeAt(requestOrigin.length);
4839
+ return code === 47 || code === 63 || code === 35;
4840
+ }
4841
+ async function getFailureResponse(opts, ctx) {
4842
+ if (typeof opts.failureResponse === "function") return opts.failureResponse(ctx);
4843
+ return opts.failureResponse?.clone() ?? new Response("Forbidden", { status: 403 });
4221
4844
  }
4222
4845
  var serovalPlugins = void 0;
4223
4846
  var FORM_DATA_CONTENT_TYPES = ["multipart/form-data", "application/x-www-form-urlencoded"];
4224
4847
  var MAX_PAYLOAD_SIZE = 1e6;
4848
+ var MAX_PENDING_SERIALIZATION_RECORDS = 1024;
4849
+ var MAX_PENDING_SERIALIZATION_BYTES = 33554432;
4850
+ var textEncoder3 = new TextEncoder();
4851
+ function encodeSerializationRecord(value) {
4852
+ return textEncoder3.encode(JSON.stringify(value));
4853
+ }
4854
+ function exceedsPendingSerializationLimit(record, recordCount, pendingBytes) {
4855
+ return recordCount >= MAX_PENDING_SERIALIZATION_RECORDS || pendingBytes + record.byteLength > MAX_PENDING_SERIALIZATION_BYTES;
4856
+ }
4857
+ function runSerializationCleanup(dispose) {
4858
+ try {
4859
+ dispose();
4860
+ } catch {
4861
+ }
4862
+ }
4863
+ function cancelRawStream(stream, reason) {
4864
+ stream.cancel(reason).catch(() => {
4865
+ });
4866
+ }
4225
4867
  var handleServerAction = async ({ request, context, serverFnId }) => {
4226
4868
  const methodUpper = request.method.toUpperCase();
4227
4869
  const url = new URL(request.url);
@@ -4231,192 +4873,260 @@ var handleServerAction = async ({ request, context, serverFnId }) => {
4231
4873
  headers: { Allow: action.method }
4232
4874
  });
4233
4875
  const isServerFn = request.headers.get("x-tsr-serverFn") === "true";
4234
- if (!serovalPlugins) serovalPlugins = getDefaultSerovalPlugins();
4876
+ serovalPlugins ??= getSerovalPlugins(defaultSerovalDeserializerPlugins);
4235
4877
  const contentType = request.headers.get("Content-Type");
4236
- function parsePayload(payload) {
4237
- return fromJSON(payload, { plugins: serovalPlugins });
4238
- }
4239
- return await (async () => {
4240
- try {
4241
- let serializeResult2 = function(res2) {
4242
- let nonStreamingBody = void 0;
4243
- const alsResponse = getResponse();
4244
- if (res2 !== void 0) {
4245
- const rawStreams = /* @__PURE__ */ new Map();
4246
- let initialPhase = true;
4247
- let lateStreamWriter;
4248
- let lateStreamReadable = void 0;
4249
- const pendingLateStreams = [];
4250
- const plugins = [createRawStreamRPCPlugin((id, stream) => {
4251
- if (initialPhase) {
4252
- rawStreams.set(id, stream);
4253
- return;
4254
- }
4255
- if (lateStreamWriter) {
4256
- lateStreamWriter.write({
4257
- id,
4258
- stream
4259
- }).catch(() => {
4260
- });
4261
- return;
4262
- }
4263
- pendingLateStreams.push({
4264
- id,
4265
- stream
4266
- });
4267
- }), ...serovalPlugins || []];
4268
- let done = false;
4269
- const callbacks = {
4270
- onParse: (value) => {
4271
- nonStreamingBody = value;
4272
- },
4273
- onDone: () => {
4274
- done = true;
4275
- },
4276
- onError: (error) => {
4277
- throw error;
4278
- }
4279
- };
4280
- toCrossJSONStream(res2, {
4281
- refs: /* @__PURE__ */ new Map(),
4282
- plugins,
4283
- onParse(value) {
4284
- callbacks.onParse(value);
4285
- },
4286
- onDone() {
4287
- callbacks.onDone();
4288
- },
4289
- onError: (error) => {
4290
- callbacks.onError(error);
4291
- }
4292
- });
4293
- initialPhase = false;
4294
- if (done && rawStreams.size === 0) return new Response(nonStreamingBody ? JSON.stringify(nonStreamingBody) : void 0, {
4295
- status: alsResponse.status,
4296
- statusText: alsResponse.statusText,
4297
- headers: {
4298
- "Content-Type": "application/json",
4299
- [X_TSS_SERIALIZED]: "true"
4300
- }
4301
- });
4302
- const { readable, writable } = new TransformStream();
4303
- lateStreamReadable = readable;
4304
- lateStreamWriter = writable.getWriter();
4305
- for (const registration of pendingLateStreams) lateStreamWriter.write(registration).catch(() => {
4306
- });
4307
- pendingLateStreams.length = 0;
4308
- const multiplexedStream = createMultiplexedStream(new ReadableStream({
4309
- start(controller) {
4310
- callbacks.onParse = (value) => {
4311
- controller.enqueue(JSON.stringify(value) + "\n");
4312
- };
4313
- callbacks.onDone = () => {
4314
- try {
4315
- controller.close();
4316
- } catch {
4317
- }
4318
- lateStreamWriter?.close().catch(() => {
4319
- }).finally(() => {
4320
- lateStreamWriter = void 0;
4321
- });
4322
- };
4323
- callbacks.onError = (error) => {
4324
- controller.error(error);
4325
- lateStreamWriter?.abort(error).catch(() => {
4326
- }).finally(() => {
4327
- lateStreamWriter = void 0;
4328
- });
4329
- };
4330
- if (nonStreamingBody !== void 0) callbacks.onParse(nonStreamingBody);
4331
- if (done) callbacks.onDone();
4332
- },
4333
- cancel() {
4334
- lateStreamWriter?.abort().catch(() => {
4335
- });
4336
- lateStreamWriter = void 0;
4337
- }
4338
- }), rawStreams, lateStreamReadable);
4339
- return new Response(multiplexedStream, {
4340
- status: alsResponse.status,
4341
- statusText: alsResponse.statusText,
4342
- headers: {
4343
- "Content-Type": TSS_CONTENT_TYPE_FRAMED_VERSIONED,
4344
- [X_TSS_SERIALIZED]: "true"
4345
- }
4346
- });
4347
- }
4348
- return new Response(void 0, {
4349
- status: alsResponse.status,
4350
- statusText: alsResponse.statusText
4351
- });
4878
+ try {
4879
+ let res;
4880
+ if (FORM_DATA_CONTENT_TYPES.some((type) => contentType && contentType.includes(type))) {
4881
+ if (methodUpper === "GET") invariant();
4882
+ const formData = await request.formData();
4883
+ const serializedContext = formData.get(TSS_FORMDATA_CONTEXT);
4884
+ formData.delete(TSS_FORMDATA_CONTEXT);
4885
+ const params = {
4886
+ context,
4887
+ data: formData,
4888
+ method: methodUpper
4352
4889
  };
4353
- var serializeResult = serializeResult2;
4354
- let res = await (async () => {
4355
- if (FORM_DATA_CONTENT_TYPES.some((type) => contentType && contentType.includes(type))) {
4356
- if (methodUpper === "GET") invariant();
4357
- const formData = await request.formData();
4358
- const serializedContext = formData.get(TSS_FORMDATA_CONTEXT);
4359
- formData.delete(TSS_FORMDATA_CONTEXT);
4360
- const params = {
4361
- context,
4362
- data: formData,
4363
- method: methodUpper
4364
- };
4365
- if (typeof serializedContext === "string") try {
4366
- const deserializedContext = fromJSON(JSON.parse(serializedContext), { plugins: serovalPlugins });
4367
- if (typeof deserializedContext === "object" && deserializedContext) params.context = safeObjectMerge(deserializedContext, context);
4368
- } catch (e) {
4369
- }
4370
- return await action(params);
4371
- }
4372
- if (methodUpper === "GET") {
4373
- const payloadParam = url.searchParams.get("payload");
4374
- if (payloadParam && payloadParam.length > MAX_PAYLOAD_SIZE) throw new Error("Payload too large");
4375
- const payload2 = payloadParam ? parsePayload(JSON.parse(payloadParam)) : {};
4376
- payload2.context = safeObjectMerge(payload2.context, context);
4377
- payload2.method = methodUpper;
4378
- return await action(payload2);
4379
- }
4380
- let jsonPayload;
4381
- if (contentType?.includes("application/json")) jsonPayload = await request.json();
4382
- const payload = jsonPayload ? parsePayload(jsonPayload) : {};
4383
- payload.context = safeObjectMerge(payload.context, context);
4384
- payload.method = methodUpper;
4385
- return await action(payload);
4386
- })();
4387
- const unwrapped = res.result || res.error;
4388
- if (isNotFound(res)) res = isNotFoundResponse(res);
4389
- if (!isServerFn) return unwrapped;
4390
- if (unwrapped instanceof Response) {
4391
- if (isRedirect(unwrapped)) return unwrapped;
4392
- unwrapped.headers.set(X_TSS_RAW_RESPONSE, "true");
4393
- return unwrapped;
4890
+ if (typeof serializedContext === "string") try {
4891
+ const deserializedContext = fromJSON(JSON.parse(serializedContext), { plugins: serovalPlugins });
4892
+ if (typeof deserializedContext === "object" && deserializedContext) params.context = safeObjectMerge(deserializedContext, context);
4893
+ } catch (e) {
4394
4894
  }
4395
- return serializeResult2(res);
4396
- } catch (error) {
4397
- if (error instanceof Response) return error;
4398
- if (isNotFound(error)) return isNotFoundResponse(error);
4399
- console.info();
4400
- console.info("Server Fn Error!");
4401
- console.info();
4402
- console.error(error);
4403
- console.info();
4404
- const serializedError = JSON.stringify(await Promise.resolve(toCrossJSONAsync(error, {
4405
- refs: /* @__PURE__ */ new Map(),
4406
- plugins: serovalPlugins
4407
- })));
4408
- const response = getResponse();
4895
+ res = await action(params);
4896
+ } else if (methodUpper === "GET") {
4897
+ const payloadParam = url.searchParams.get("payload");
4898
+ if (payloadParam && payloadParam.length > MAX_PAYLOAD_SIZE) throw new Error("Payload too large");
4899
+ const payload = payloadParam ? fromJSON(JSON.parse(payloadParam), { plugins: serovalPlugins }) : {};
4900
+ payload.context = safeObjectMerge(payload.context, context);
4901
+ payload.method = methodUpper;
4902
+ res = await action(payload);
4903
+ } else {
4904
+ const payload = contentType?.includes("application/json") ? fromJSON(await request.json(), { plugins: serovalPlugins }) : {};
4905
+ payload.context = safeObjectMerge(payload.context, context);
4906
+ payload.method = methodUpper;
4907
+ res = await action(payload);
4908
+ }
4909
+ const unwrapped = res.result !== void 0 ? res.result : res.error;
4910
+ if (isNotFound(res)) res = isNotFoundResponse(res);
4911
+ if (!isServerFn) return unwrapped;
4912
+ if (unwrapped instanceof Response) {
4913
+ if (isRedirect(unwrapped)) return unwrapped;
4914
+ unwrapped.headers.set(X_TSS_RAW_RESPONSE, "true");
4915
+ return unwrapped;
4916
+ }
4917
+ return serializeResult(res, request.signal, serovalPlugins);
4918
+ } catch (error) {
4919
+ if (error instanceof Response) return error;
4920
+ if (isNotFound(error)) return isNotFoundResponse(error);
4921
+ console.error("Server Fn Error!", error);
4922
+ const serializedError = JSON.stringify(await toCrossJSONAsync(error, {
4923
+ refs: /* @__PURE__ */ new Map(),
4924
+ plugins: serovalPlugins
4925
+ }));
4926
+ const response = getResponse();
4927
+ const headers = {
4928
+ "Content-Type": "application/json",
4929
+ [X_TSS_SERIALIZED]: "true"
4930
+ };
4931
+ try {
4409
4932
  return new Response(serializedError, {
4410
4933
  status: response.status ?? 500,
4411
4934
  statusText: response.statusText,
4935
+ headers
4936
+ });
4937
+ } catch {
4938
+ return new Response(serializedError, {
4939
+ status: 500,
4940
+ statusText: "",
4941
+ headers
4942
+ });
4943
+ }
4944
+ }
4945
+ };
4946
+ function serializeResult(res, signal, plugins) {
4947
+ const alsResponse = getResponse();
4948
+ const initialRecords = [];
4949
+ let initialBytes = 0;
4950
+ const pendingRawStreams = [];
4951
+ let done = false;
4952
+ let initialParsed = false;
4953
+ let serializationFailure;
4954
+ let disposeSerialization;
4955
+ let onParse2 = (value, initial) => {
4956
+ if (serializationFailure) return;
4957
+ initialParsed ||= initial;
4958
+ const record = encodeSerializationRecord(value);
4959
+ if (exceedsPendingSerializationLimit(record, initialRecords.length, initialBytes)) {
4960
+ serializationFailure = [/* @__PURE__ */ new Error("Server function serialization exceeded its pending output limit")];
4961
+ return;
4962
+ }
4963
+ initialRecords.push(record);
4964
+ initialBytes += record.byteLength;
4965
+ };
4966
+ let onDone2 = () => {
4967
+ if (initialParsed) done = true;
4968
+ };
4969
+ let onError2 = (error) => {
4970
+ serializationFailure ??= [error];
4971
+ };
4972
+ const rawStreamPlugin = createRawStreamRPCPlugin((id, stream) => {
4973
+ if (serializationFailure) {
4974
+ cancelRawStream(stream, serializationFailure[0]);
4975
+ return;
4976
+ }
4977
+ if (id > 1024) {
4978
+ const error = /* @__PURE__ */ new Error(`Too many raw streams in framed response (max ${MAX_FRAMED_STREAMS})`);
4979
+ cancelRawStream(stream, error);
4980
+ onError2(error);
4981
+ return;
4982
+ }
4983
+ pendingRawStreams.push({
4984
+ id,
4985
+ stream
4986
+ });
4987
+ });
4988
+ const dispose = toCrossJSONStream(res, {
4989
+ refs: /* @__PURE__ */ new Map(),
4990
+ plugins: [rawStreamPlugin, ...plugins],
4991
+ onParse(value, initial) {
4992
+ onParse2(value, initial);
4993
+ },
4994
+ onDone() {
4995
+ onDone2();
4996
+ },
4997
+ onError: (error) => {
4998
+ onError2(error);
4999
+ }
5000
+ });
5001
+ if (serializationFailure) {
5002
+ runSerializationCleanup(dispose);
5003
+ for (const registration of pendingRawStreams) cancelRawStream(registration.stream, serializationFailure[0]);
5004
+ throw serializationFailure[0];
5005
+ }
5006
+ if (!done) disposeSerialization = dispose;
5007
+ if (done && pendingRawStreams.length === 0 && initialRecords.length === 1) return new Response(initialRecords[0], {
5008
+ status: alsResponse.status,
5009
+ statusText: alsResponse.statusText,
5010
+ headers: {
5011
+ "Content-Type": "application/json",
5012
+ [X_TSS_SERIALIZED]: "true"
5013
+ }
5014
+ });
5015
+ if (done && initialRecords.length === 1) {
5016
+ const json = initialRecords[0];
5017
+ if (json.byteLength > 16777216) {
5018
+ const error = /* @__PURE__ */ new Error("Server function serialization exceeded its pending output limit");
5019
+ for (const registration of pendingRawStreams) cancelRawStream(registration.stream, error);
5020
+ throw error;
5021
+ }
5022
+ const rawStreams = pendingRawStreams.splice(0);
5023
+ initialRecords.length = 0;
5024
+ return createFramedResponse(new ReadableStream({
5025
+ start(controller) {
5026
+ controller.enqueue({
5027
+ json,
5028
+ rawStreams
5029
+ });
5030
+ controller.close();
5031
+ },
5032
+ cancel(reason) {
5033
+ for (const registration of rawStreams) cancelRawStream(registration.stream, reason);
5034
+ }
5035
+ }), { signal });
5036
+ }
5037
+ const { readable, writable } = new TransformStream();
5038
+ const writer = writable.getWriter();
5039
+ const recordAbortController = new AbortController();
5040
+ let pendingBytes = 0;
5041
+ const pendingRecords = /* @__PURE__ */ new Set();
5042
+ const abortRecordStream = (error) => {
5043
+ if (serializationFailure) return;
5044
+ serializationFailure = [error];
5045
+ const disposeCurrentSerialization = disposeSerialization;
5046
+ disposeSerialization = void 0;
5047
+ for (const registration of pendingRawStreams.splice(0)) cancelRawStream(registration.stream, error);
5048
+ for (const record of pendingRecords) for (const registration of record.rawStreams) cancelRawStream(registration.stream, error);
5049
+ pendingRecords.clear();
5050
+ recordAbortController.abort(error);
5051
+ writer.abort(error).catch(() => {
5052
+ });
5053
+ if (disposeCurrentSerialization) runSerializationCleanup(disposeCurrentSerialization);
5054
+ };
5055
+ const writeRecord = (json, rawStreams) => {
5056
+ if (serializationFailure) {
5057
+ for (const registration of rawStreams) cancelRawStream(registration.stream, serializationFailure[0]);
5058
+ return false;
5059
+ }
5060
+ if (json.byteLength > 16777216 || exceedsPendingSerializationLimit(json, pendingRecords.size, pendingBytes)) {
5061
+ const error = /* @__PURE__ */ new Error("Server function serialization exceeded its pending output limit");
5062
+ for (const registration of rawStreams) cancelRawStream(registration.stream, error);
5063
+ onError2(error);
5064
+ return false;
5065
+ }
5066
+ pendingBytes += json.byteLength;
5067
+ const record = {
5068
+ json,
5069
+ rawStreams
5070
+ };
5071
+ pendingRecords.add(record);
5072
+ writer.write(record).then(() => {
5073
+ pendingRecords.delete(record);
5074
+ pendingBytes -= json.byteLength;
5075
+ }, (error) => {
5076
+ const stillOwned = pendingRecords.delete(record);
5077
+ pendingBytes -= json.byteLength;
5078
+ if (stillOwned) for (const registration of rawStreams) cancelRawStream(registration.stream, error);
5079
+ });
5080
+ return true;
5081
+ };
5082
+ onParse2 = (value) => {
5083
+ if (serializationFailure) return;
5084
+ writeRecord(encodeSerializationRecord(value), pendingRawStreams.splice(0));
5085
+ };
5086
+ onDone2 = () => {
5087
+ if (serializationFailure) return;
5088
+ disposeSerialization = void 0;
5089
+ writer.close().catch(() => {
5090
+ });
5091
+ };
5092
+ onError2 = (error) => {
5093
+ abortRecordStream(error);
5094
+ };
5095
+ const initialRawStreams = pendingRawStreams.splice(0);
5096
+ for (let index = 0; index < initialRecords.length; index++) {
5097
+ const isLast = index === initialRecords.length - 1;
5098
+ if (!writeRecord(initialRecords[index], isLast ? initialRawStreams : [])) {
5099
+ if (!isLast) for (const registration of initialRawStreams) cancelRawStream(registration.stream, serializationFailure[0]);
5100
+ initialRecords.length = 0;
5101
+ throw serializationFailure[0];
5102
+ }
5103
+ }
5104
+ initialRecords.length = 0;
5105
+ if (done) onDone2();
5106
+ writer.closed.catch((error) => {
5107
+ abortRecordStream(error);
5108
+ });
5109
+ return createFramedResponse(readable, {
5110
+ signal: AbortSignal.any([recordAbortController.signal, signal]),
5111
+ onCancel: abortRecordStream
5112
+ });
5113
+ function createFramedResponse(records, options) {
5114
+ const multiplexedStream = createMultiplexedStream(records, options);
5115
+ try {
5116
+ return new Response(multiplexedStream, {
5117
+ status: alsResponse.status,
5118
+ statusText: alsResponse.statusText,
4412
5119
  headers: {
4413
- "Content-Type": "application/json",
5120
+ "Content-Type": TSS_CONTENT_TYPE_FRAMED_VERSIONED,
4414
5121
  [X_TSS_SERIALIZED]: "true"
4415
5122
  }
4416
5123
  });
5124
+ } catch (error) {
5125
+ cancelRawStream(multiplexedStream, error);
5126
+ throw error;
4417
5127
  }
4418
- })();
4419
- };
5128
+ }
5129
+ }
4420
5130
  function isNotFoundResponse(error) {
4421
5131
  const { headers, ...rest } = error;
4422
5132
  return new Response(JSON.stringify(rest), {
@@ -4982,9 +5692,9 @@ var getBaseManifest = getProdBaseManifest;
4982
5692
  var createEarlyHintsForRequest = createEarlyHintsCollector;
4983
5693
  async function loadEntries() {
4984
5694
  const [routerEntry, startEntry, pluginAdapters] = await Promise.all([
4985
- import("./router-C437aaqv-72HBLLJI.js").then((n) => n.t),
4986
- import("./start-QK6aG02q-EMREW2SB.js"),
4987
- import("./empty-plugin-adapters-Cqtvkauv-ILKI7W7V.js")
5695
+ import("./router-UgU5vJxm-R33FGTXY.js").then((n) => n.t),
5696
+ import("./start-DEejK9Uj-FODAOTAO.js"),
5697
+ import("./empty-plugin-adapters-DOl-E2pL-RKRSN75W.js")
4988
5698
  ]);
4989
5699
  return {
4990
5700
  routerEntry,
@@ -5009,65 +5719,76 @@ function throwRouteHandlerError() {
5009
5719
  function throwIfMayNotDefer() {
5010
5720
  throw new Error(ERR_NO_DEFER);
5011
5721
  }
5012
- function isSpecialResponse(value) {
5013
- return value instanceof Response || isRedirect(value);
5722
+ function getResponseFromResult(result) {
5723
+ return isSsrResponse(result) || result instanceof Response ? result : result?.response;
5014
5724
  }
5015
- function handleCtxResult(result) {
5016
- if (isSsrResponse(result) || isSpecialResponse(result)) return { response: result };
5017
- return result;
5725
+ var responseBodySources = /* @__PURE__ */ new WeakMap();
5726
+ function disposeResponseResult(result, reason) {
5727
+ const response = getResponseFromResult(result);
5728
+ if (isSsrResponse(response) || response instanceof Response) disposeSsrResponse(response, reason);
5729
+ }
5730
+ function hasResponseBody(value) {
5731
+ return value instanceof Response && value.body !== null;
5732
+ }
5733
+ function inheritsResponseOwnership(ownership, candidate) {
5734
+ return hasResponseBody(candidate) && (candidate.body === ownership.response.body || responseBodySources.get(candidate) === ownership.response);
5018
5735
  }
5019
- function disposeLateResponse(result, signal) {
5020
- const response = handleCtxResult(result)?.response;
5021
- if (isSsrResponse(response) || isSpecialResponse(response)) disposeSsrResponseDetached(response, signal.reason);
5736
+ function disposeResponseOwnership(ownership, reason) {
5737
+ const { response, sourceBody, streamResponse } = ownership;
5738
+ streamResponse?.dispose(reason);
5739
+ if (!streamResponse || response.body !== sourceBody) response.body.cancel(reason).catch(() => {
5740
+ });
5741
+ }
5742
+ function getOwnedResponse(ownership) {
5743
+ const { response, sourceBody, streamResponse } = ownership;
5744
+ if (!streamResponse) return response;
5745
+ if (streamResponse.response === response && response.body === sourceBody) return streamResponse;
5746
+ if (response.body === sourceBody) return {
5747
+ ...streamResponse,
5748
+ response
5749
+ };
5750
+ return {
5751
+ ...streamResponse,
5752
+ response,
5753
+ dispose(reason) {
5754
+ disposeResponseOwnership(ownership, reason);
5755
+ }
5756
+ };
5022
5757
  }
5023
- function isSignalAborted(signal) {
5024
- return signal.aborted;
5758
+ function createLateResponseDisposer(signal) {
5759
+ return (result) => disposeResponseResult(result, signal.reason);
5025
5760
  }
5026
- async function executeMiddleware(middlewares, ctx, signal) {
5761
+ async function executeMiddleware(middlewares, terminal, ctx, signal, terminalNext) {
5027
5762
  let index = -1;
5028
- let streamResponse;
5029
- let retiredStreamIdentities;
5030
- const isResponseAlias = (candidate, response) => candidate === response || candidate instanceof Response && response.body !== null && candidate.body === response.body;
5763
+ let responseOwnership;
5764
+ let settled = false;
5765
+ const disposeAbandonedResult = createLateResponseDisposer(signal);
5031
5766
  const setResponse = (response) => {
5032
- if (isSsrResponse(response)) {
5033
- if (response.serverSsrCleanup === "stream") streamResponse = response;
5034
- ctx.response = response.response;
5767
+ const ssrResponse = isSsrResponse(response) ? response : void 0;
5768
+ const streamResponse = ssrResponse?.serverSsrCleanup === "stream" ? ssrResponse : void 0;
5769
+ const exposed = ssrResponse ? ssrResponse.response : response;
5770
+ const current = responseOwnership;
5771
+ if (settled) {
5772
+ if (exposed !== ctx.response) disposeResponseResult(response, "late middleware response");
5035
5773
  return;
5036
5774
  }
5037
- ctx.response = response;
5038
- };
5039
- const disposeStreamResponse = async (reason) => {
5040
- const response = streamResponse;
5041
- if (!response) return;
5042
- streamResponse = void 0;
5043
- retiredStreamIdentities ??= /* @__PURE__ */ new WeakSet();
5044
- retiredStreamIdentities.add(response.response);
5045
- if (response.response.body) retiredStreamIdentities.add(response.response.body);
5046
- const currentResponse = ctx.response;
5047
- if (isResponseAlias(currentResponse, response.response)) ctx.response = void 0;
5048
- await response.dispose(reason);
5049
- };
5050
- const disposeAbandonedResult = (result) => {
5051
- const exposed = handleCtxResult(result)?.response;
5052
- const response = isSsrResponse(exposed) ? exposed.response : exposed;
5053
- if (streamResponse && isResponseAlias(response, streamResponse.response)) {
5054
- disposeStreamResponse(signal.reason).catch(console.error);
5055
- return;
5775
+ if (current && current.response === exposed) current.streamResponse ??= streamResponse;
5776
+ else if (current && inheritsResponseOwnership(current, exposed)) {
5777
+ current.response = exposed;
5778
+ current.streamResponse ??= streamResponse;
5779
+ } else {
5780
+ if (current) disposeResponseOwnership(current, "middleware response replaced");
5781
+ if (hasResponseBody(exposed)) responseOwnership = {
5782
+ response: exposed,
5783
+ sourceBody: exposed.body,
5784
+ streamResponse
5785
+ };
5786
+ else responseOwnership = void 0;
5056
5787
  }
5057
- if (response instanceof Response && retiredStreamIdentities && (retiredStreamIdentities.has(response) || response.body !== null && retiredStreamIdentities.has(response.body))) return;
5058
- disposeLateResponse(result, signal);
5788
+ ctx.response = exposed;
5059
5789
  };
5060
- const getFinalResponse = async () => {
5061
- const response = ctx.response;
5062
- if (!response) throwRouteHandlerError();
5063
- if (!streamResponse) return response;
5064
- if (response === streamResponse.response) return streamResponse;
5065
- if (streamResponse.response.body !== null && response.body === streamResponse.response.body) return {
5066
- ...streamResponse,
5067
- response
5068
- };
5069
- await disposeStreamResponse("middleware response replaced");
5070
- return response;
5790
+ const reconcileCtxResponse = () => {
5791
+ if (ctx.response !== responseOwnership?.response) setResponse(ctx.response);
5071
5792
  };
5072
5793
  let nextPromise;
5073
5794
  function next(nextCtx) {
@@ -5076,73 +5797,68 @@ async function executeMiddleware(middlewares, ctx, signal) {
5076
5797
  return result;
5077
5798
  }
5078
5799
  async function runNext(nextCtx) {
5079
- if (signal.aborted) throw signal.reason;
5800
+ signal.throwIfAborted();
5080
5801
  if (nextCtx) {
5081
5802
  if (nextCtx.context) ctx.context = safeObjectMerge(ctx.context, nextCtx.context);
5082
5803
  for (const key of Object.keys(nextCtx)) if (key === "response") setResponse(nextCtx.response);
5083
5804
  else if (key !== "context") ctx[key] = nextCtx[key];
5084
5805
  }
5085
5806
  index++;
5086
- const middleware = middlewares[index];
5807
+ const isTerminal = index === middlewares.length;
5808
+ const middleware = index < middlewares.length ? middlewares[index] : isTerminal ? terminal : void 0;
5809
+ const middlewareNext = isTerminal && terminalNext ? terminalNext : next;
5087
5810
  if (!middleware) return ctx;
5088
5811
  let result;
5089
5812
  try {
5090
5813
  const pending = middleware({
5091
5814
  ...ctx,
5092
- next
5815
+ next: middlewareNext
5093
5816
  });
5094
- if (pending === nextPromise) {
5817
+ if (nextPromise && pending === nextPromise) {
5095
5818
  nextPromise = void 0;
5096
- result = await pending;
5097
- if (isSignalAborted(signal)) {
5098
- disposeAbandonedResult(result);
5099
- throw signal.reason;
5100
- }
5101
- } else result = await waitForRequest(pending, signal, disposeAbandonedResult);
5819
+ await pending;
5820
+ if (signal.aborted) throw signal.reason;
5821
+ return ctx;
5822
+ } else if (!isPromise(pending)) {
5823
+ result = pending;
5824
+ signal.throwIfAborted();
5825
+ } else result = await waitForReason(pending, signal, disposeAbandonedResult, disposeAbandonedResult);
5102
5826
  } catch (err) {
5103
- if (isSignalAborted(signal)) throw signal.reason;
5104
- if (isSpecialResponse(err)) {
5827
+ reconcileCtxResponse();
5828
+ if (signal.aborted) {
5829
+ if (result !== void 0) disposeAbandonedResult(result);
5830
+ if (err !== signal.reason) disposeAbandonedResult(err);
5831
+ throw signal.reason;
5832
+ }
5833
+ if (err instanceof Response) {
5105
5834
  setResponse(err);
5106
5835
  return ctx;
5107
5836
  }
5108
5837
  throw err;
5109
5838
  }
5110
- const normalized = handleCtxResult(result);
5111
- if (normalized) {
5112
- if (normalized.response !== void 0) setResponse(normalized.response);
5113
- if (normalized.context) ctx.context = safeObjectMerge(ctx.context, normalized.context);
5839
+ if (isTerminal && terminalNext && !result) throwRouteHandlerError();
5840
+ reconcileCtxResponse();
5841
+ if (result && result !== ctx) {
5842
+ const response = getResponseFromResult(result);
5843
+ if (response !== void 0 && response !== ctx.response) setResponse(response);
5844
+ if (response !== result && result.context && result.context !== ctx.context) ctx.context = safeObjectMerge(ctx.context, result.context);
5114
5845
  }
5115
5846
  return ctx;
5116
5847
  }
5117
5848
  try {
5118
5849
  await runNext();
5119
- const response = await waitForRequest(getFinalResponse(), signal, disposeAbandonedResult);
5120
- if (signal.aborted) {
5121
- disposeAbandonedResult(response);
5122
- throw signal.reason;
5123
- }
5124
- return {
5125
- ctx,
5126
- response
5127
- };
5850
+ const response = ctx.response;
5851
+ if (!response) throwRouteHandlerError();
5852
+ reconcileCtxResponse();
5853
+ if (signal.aborted) throw signal.reason;
5854
+ settled = true;
5855
+ return responseOwnership ? getOwnedResponse(responseOwnership) : response;
5128
5856
  } catch (err) {
5129
- const disposal = disposeStreamResponse(signal.aborted ? signal.reason : err);
5130
- if (signal.aborted) disposal.catch(console.error);
5131
- else await disposal;
5857
+ settled = true;
5858
+ if (responseOwnership) disposeResponseOwnership(responseOwnership, signal.aborted ? signal.reason : err);
5132
5859
  throw err;
5133
5860
  }
5134
5861
  }
5135
- function handlerToMiddleware(handler, mayDefer = false) {
5136
- if (mayDefer) return handler;
5137
- return async (ctx) => {
5138
- const response = await handler({
5139
- ...ctx,
5140
- next: throwIfMayNotDefer
5141
- });
5142
- if (!response) throwRouteHandlerError();
5143
- return response;
5144
- };
5145
- }
5146
5862
  function createStartHandler(cbOrOptions) {
5147
5863
  const handlerOptions = typeof cbOrOptions === "function" ? {} : cbOrOptions;
5148
5864
  const cb = typeof cbOrOptions === "function" ? cbOrOptions : cbOrOptions.handler;
@@ -5153,17 +5869,25 @@ function createStartHandler(cbOrOptions) {
5153
5869
  const resolveManifestForRequest = finalManifestResolver.resolveCached;
5154
5870
  finalManifestResolver.warmup({ getBaseManifest: () => getBaseManifest(void 0) });
5155
5871
  const startRequestResolver = async (request, requestOpts) => {
5156
- let router = null;
5872
+ const signal = request.signal;
5873
+ let router;
5874
+ let routerPromise;
5157
5875
  let responseOwnsCleanup = false;
5158
5876
  try {
5159
- request.signal.throwIfAborted();
5877
+ signal.throwIfAborted();
5160
5878
  const { url, handledProtocolRelativeURL } = getNormalizedURL(request.url);
5161
5879
  const href = url.pathname + url.search + url.hash;
5162
- const origin = getOrigin(request);
5880
+ const origin = url.origin;
5163
5881
  if (handledProtocolRelativeURL) return Response.redirect(url, 308);
5164
- const entries = await waitForRequest(getEntries(), request.signal);
5165
- const hasStartInstance = !!entries.startEntry.startInstance;
5166
- const startOptions = await waitForRequest(entries.startEntry.startInstance?.getOptions(), request.signal) || {};
5882
+ const entries = await waitForReason(getEntries(), signal);
5883
+ const isServerFnRequest = !!SERVER_FN_BASE && url.pathname.startsWith(SERVER_FN_BASE);
5884
+ const startInstance = entries.startEntry.startInstance;
5885
+ let startOptions;
5886
+ if (startInstance) {
5887
+ const pendingStartOptions = startInstance.getOptions();
5888
+ startOptions = isPromise(pendingStartOptions) ? await waitForReason(pendingStartOptions, signal) : pendingStartOptions;
5889
+ signal.throwIfAborted();
5890
+ } else startOptions = {};
5167
5891
  const { hasPluginAdapters, pluginSerializationAdapters } = entries.pluginAdapters;
5168
5892
  const serializationAdapters = [
5169
5893
  ...startOptions.serializationAdapters || [],
@@ -5172,165 +5896,179 @@ function createStartHandler(cbOrOptions) {
5172
5896
  ];
5173
5897
  const requestStartOptions = {
5174
5898
  ...startOptions,
5175
- requestMiddleware: hasStartInstance ? startOptions.requestMiddleware : [defaultCsrfMiddleware],
5899
+ requestMiddleware: startInstance ? startOptions.requestMiddleware : isServerFnRequest ? [defaultCsrfMiddleware] : void 0,
5176
5900
  serializationAdapters
5177
5901
  };
5178
5902
  const flattenedRequestMiddlewares = requestStartOptions.requestMiddleware ? flattenMiddlewares(requestStartOptions.requestMiddleware) : [];
5179
5903
  const executedRequestMiddlewares = new Set(flattenedRequestMiddlewares);
5180
- const getRouter = async () => {
5181
- if (router) return router;
5182
- router = await waitForRequest(entries.routerEntry.getRouter(), request.signal);
5183
- let isShell = IS_SHELL_ENV;
5184
- if (IS_PRERENDERING && !isShell) isShell = request.headers.get(HEADERS.TSS_SHELL) === "true";
5185
- const history = createMemoryHistory({ initialEntries: [href] });
5186
- router.update({
5187
- history,
5188
- isShell,
5189
- isPrerendering: IS_PRERENDERING,
5190
- origin: router.options.origin ?? origin,
5191
- defaultSsr: requestStartOptions.defaultSsr,
5192
- serializationAdapters: [...requestStartOptions.serializationAdapters, ...router.options.serializationAdapters || []],
5193
- basepath: ROUTER_BASEPATH
5194
- });
5195
- return router;
5904
+ const getRouter = () => {
5905
+ routerPromise ??= (async () => {
5906
+ signal.throwIfAborted();
5907
+ const requestRouter = await waitForReason(entries.routerEntry.getRouter(), signal);
5908
+ let isShell = IS_SHELL_ENV;
5909
+ if (IS_PRERENDERING && !isShell) isShell = request.headers.get(HEADERS.TSS_SHELL) === "true";
5910
+ const history = createServerHistory(href);
5911
+ requestRouter.update({
5912
+ history,
5913
+ isShell,
5914
+ isPrerendering: IS_PRERENDERING,
5915
+ origin: requestRouter.options.origin ?? origin,
5916
+ defaultSsr: requestStartOptions.defaultSsr,
5917
+ serializationAdapters: [...requestStartOptions.serializationAdapters, ...requestRouter.options.serializationAdapters || []],
5918
+ basepath: ROUTER_BASEPATH
5919
+ });
5920
+ router = requestRouter;
5921
+ return requestRouter;
5922
+ })();
5923
+ return routerPromise;
5196
5924
  };
5197
- if (SERVER_FN_BASE && url.pathname.startsWith(SERVER_FN_BASE)) {
5925
+ const handlerType = isServerFnRequest ? "serverFn" : "router";
5926
+ const startContext = {
5927
+ getRouter,
5928
+ startOptions: requestStartOptions,
5929
+ request,
5930
+ executedRequestMiddlewares,
5931
+ handlerType
5932
+ };
5933
+ let terminal;
5934
+ if (isServerFnRequest) {
5198
5935
  const serverFnId = url.pathname.slice(SERVER_FN_BASE.length).split("/")[0];
5199
5936
  if (!serverFnId) throw new Error("Invalid server action param for serverFnId");
5200
- const serverFnHandler = async ({ context }) => {
5201
- return runWithStartContext({
5202
- getRouter,
5203
- startOptions: requestStartOptions,
5204
- contextAfterGlobalMiddlewares: context,
5937
+ terminal = ({ context }) => runWithStartContext({
5938
+ ...startContext,
5939
+ contextAfterGlobalMiddlewares: context
5940
+ }, () => handleServerAction({
5941
+ request,
5942
+ context: requestOpts?.context,
5943
+ serverFnId
5944
+ }));
5945
+ } else {
5946
+ const executeRouter = async (serverContext, matchedRoutes) => {
5947
+ if (!/(^|,)\s*(\*\/\*|text\/html)/.test(request.headers.get("Accept") || "*/*")) return normalizeSsrResponse(Response.json({ error: "Only HTML requests are supported here" }, { status: 406 }));
5948
+ const manifest2 = await waitForReason(resolveManifestForRequest({
5205
5949
  request,
5206
- executedRequestMiddlewares,
5207
- handlerType: "serverFn"
5208
- }, () => handleServerAction({
5950
+ requestInlineCss: requestOpts?.inlineCss,
5951
+ getBaseManifest: () => getBaseManifest(matchedRoutes)
5952
+ }), signal);
5953
+ const earlyHints = createEarlyHintsForRequest({
5954
+ onEarlyHints: requestOpts?.onEarlyHints,
5955
+ responseLinkHeader: requestOpts?.responseLinkHeader
5956
+ });
5957
+ earlyHints?.collectStatic({
5958
+ manifest: manifest2,
5959
+ matchedRoutes
5960
+ });
5961
+ const routerInstance = await getRouter();
5962
+ attachRouterServerSsrUtils({
5963
+ router: routerInstance,
5964
+ manifest: manifest2,
5965
+ getRequestAssets: () => getStartContext({ throwIfNotFound: false })?.requestAssets
5966
+ });
5967
+ routerInstance.options.additionalContext = { serverContext };
5968
+ await routerInstance.load({ _signal: signal });
5969
+ signal.throwIfAborted();
5970
+ if (routerInstance._serverResult?.type === "redirect") return normalizeSsrResponse(routerInstance._serverResult.redirect);
5971
+ earlyHints?.collectDynamic(_getRenderedMatches(routerInstance.stores.matches.get()));
5972
+ const ctx = getStartContext({ throwIfNotFound: false });
5973
+ await routerInstance.serverSsr.dehydrate({
5974
+ requestAssets: ctx?.requestAssets,
5975
+ signal
5976
+ });
5977
+ signal.throwIfAborted();
5978
+ const responseHeaders = getStartResponseHeaders({ router: routerInstance });
5979
+ earlyHints?.appendResponseHeaders(responseHeaders);
5980
+ signal.throwIfAborted();
5981
+ const disposeLate = createLateResponseDisposer(signal);
5982
+ return normalizeSsrResponse(await waitForReason(cb({
5209
5983
  request,
5210
- context: requestOpts?.context,
5211
- serverFnId
5212
- }));
5984
+ router: routerInstance,
5985
+ responseHeaders
5986
+ }), signal, disposeLate, disposeLate));
5213
5987
  };
5214
- const { response: middlewareResponse2 } = await executeMiddleware([...flattenedRequestMiddlewares.map((d) => d.options.server), serverFnHandler], {
5215
- request,
5216
- pathname: url.pathname,
5217
- handlerType: "serverFn",
5218
- context: createNullProtoObject(requestOpts?.context)
5219
- }, request.signal);
5220
- const result = await handleRedirectResponse(middlewareResponse2, request, getRouter, request.signal);
5221
- bindSsrResponseToRequest(router ?? void 0, result, request.signal);
5222
- request.signal.throwIfAborted();
5223
- responseOwnsCleanup = result.serverSsrCleanup === "stream";
5224
- return result.response;
5225
- }
5226
- const executeRouter = async (serverContext, matchedRoutes) => {
5227
- const acceptParts = (request.headers.get("Accept") || "*/*").split(",");
5228
- if (!["*/*", "text/html"].some((mimeType) => acceptParts.some((part) => part.trim().startsWith(mimeType)))) return normalizeSsrResponse(Response.json({ error: "Only HTML requests are supported here" }, { status: 500 }));
5229
- const manifest2 = await waitForRequest(resolveManifestForRequest({
5230
- request,
5231
- requestInlineCss: requestOpts?.inlineCss,
5232
- getBaseManifest: () => getBaseManifest(matchedRoutes)
5233
- }), request.signal);
5234
- const earlyHints = createEarlyHintsForRequest({
5235
- onEarlyHints: requestOpts?.onEarlyHints,
5236
- responseLinkHeader: requestOpts?.responseLinkHeader
5237
- });
5238
- earlyHints?.collectStatic({
5239
- manifest: manifest2,
5240
- matchedRoutes
5241
- });
5242
- const routerInstance = await getRouter();
5243
- attachRouterServerSsrUtils({
5244
- router: routerInstance,
5245
- manifest: manifest2,
5246
- getRequestAssets: () => getStartContext({ throwIfNotFound: false })?.requestAssets
5247
- });
5248
- routerInstance.options.additionalContext = { serverContext };
5249
- await routerInstance.load({ _signal: request.signal });
5250
- request.signal.throwIfAborted();
5251
- if (routerInstance._serverResult?.type === "redirect") return normalizeSsrResponse(routerInstance._serverResult.redirect);
5252
- earlyHints?.collectDynamic(_getRenderedMatches(routerInstance.stores.matches.get()));
5253
- const ctx = getStartContext({ throwIfNotFound: false });
5254
- await waitForRequest(routerInstance.serverSsr.dehydrate({ requestAssets: ctx?.requestAssets }), request.signal);
5255
- request.signal.throwIfAborted();
5256
- const responseHeaders = getStartResponseHeaders({ router: routerInstance });
5257
- earlyHints?.appendResponseHeaders(responseHeaders);
5258
- request.signal.throwIfAborted();
5259
- return normalizeSsrResponse(await waitForRequest(cb({
5260
- request,
5261
- router: routerInstance,
5262
- responseHeaders
5263
- }), request.signal, (late) => disposeLateResponse(late, request.signal)));
5264
- };
5265
- const requestHandlerMiddleware = async ({ context }) => {
5266
- return runWithStartContext({
5988
+ terminal = ({ context }) => runWithStartContext({
5989
+ ...startContext,
5990
+ contextAfterGlobalMiddlewares: context
5991
+ }, () => handleServerRoutes({
5267
5992
  getRouter,
5268
- startOptions: requestStartOptions,
5269
- contextAfterGlobalMiddlewares: context,
5270
5993
  request,
5271
- executedRequestMiddlewares,
5272
- handlerType: "router"
5273
- }, async () => {
5274
- try {
5275
- return await handleServerRoutes({
5276
- getRouter,
5277
- request,
5278
- url,
5279
- executeRouter,
5280
- context,
5281
- executedRequestMiddlewares
5282
- });
5283
- } catch (err) {
5284
- if (err instanceof Response) return err;
5285
- throw err;
5286
- }
5287
- });
5288
- };
5289
- const { response: middlewareResponse } = await executeMiddleware([...flattenedRequestMiddlewares.map((d) => d.options.server), requestHandlerMiddleware], {
5994
+ url,
5995
+ executeRouter,
5996
+ context,
5997
+ executedRequestMiddlewares
5998
+ }));
5999
+ }
6000
+ const middlewareResponse = await executeMiddleware(flattenedRequestMiddlewares.map((d) => d.options.server), terminal, {
5290
6001
  request,
5291
6002
  pathname: url.pathname,
5292
- handlerType: "router",
6003
+ handlerType,
5293
6004
  context: createNullProtoObject(requestOpts?.context)
5294
- }, request.signal);
5295
- const response = await handleRedirectResponse(middlewareResponse, request, getRouter, request.signal);
5296
- bindSsrResponseToRequest(router ?? void 0, response, request.signal);
5297
- request.signal.throwIfAborted();
5298
- responseOwnsCleanup = response.serverSsrCleanup === "stream";
5299
- return response.response;
6005
+ }, signal);
6006
+ let result;
6007
+ try {
6008
+ result = await handleRedirectResponse(middlewareResponse, getRouter, signal, isServerFnRequest && request.headers.get("x-tsr-serverFn") === "true");
6009
+ if (request.method === "HEAD") result = stripSsrResponseBody(result, "HEAD body stripped");
6010
+ } catch (error) {
6011
+ disposeResponseResult(middlewareResponse, signal.aborted ? signal.reason : error);
6012
+ throw error;
6013
+ }
6014
+ bindSsrResponseToRequest(router, result, signal);
6015
+ signal.throwIfAborted();
6016
+ responseOwnsCleanup = result.serverSsrCleanup === "stream";
6017
+ return result.response;
5300
6018
  } finally {
5301
6019
  if (router?.serverSsr && !responseOwnsCleanup) router.serverSsr.cleanup();
5302
- router = null;
5303
6020
  }
5304
6021
  };
5305
6022
  return requestHandler(startRequestResolver);
5306
6023
  }
5307
- async function handleRedirectResponse(response, request, getRouter, signal) {
6024
+ var relativeRedirectProtocols = /* @__PURE__ */ new Set();
6025
+ async function handleRedirectResponse(response, getRouter, signal, serializeRedirect) {
5308
6026
  signal.throwIfAborted();
5309
6027
  const ssrResponse = normalizeSsrResponse(response);
5310
- if (!isRedirect(ssrResponse.response)) return ssrResponse;
5311
- if (isResolvedRedirect(ssrResponse.response)) {
5312
- if (request.headers.get("x-tsr-serverFn") === "true") return waitForRequest(replaceSsrResponse(ssrResponse, Response.json({
5313
- ...ssrResponse.response.options,
5314
- isSerializedRedirect: true
5315
- }, { headers: ssrResponse.response.headers }), "redirect response replaced"), signal);
5316
- return ssrResponse;
5317
- }
5318
- const opts = ssrResponse.response.options;
5319
- if (opts.to && typeof opts.to === "string" && !opts.to.startsWith("/")) throw new Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(opts)}`);
5320
- if ([
6028
+ const redirect = ssrResponse.response;
6029
+ if (!isRedirect(redirect)) return ssrResponse;
6030
+ const opts = redirect.options;
6031
+ const href = redirect.headers.get("Location") || opts.href;
6032
+ if (!href && opts.to && typeof opts.to === "string" && !opts.to.startsWith("/")) throw new Error(`Server side redirects must use absolute paths via the 'href' or 'to' options. The redirect() method's "to" property accepts an internal path only. Use the "href" property to provide an external URL. Received: ${JSON.stringify(opts)}`);
6033
+ if (!href && [
5321
6034
  "params",
5322
6035
  "search",
5323
6036
  "hash"
5324
6037
  ].some((d) => typeof opts[d] === "function")) throw new Error(`Server side redirects must use static search, params, and hash values and do not support functional values. Received functional values for: ${Object.keys(opts).filter((d) => typeof opts[d] === "function").map((d) => `"${d}"`).join(", ")}`);
5325
6038
  signal.throwIfAborted();
5326
- const router = await waitForRequest(getRouter(), signal);
5327
- signal.throwIfAborted();
5328
- const redirect = router.resolveRedirect(ssrResponse.response);
5329
- if (request.headers.get("x-tsr-serverFn") === "true") return waitForRequest(replaceSsrResponse(ssrResponse, Response.json({
5330
- ...ssrResponse.response.options,
5331
- isSerializedRedirect: true
5332
- }, { headers: ssrResponse.response.headers }), "redirect response replaced"), signal);
5333
- return waitForRequest(replaceSsrResponse(ssrResponse, redirect, "redirect response replaced"), signal);
6039
+ if (href && !isDangerousProtocol(href, relativeRedirectProtocols)) {
6040
+ opts.href = href;
6041
+ redirect.headers.set("Location", href);
6042
+ } else {
6043
+ const router = await getRouter();
6044
+ signal.throwIfAborted();
6045
+ router.resolveRedirect(redirect);
6046
+ }
6047
+ if (serializeRedirect) {
6048
+ const redirectOptions = { ...opts };
6049
+ delete redirectOptions.headers;
6050
+ const responseHeaders = new Headers(redirect.headers);
6051
+ responseHeaders.set("content-type", "application/json");
6052
+ return replaceSsrResponse(ssrResponse, Response.json({
6053
+ ...redirectOptions,
6054
+ isSerializedRedirect: true
6055
+ }, { headers: responseHeaders }), "redirect response replaced");
6056
+ }
6057
+ return ssrResponse;
6058
+ }
6059
+ function withParsedParams(handler, matchedRoutes) {
6060
+ if (!matchedRoutes.some((route) => route.options.params?.parse ?? route.options.parseParams)) return handler;
6061
+ return (ctx) => {
6062
+ const params = Object.assign(/* @__PURE__ */ Object.create(null), ctx.params);
6063
+ for (const route of matchedRoutes) {
6064
+ const parse = route.options.params?.parse ?? route.options.parseParams;
6065
+ if (parse) Object.assign(params, parse(params));
6066
+ }
6067
+ return handler({
6068
+ ...ctx,
6069
+ params
6070
+ });
6071
+ };
5334
6072
  }
5335
6073
  async function handleServerRoutes({ getRouter, request, url, executeRouter, context, executedRequestMiddlewares }) {
5336
6074
  const router = await getRouter();
@@ -5338,6 +6076,8 @@ async function handleServerRoutes({ getRouter, request, url, executeRouter, cont
5338
6076
  const [matchedRoutes, rawParams, foundRoute] = router.getMatchedRoutes(pathname);
5339
6077
  const isExactMatch = foundRoute && rawParams["**"] === void 0;
5340
6078
  const routeMiddlewares = [];
6079
+ let terminalHandler = (ctx) => executeRouter(ctx.context, matchedRoutes);
6080
+ let terminalNext;
5341
6081
  for (const route of matchedRoutes) {
5342
6082
  const serverMiddleware = route.options.server?.middleware;
5343
6083
  if (serverMiddleware) {
@@ -5346,37 +6086,35 @@ async function handleServerRoutes({ getRouter, request, url, executeRouter, cont
5346
6086
  }
5347
6087
  }
5348
6088
  const server = foundRoute?.options.server;
5349
- let isHeadFallback = false;
5350
6089
  if (server?.handlers && isExactMatch) {
5351
6090
  const handlers = typeof server.handlers === "function" ? server.handlers({ createHandlers: (d) => d }) : server.handlers;
5352
6091
  const requestMethod = request.method.toUpperCase();
5353
6092
  const handler = requestMethod === "HEAD" ? handlers["HEAD"] ?? handlers["GET"] ?? handlers["ANY"] : handlers[requestMethod] ?? handlers["ANY"];
5354
- isHeadFallback = requestMethod === "HEAD" && handler !== void 0 && !handlers["HEAD"];
5355
6093
  if (handler) {
5356
6094
  const mayDefer = !!foundRoute.options.component;
5357
- if (typeof handler === "function") routeMiddlewares.push(handlerToMiddleware(handler, mayDefer));
5358
- else {
6095
+ if (typeof handler !== "function") {
5359
6096
  if (handler.middleware?.length) {
5360
6097
  const handlerMiddlewares = flattenMiddlewares(handler.middleware);
5361
6098
  for (const m of handlerMiddlewares) routeMiddlewares.push(m.options.server);
5362
6099
  }
5363
- if (handler.handler) routeMiddlewares.push(handlerToMiddleware(handler.handler, mayDefer));
6100
+ }
6101
+ const routeHandler = typeof handler === "function" ? handler : handler.handler;
6102
+ if (routeHandler) {
6103
+ const parsedHandler = withParsedParams(routeHandler, matchedRoutes);
6104
+ if (!mayDefer) {
6105
+ terminalHandler = parsedHandler;
6106
+ terminalNext = throwIfMayNotDefer;
6107
+ } else routeMiddlewares.push(parsedHandler);
5364
6108
  }
5365
6109
  }
5366
6110
  }
5367
- routeMiddlewares.push(((ctx2) => executeRouter(ctx2.context, matchedRoutes)));
5368
- const { ctx, response } = await executeMiddleware(routeMiddlewares, {
6111
+ return normalizeSsrResponse(await executeMiddleware(routeMiddlewares, terminalHandler, {
5369
6112
  request,
5370
6113
  context,
5371
6114
  params: rawParams,
5372
6115
  pathname,
5373
6116
  handlerType: "router"
5374
- }, request.signal);
5375
- if (isHeadFallback) {
5376
- if (!ctx.response) throwRouteHandlerError();
5377
- return waitForRequest(stripSsrResponseBody(await handleRedirectResponse(response, request, getRouter, request.signal), "HEAD body stripped"), request.signal);
5378
- }
5379
- return normalizeSsrResponse(response);
6117
+ }, request.signal, terminalNext));
5380
6118
  }
5381
6119
  var fetch$1 = createStartHandler(defaultStreamHandler);
5382
6120
  function createServerEntry(entry) {