@solidjs/web 2.0.0-rc.8 → 2.0.0-rc.9

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 (36) hide show
  1. package/dist/server.dev.js +626 -125
  2. package/dist/server.js +433 -95
  3. package/dist/server.observe.js +3980 -0
  4. package/dist/web.dev.js +208 -60
  5. package/dist/web.js +175 -58
  6. package/dist/web.observe.js +175 -58
  7. package/frames/dist/client.dev.js +103 -4
  8. package/frames/dist/client.js +5 -2
  9. package/frames/dist/client.observe.js +2123 -0
  10. package/frames/dist/server.dev.js +521 -79
  11. package/frames/dist/server.js +352 -52
  12. package/frames/dist/server.observe.js +4946 -0
  13. package/frames/package.json +12 -0
  14. package/package.json +87 -3
  15. package/server-functions/dist/client.dev.js +1102 -0
  16. package/server-functions/dist/client.js +74 -69
  17. package/server-functions/dist/client.observe.js +1102 -0
  18. package/server-functions/dist/server.dev.js +402 -31
  19. package/server-functions/dist/server.js +339 -30
  20. package/server-functions/dist/server.observe.js +2726 -0
  21. package/server-functions/package.json +12 -0
  22. package/types/client.d.ts +22 -1
  23. package/types/diagnostics.d.ts +24 -0
  24. package/types/frames/frame-transport.d.ts +1 -1
  25. package/types/index.d.ts +25 -15
  26. package/types/index.server.d.ts +35 -8
  27. package/types/jsx.d.ts +15 -4
  28. package/types/observe.d.ts +294 -0
  29. package/types/response.d.ts +18 -0
  30. package/types/server-functions/client.d.ts +32 -22
  31. package/types/server-functions/server.d.ts +28 -37
  32. package/types/server-functions/shared.d.ts +39 -9
  33. package/types/server-mock.d.ts +26 -4
  34. package/types/server-observe.d.ts +39 -0
  35. package/types/server.d.ts +104 -5
  36. package/types/trace.d.ts +79 -0
@@ -0,0 +1,4946 @@
1
+ import { reportServerError, ssrHandleError, ssrSanitizeError, inServerComponentScope, creationStamp, runInServerComponentScope, getProjectionTrace } from 'solid-js/internal';
2
+ import { OBSERVE, getOwner, sharedConfig, createRoot, runWithOwner, NoHydration, createMemo, Hydration, createOwner } from 'solid-js';
3
+ import { Feature, createStream, toCrossJSONStream, Serializer, getCrossReferenceHeader } from 'seroval';
4
+ import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
5
+
6
+ const STATE = Symbol.for("solid.container-trace-state");
7
+ const state = globalThis[STATE] || (globalThis[STATE] = {
8
+ materialized: new WeakMap(),
9
+ materializedValues: new WeakSet()
10
+ });
11
+ function setContainerTraceResolver(fn) {
12
+ state.resolveTrace = fn;
13
+ }
14
+ function setContainerTraceStreamMint(fn) {
15
+ state.streamOf = fn;
16
+ }
17
+ function isContainerTraced(value) {
18
+ const resolve = state.resolveTrace;
19
+ return !!(resolve && value && typeof value === "object" && resolve(value));
20
+ }
21
+ const TRACE = Symbol.for("solid.container-trace");
22
+ function envelopeContainerTraces(value) {
23
+ if (!state.resolveTrace || value == null || typeof value !== "object") return value;
24
+ const trace = state.resolveTrace(value);
25
+ if (trace) return {
26
+ [TRACE]: trace
27
+ };
28
+ if (Array.isArray(value)) {
29
+ let out = value;
30
+ for (let i = 0; i < value.length; i++) {
31
+ const next = envelopeContainerTraces(value[i]);
32
+ if (next !== value[i]) {
33
+ if (out === value) out = value.slice();
34
+ out[i] = next;
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ if (Object.getPrototypeOf(value) === Object.prototype) {
40
+ let out = value;
41
+ for (const key of Object.keys(value)) {
42
+ const next = envelopeContainerTraces(value[key]);
43
+ if (next !== value[key]) {
44
+ if (out === value) out = {
45
+ ...value
46
+ };
47
+ out[key] = next;
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ return value;
53
+ }
54
+ function materialize(marker) {
55
+ let value = state.materialized.get(marker.$tr);
56
+ if (value === undefined) {
57
+ value = state.materializeTrace(marker);
58
+ state.materialized.set(marker.$tr, value);
59
+ if (value !== null && typeof value === "object") state.materializedValues.add(value);
60
+ }
61
+ return value;
62
+ }
63
+ function parseTrace(value, ctx) {
64
+ const trace = value[TRACE];
65
+ const sub = trace.subscribe();
66
+ return {
67
+ a: trace.array ? 1 : 0,
68
+ i: ctx.parse(state.streamOf ? state.streamOf(sub) : sub)
69
+ };
70
+ }
71
+ const ContainerTracePlugin = {
72
+ tag: "solid/container-trace",
73
+ test(value) {
74
+ return value != null && typeof value === "object" && TRACE in value;
75
+ },
76
+ parse: {
77
+ sync() {
78
+ throw new Error("A reactive container can only be serialized by a streaming serializer.");
79
+ },
80
+ async async(value, ctx) {
81
+ const trace = value[TRACE];
82
+ const sub = trace.subscribe();
83
+ return {
84
+ a: trace.array ? 1 : 0,
85
+ i: await ctx.parse(state.streamOf ? state.streamOf(sub) : sub)
86
+ };
87
+ },
88
+ stream: parseTrace
89
+ },
90
+ serialize(node, ctx) {
91
+ return "{$tr:" + ctx.serialize(node.i) + ",$ta:" + node.a + "}";
92
+ },
93
+ deserialize(node, ctx) {
94
+ const iterable = ctx.deserialize(node.i);
95
+ const marker = {
96
+ $tr: iterable,
97
+ $ta: node.a
98
+ };
99
+ return state.materializeTrace ? materialize(marker) : marker;
100
+ }
101
+ };
102
+
103
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
104
+
105
+ const PROVIDER = Symbol.for("solid-js/observe/server/provider");
106
+ function currentProvider() {
107
+ if (OBSERVE === undefined) return undefined;
108
+ const slot = OBSERVE.server.trace;
109
+ return slot && slot[PROVIDER];
110
+ }
111
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
112
+ const ZERO_TRACE = "00000000000000000000000000000000";
113
+ const ZERO_SPAN = "0000000000000000";
114
+ function parseTraceparent(value) {
115
+ if (!value) return undefined;
116
+ const m = TRACEPARENT.exec(value.trim());
117
+ if (!m) return undefined;
118
+ const [, version, traceId, parentId, flags, rest] = m;
119
+ if (version === "ff") return undefined;
120
+ if (version === "00" && rest !== undefined) return undefined;
121
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
122
+ return {
123
+ traceId,
124
+ parentId,
125
+ sampled: (parseInt(flags, 16) & 1) === 1
126
+ };
127
+ }
128
+ function randomHex(bytes) {
129
+ const buffer = new Uint8Array(bytes);
130
+ crypto.getRandomValues(buffer);
131
+ let out = "";
132
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
133
+ return out;
134
+ }
135
+ function randomTraceId() {
136
+ let id = randomHex(16);
137
+ while (id === ZERO_TRACE) id = randomHex(16);
138
+ return id;
139
+ }
140
+ function randomSpanId() {
141
+ let id = randomHex(8);
142
+ while (id === ZERO_SPAN) id = randomHex(8);
143
+ return id;
144
+ }
145
+ function formatTraceparent(context) {
146
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
147
+ }
148
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
149
+ function records$1() {
150
+ const g = globalThis;
151
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
152
+ }
153
+ function traceFor(key, request) {
154
+ const store = records$1();
155
+ let record = store.get(key);
156
+ if (record) return record;
157
+ const headers = request ? request.headers : undefined;
158
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
159
+ const context = {
160
+ traceId: incoming ? incoming.traceId : randomTraceId(),
161
+ spanId: randomSpanId(),
162
+ entries: {}
163
+ };
164
+ if (incoming) {
165
+ context.parentId = incoming.parentId;
166
+ context.sampled = incoming.sampled;
167
+ }
168
+ if (headers) {
169
+ const state = headers.get("tracestate");
170
+ if (state) context.state = state;
171
+ const baggage = headers.get("baggage");
172
+ if (baggage) context.baggage = baggage;
173
+ }
174
+ let answered = false;
175
+ let providedEntries;
176
+ {
177
+ const provider = currentProvider();
178
+ if (provider) {
179
+ let answer;
180
+ try {
181
+ answer = provider(request);
182
+ } catch (error) {
183
+ console.error(error);
184
+ }
185
+ if (answer !== undefined && answer !== null) {
186
+ answered = true;
187
+ if (answer.traceId !== undefined) context.traceId = answer.traceId;
188
+ if (answer.spanId !== undefined) context.spanId = answer.spanId;
189
+ if (answer.parentId !== undefined) context.parentId = answer.parentId;
190
+ if (answer.sampled !== undefined) context.sampled = answer.sampled;
191
+ if (answer.state !== undefined) context.state = answer.state;
192
+ if (answer.baggage !== undefined) context.baggage = answer.baggage;
193
+ providedEntries = answer.entries;
194
+ }
195
+ }
196
+ }
197
+ context.entries.traceparent = formatTraceparent(context);
198
+ if (providedEntries) Object.assign(context.entries, providedEntries);
199
+ record = {
200
+ context,
201
+ emit: incoming !== undefined && incoming.sampled || answered
202
+ };
203
+ store.set(key, record);
204
+ return record;
205
+ }
206
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
207
+ function splitServerTiming(value) {
208
+ const entries = [];
209
+ let start = 0;
210
+ let quoted = false;
211
+ for (let i = 0; i < value.length; i++) {
212
+ const c = value[i];
213
+ if (quoted) {
214
+ if (c === "\\") i++;else if (c === '"') quoted = false;
215
+ } else if (c === '"') quoted = true;else if (c === ",") {
216
+ entries.push(value.slice(start, i));
217
+ start = i + 1;
218
+ }
219
+ }
220
+ entries.push(value.slice(start));
221
+ return entries;
222
+ }
223
+ function metricName(entry) {
224
+ return entry.split(";")[0].trim().toLowerCase();
225
+ }
226
+ function namesOnServerTiming(headers) {
227
+ const names = new Set();
228
+ const existing = headers.get("server-timing");
229
+ if (existing) {
230
+ for (const entry of splitServerTiming(existing)) {
231
+ const name = metricName(entry);
232
+ if (name) names.add(name);
233
+ }
234
+ }
235
+ return names;
236
+ }
237
+ function quoteDesc(value) {
238
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[\\"]/g, m => "\\" + m);
239
+ }
240
+ function appendTraceServerTiming(headers, record) {
241
+ if (!record.emit) return;
242
+ const entries = record.context.entries;
243
+ let present;
244
+ for (const name in entries) {
245
+ if (!TOKEN.test(name)) continue;
246
+ if (!present) present = namesOnServerTiming(headers);
247
+ if (present.has(name.toLowerCase())) continue;
248
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
249
+ present.add(name.toLowerCase());
250
+ }
251
+ }
252
+ function escapeAttr(value) {
253
+ return value.replace(/[&"<>]/g, c => c === "&" ? "&amp;" : c === '"' ? "&quot;" : c === "<" ? "&lt;" : "&gt;");
254
+ }
255
+ function traceMetaMarkup(record) {
256
+ if (!record.emit) return "";
257
+ let markup = "";
258
+ const entries = record.context.entries;
259
+ for (const name in entries) {
260
+ if (!TOKEN.test(name)) continue;
261
+ markup += `<meta name="${name}" content="${escapeAttr(entries[name])}">`;
262
+ }
263
+ return markup;
264
+ }
265
+
266
+ setContainerTraceStreamMint(iterable => {
267
+ const stream = createStream();
268
+ (async () => {
269
+ try {
270
+ for await (const value of iterable) stream.next(value);
271
+ stream.return(undefined);
272
+ } catch (error) {
273
+ stream.throw(error);
274
+ }
275
+ })();
276
+ return stream;
277
+ });
278
+ const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
279
+ CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
280
+ FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin,
281
+ ContainerTracePlugin]);
282
+ function resolveSerializerPlugins(customPlugins) {
283
+ return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
284
+ }
285
+ const JSON_CODEC_DISABLED_FEATURES = Feature.RegExp;
286
+ const JSON_CODEC_DEPTH_LIMIT = 64;
287
+ function resolveCodecOptions({
288
+ plugins,
289
+ disabledFeatures,
290
+ depthLimit,
291
+ serializeErrorStacks
292
+ } = {}) {
293
+ return {
294
+ plugins: resolveSerializerPlugins(plugins),
295
+ disabledFeatures: disabledFeatures === undefined ? JSON_CODEC_DISABLED_FEATURES : disabledFeatures,
296
+ depthLimit: depthLimit === undefined ? JSON_CODEC_DEPTH_LIMIT : depthLimit,
297
+ serializeErrorStacks
298
+ };
299
+ }
300
+
301
+ const DEFAULT_DISABLED_FEATURES = Feature.AggregateError | Feature.BigIntTypedArray;
302
+ const serializeOnlyDisabledFeatures = serializeErrorStacks => (serializeErrorStacks === undefined ? process.env.NODE_ENV === "development" : serializeErrorStacks) ? 0 : Feature.ErrorPrototypeStack;
303
+ const HYDRATION_GLOBAL = "_$HY.r";
304
+ function createSerializer(options) {
305
+ return new Serializer({
306
+ ...options,
307
+ plugins: resolveSerializerPlugins(options.plugins),
308
+ disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures(options.serializeErrorStacks)
309
+ });
310
+ }
311
+ function createHydrationSerializer({
312
+ onData,
313
+ onDone,
314
+ scopeId,
315
+ onError,
316
+ plugins
317
+ }) {
318
+ return createSerializer({
319
+ scopeId,
320
+ plugins,
321
+ globalIdentifier: HYDRATION_GLOBAL,
322
+ onData,
323
+ onDone,
324
+ onError
325
+ });
326
+ }
327
+ function getLocalHeaderScript(id) {
328
+ return getCrossReferenceHeader(id) + ";";
329
+ }
330
+ function createJSONSerializer({
331
+ onData,
332
+ onDone,
333
+ onError,
334
+ plugins,
335
+ disabledFeatures,
336
+ depthLimit,
337
+ serializeErrorStacks
338
+ }) {
339
+ const resolved = resolveCodecOptions({
340
+ plugins,
341
+ disabledFeatures,
342
+ depthLimit,
343
+ serializeErrorStacks
344
+ });
345
+ const refs = new Map();
346
+ const cancels = new Set();
347
+ let pendingWrites = 0;
348
+ let flushed = false;
349
+ let done = false;
350
+ const maybeDone = () => {
351
+ if (flushed && pendingWrites === 0 && !done) {
352
+ done = true;
353
+ onDone && onDone();
354
+ }
355
+ };
356
+ return {
357
+ write(key, value) {
358
+ if (flushed) return;
359
+ pendingWrites++;
360
+ let settled = false;
361
+ let cancel = null;
362
+ const stream = toCrossJSONStream(value, {
363
+ refs,
364
+ plugins: resolved.plugins,
365
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks),
366
+ onParse(node, initial) {
367
+ onData({
368
+ key,
369
+ node,
370
+ initial
371
+ });
372
+ },
373
+ onError,
374
+ onDone() {
375
+ settled = true;
376
+ if (cancel) cancels.delete(cancel);
377
+ pendingWrites--;
378
+ maybeDone();
379
+ }
380
+ });
381
+ if (!settled) {
382
+ cancel = stream;
383
+ cancels.add(cancel);
384
+ }
385
+ },
386
+ flush() {
387
+ flushed = true;
388
+ maybeDone();
389
+ },
390
+ close() {
391
+ flushed = true;
392
+ for (const cancel of cancels) cancel();
393
+ cancels.clear();
394
+ }
395
+ };
396
+ }
397
+
398
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
399
+ function isResponseEnvelope(value) {
400
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
401
+ }
402
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
403
+ function isSafeError(value) {
404
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
405
+ }
406
+ const REVALIDATE_HEADER = "X-Revalidate";
407
+
408
+ function frameAddress(id, args) {
409
+ return args && args.length ? id + ":" + hashArguments(args) : id;
410
+ }
411
+ function hashArguments(args) {
412
+ let hash = 0;
413
+ const text = stableString(args);
414
+ for (let i = 0; i < text.length; i++) {
415
+ hash = (hash << 5) - hash + text.charCodeAt(i);
416
+ hash |= 0;
417
+ }
418
+ return (hash >>> 0).toString(36);
419
+ }
420
+ function stableString(value, seen) {
421
+ if (value === null || typeof value !== "object") {
422
+ return typeof value === "bigint" ? value + "n" : String(value);
423
+ }
424
+ if (value instanceof Date) return "Date:" + value.getTime();
425
+ seen || (seen = new Set());
426
+ if (seen.has(value)) return "~";
427
+ seen.add(value);
428
+ if (value instanceof Map) {
429
+ const entries = [];
430
+ for (const [k, v] of value) {
431
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
432
+ }
433
+ return "Map{" + entries.sort().join(",") + "}";
434
+ }
435
+ if (value instanceof Set) {
436
+ const members = [];
437
+ for (const v of value) members.push(stableString(v, seen));
438
+ return "Set{" + members.sort().join(",") + "}";
439
+ }
440
+ if (Array.isArray(value)) {
441
+ let out = "[";
442
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
443
+ return out + "]";
444
+ }
445
+ const keys = Object.keys(value).sort();
446
+ let out = "{";
447
+ for (let i = 0; i < keys.length; i++) {
448
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
449
+ }
450
+ return out + "}";
451
+ }
452
+ const ERROR_HEADER = "X-Server-Function-Error";
453
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
454
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
455
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
456
+ const BodyFormat = {
457
+ Serialized: "0",
458
+ String: "1",
459
+ FormData: "2",
460
+ URLSearchParams: "3",
461
+ Blob: "4",
462
+ File: "5",
463
+ ArrayBuffer: "6",
464
+ Uint8Array: "7",
465
+ Json: "8",
466
+ Void: "9"
467
+ };
468
+ function createChunk(data) {
469
+ const encoder = new TextEncoder();
470
+ const encodeData = encoder.encode(data);
471
+ const bytes = encodeData.length;
472
+ const chunk = new Uint8Array(12 + bytes);
473
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
474
+ chunk.set(encodeData, 12);
475
+ return chunk;
476
+ }
477
+ class ChunkReader {
478
+ constructor(stream) {
479
+ this.reader = stream.getReader();
480
+ this.store = new Uint8Array(0);
481
+ this.buffer = this.store;
482
+ this.done = false;
483
+ }
484
+ async readChunk() {
485
+ const chunk = await this.reader.read();
486
+ if (chunk.done) {
487
+ this.done = true;
488
+ return;
489
+ }
490
+ const incoming = chunk.value;
491
+ const store = this.store;
492
+ const start = this.buffer.byteOffset;
493
+ const end = start + this.buffer.length;
494
+ const needed = this.buffer.length + incoming.length;
495
+ if (end + incoming.length <= store.length) {
496
+ store.set(incoming, end);
497
+ this.buffer = store.subarray(start, end + incoming.length);
498
+ } else if (needed <= store.length) {
499
+ store.copyWithin(0, start, end);
500
+ store.set(incoming, this.buffer.length);
501
+ this.buffer = store.subarray(0, needed);
502
+ } else {
503
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
504
+ grown.set(this.buffer);
505
+ grown.set(incoming, this.buffer.length);
506
+ this.store = grown;
507
+ this.buffer = grown.subarray(0, needed);
508
+ }
509
+ }
510
+ async next() {
511
+ while (this.buffer.length < 12) {
512
+ if (this.done) {
513
+ if (this.buffer.length === 0) return {
514
+ done: true,
515
+ value: undefined
516
+ };
517
+ throw new Error("Malformed server function stream.");
518
+ }
519
+ await this.readChunk();
520
+ }
521
+ const decoder = new TextDecoder();
522
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
523
+ if (Number.isNaN(bytes)) {
524
+ throw new Error("Malformed server function stream.");
525
+ }
526
+ while (bytes > this.buffer.length - 12) {
527
+ if (this.done) {
528
+ throw new Error("Malformed server function stream.");
529
+ }
530
+ await this.readChunk();
531
+ }
532
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
533
+ this.buffer = this.buffer.subarray(12 + bytes);
534
+ return {
535
+ done: false,
536
+ value: partial
537
+ };
538
+ }
539
+ async drain(interpret) {
540
+ while (true) {
541
+ const result = await this.next();
542
+ if (result.done) {
543
+ break;
544
+ }
545
+ interpret(result.value);
546
+ }
547
+ }
548
+ }
549
+ function serializeStream(value, codecOptions) {
550
+ return new ReadableStream({
551
+ async start(controller) {
552
+ const {
553
+ serializeJSON
554
+ } = await import('@solidjs/web/serialization');
555
+ serializeJSON(value, {
556
+ ...codecOptions,
557
+ onParse(node) {
558
+ controller.enqueue(createChunk(JSON.stringify(node)));
559
+ },
560
+ onDone() {
561
+ controller.close();
562
+ },
563
+ onError(error) {
564
+ controller.error(error);
565
+ }
566
+ });
567
+ }
568
+ });
569
+ }
570
+
571
+ function emitFinding(finding, subject = getOwner()) {
572
+ if (OBSERVE === undefined) return;
573
+ OBSERVE.diagnostics.emit(finding, subject);
574
+ }
575
+ function recordFinding(finding, subject = getOwner()) {
576
+ if (OBSERVE !== undefined) OBSERVE.diagnostics.emit(finding, subject);
577
+ }
578
+ function errorText(error) {
579
+ if (error instanceof Error) return error.message ? `${error.name}: ${error.message}` : error.name;
580
+ return String(error);
581
+ }
582
+
583
+ const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
584
+ const HEAD_ATTR_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;
585
+ const RESOURCE_LINK_RELS = new Set(["preload", "modulepreload", "prefetch", "preconnect", "dns-prefetch", "stylesheet"]);
586
+ const RESOURCE_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
587
+ const STYLESHEET_FETCH_META = new Set(["crossorigin", "integrity", "referrerpolicy", "fetchpriority"]);
588
+ function evalHeadValue(v) {
589
+ return typeof v === "function" ? v() : v;
590
+ }
591
+ function evalHeadProps(props, presets) {
592
+ const out = {};
593
+ for (const name in props) out[name] = presets && name in presets ? presets[name] : evalHeadValue(props[name]);
594
+ return out;
595
+ }
596
+ function classifyHeadTag(desc) {
597
+ const tag = desc.tag;
598
+ if (tag === "link") {
599
+ const rel = evalHeadValue(desc.props && desc.props.rel);
600
+ return {
601
+ resource: RESOURCE_LINK_RELS.has(rel),
602
+ rel
603
+ };
604
+ }
605
+ if (tag === "style") return {
606
+ resource: !!(desc.props && "href" in desc.props)
607
+ };
608
+ if (tag === "script") return {
609
+ resource: !!(desc.props && "src" in desc.props)
610
+ };
611
+ return {
612
+ resource: false
613
+ };
614
+ }
615
+ function qualifierValue(name, value) {
616
+ if (value == null || value === false) return null;
617
+ if (name === "imagesrcset" || name === "imagesizes") return typeof value === "string" && value !== "" ? value : null;
618
+ const v = value === true ? "" : String(value);
619
+ if (name === "as") return asciiLowerCase(v);
620
+ if (name !== "crossorigin") return v;
621
+ return v.length === 15 && v.toLowerCase() === "use-credentials" ? v.toLowerCase() : "anonymous";
622
+ }
623
+ function asciiLowerCase(value) {
624
+ return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
625
+ }
626
+ function resourceIdentity(tag, props) {
627
+ const url = String(props.href || props.src || "");
628
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + url.length + ":" + url;
629
+ for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
630
+ const q = RESOURCE_QUALIFIERS[i];
631
+ const value = qualifierValue(q, props[q]);
632
+ if (value !== null) id += ":" + q + "=" + value.length + ":" + value;
633
+ }
634
+ return id;
635
+ }
636
+ function replaceableIdentity(tag, props, key, unique) {
637
+ if (tag === "title") return "title";
638
+ if (tag === "base") return "base";
639
+ if (tag === "meta" && props.charset != null) return "charset";
640
+ if (key != null) return tag + ":key:" + key;
641
+ if (tag === "meta") {
642
+ for (const ns of ["name", "property", "http-equiv"]) if (props[ns] != null) return "meta:" + ns + ":" + props[ns] + (props.media != null ? ":media=" + props.media : "");
643
+ return unique;
644
+ }
645
+ if (tag === "link") {
646
+ const rel = props.rel || "";
647
+ if (rel === "icon" || rel === "apple-touch-icon") return "link:" + rel + (props.sizes != null ? ":sizes=" + props.sizes : "") + (props.type != null ? ":type=" + props.type : "");
648
+ return "link:" + rel + ":" + (props.href || "");
649
+ }
650
+ return unique;
651
+ }
652
+ function resolveHead(groups) {
653
+ const winners = new Map();
654
+ const sorted = groups.slice().sort((a, b) => a.seq - b.seq);
655
+ for (let i = 0; i < sorted.length; i++) {
656
+ const group = sorted[i];
657
+ const byIdentity = new Map();
658
+ for (let j = 0; j < group.tags.length; j++) {
659
+ const t = group.tags[j];
660
+ let list = byIdentity.get(t.identity);
661
+ if (!list) byIdentity.set(t.identity, list = []);
662
+ list.push(t);
663
+ }
664
+ for (const [identity, tags] of byIdentity) {
665
+ if (identity === "title") {
666
+ winners.set(identity, {
667
+ seq: group.seq,
668
+ tags: [tags[tags.length - 1]]
669
+ });
670
+ } else {
671
+ winners.set(identity, {
672
+ seq: group.seq,
673
+ tags
674
+ });
675
+ }
676
+ }
677
+ }
678
+ return winners;
679
+ }
680
+
681
+ function joinAssetPath(base, file) {
682
+ if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
683
+ if (typeof base !== "string" || !base) base = "/";
684
+ if (base[base.length - 1] !== "/") base += "/";
685
+ return base + (file[0] === "/" ? file.slice(1) : file);
686
+ }
687
+ function resolveAssets(moduleUrl, manifest) {
688
+ if (!manifest) return null;
689
+ const base = manifest._base;
690
+ const entry = manifest[moduleUrl];
691
+ if (!entry) return null;
692
+ const css = [];
693
+ const js = [];
694
+ let preloads;
695
+ const visited = new Set();
696
+ const walk = key => {
697
+ if (visited.has(key)) return;
698
+ visited.add(key);
699
+ const e = manifest[key];
700
+ if (!e) return;
701
+ js.push(joinAssetPath(base, e.file));
702
+ if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
703
+ if (e.preloads) {
704
+ for (let i = 0; i < e.preloads.length; i++) {
705
+ const link = e.preloads[i];
706
+ const href = link && typeof link.href === "string" && link.href;
707
+ const srcset = link && typeof link.imagesrcset === "string" && link.imagesrcset;
708
+ if (!href && !srcset) continue;
709
+ if (!preloads) preloads = [];
710
+ if (href) preloads.push({
711
+ ...link,
712
+ href: joinAssetPath(base, href)
713
+ });else {
714
+ const {
715
+ href: bad,
716
+ ...rest
717
+ } = link;
718
+ preloads.push(rest);
719
+ }
720
+ }
721
+ }
722
+ if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
723
+ };
724
+ walk(moduleUrl);
725
+ const assets = {
726
+ js,
727
+ css
728
+ };
729
+ if (preloads) assets.preloads = preloads;
730
+ return assets;
731
+ }
732
+ function registerEntryAssets(manifest) {
733
+ if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
734
+ const ctx = sharedConfig.context;
735
+ if (!ctx?.registerAsset) return;
736
+ for (const key in manifest) {
737
+ if (manifest[key].isEntry) {
738
+ const assets = resolveAssets(key, manifest);
739
+ if (assets) {
740
+ if (assets.preloads) for (let i = 0; i < assets.preloads.length; i++) ctx.registerAsset("preload", assets.preloads[i]);
741
+ for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
742
+ for (let i = 1; i < assets.js.length; i++) ctx.registerAsset("module", assets.js[i]);
743
+ }
744
+ return;
745
+ }
746
+ }
747
+ }
748
+ function createAssetTracking() {
749
+ const boundaryModules = new Map();
750
+ const boundaryStyles = new Map();
751
+ const emittedAssets = new Set();
752
+ const inlineStyles = new Map();
753
+ let currentBoundaryId = null;
754
+ return {
755
+ boundaryModules,
756
+ boundaryStyles,
757
+ emittedAssets,
758
+ inlineStyles,
759
+ preloadLinks: null,
760
+ registerInlineStyle(desc) {
761
+ let entry = inlineStyles.get(desc.id);
762
+ if (!entry) {
763
+ entry = {
764
+ id: desc.id,
765
+ content: desc.content || "",
766
+ attrs: desc.attrs,
767
+ emitted: false
768
+ };
769
+ inlineStyles.set(desc.id, entry);
770
+ }
771
+ if (currentBoundaryId) {
772
+ let styles = boundaryStyles.get(currentBoundaryId);
773
+ if (!styles) {
774
+ styles = new Set();
775
+ boundaryStyles.set(currentBoundaryId, styles);
776
+ }
777
+ styles.add(entry);
778
+ }
779
+ return entry;
780
+ },
781
+ get currentBoundaryId() {
782
+ return currentBoundaryId;
783
+ },
784
+ set currentBoundaryId(v) {
785
+ currentBoundaryId = v;
786
+ },
787
+ registerModule(key, entryUrl) {
788
+ const id = currentBoundaryId || "";
789
+ let map = boundaryModules.get(id);
790
+ if (!map) {
791
+ map = {};
792
+ boundaryModules.set(id, map);
793
+ }
794
+ map[key] = entryUrl;
795
+ },
796
+ getBoundaryModules(id) {
797
+ return boundaryModules.get(id) || null;
798
+ },
799
+ getBoundaryStyles(id) {
800
+ return boundaryStyles.get(id) || null;
801
+ }
802
+ };
803
+ }
804
+ function warnUnresolvedModuleAssets(moduleUrl, warned) {
805
+ if (warned.has(moduleUrl)) return;
806
+ warned.add(moduleUrl);
807
+ console.error(`Asset manifest returned no client assets for module "${moduleUrl}". ` + "If this module is a server-rendered lazy() component, its entry will be missing from " + "the serialized hydration asset map, the client will be unable to preload it, and " + "hydration will fail with 'lazy() module \"…\" was not preloaded before hydration'. " + "This means the integration's asset resolver (dev manifest bridge or build client " + "manifest) failed to answer for this module — check the integration's server logs, " + "restart the dev server, or verify the module is included in the client build.");
808
+ }
809
+ function guardResolvedAssets(moduleUrl, result, warned) {
810
+ if (result && typeof result.then === "function") {
811
+ return result.then(assets => {
812
+ if (!assets || !assets.js || !assets.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
813
+ return assets;
814
+ });
815
+ }
816
+ if (!result || !result.js || !result.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
817
+ return result;
818
+ }
819
+ function applyAssetTracking(context, tracking, manifest, noScripts) {
820
+ const warned = new Set();
821
+ const guard = noScripts ? resolve => resolve : resolve => moduleUrl => guardResolvedAssets(moduleUrl, resolve(moduleUrl), warned);
822
+ Object.defineProperty(context, "_currentBoundaryId", {
823
+ get() {
824
+ return tracking.currentBoundaryId;
825
+ },
826
+ set(v) {
827
+ tracking.currentBoundaryId = v;
828
+ },
829
+ configurable: true,
830
+ enumerable: true
831
+ });
832
+ context.registerModule = tracking.registerModule;
833
+ context.getBoundaryModules = tracking.getBoundaryModules;
834
+ if (typeof manifest === "function") {
835
+ context.resolveAssets = guard(manifest);
836
+ } else if (manifest && typeof manifest.resolve === "function") {
837
+ context.resolveAssets = guard(key => manifest.resolve(key));
838
+ if (typeof manifest.resolveSync === "function") {
839
+ context.resolveAssetsSync = key => manifest.resolveSync(key);
840
+ }
841
+ } else if (manifest) {
842
+ const resolve = moduleUrl => resolveAssets(moduleUrl, manifest);
843
+ context.resolveAssets = guard(resolve);
844
+ context.resolveAssetsSync = resolve;
845
+ }
846
+ }
847
+ function isCssUrl(url) {
848
+ const q = url.search(/[?#]/);
849
+ return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
850
+ }
851
+ const RESPONSIVE_ATTRIBUTES = ["imagesrcset", "imagesizes"];
852
+ function isSetAttr(value) {
853
+ return value != null && value !== false && value !== "";
854
+ }
855
+ const PRELOAD_LINK_ATTRIBUTES = ["type", "crossorigin", "integrity", "referrerpolicy", "fetchpriority", "media", "imagesrcset", "imagesizes"];
856
+ function registerPreloadLink(tracking, headRegistry, link, nonce) {
857
+ if (!link || typeof link !== "object") {
858
+ return null;
859
+ }
860
+ if (typeof link.as !== "string") {
861
+ return null;
862
+ }
863
+ const as = asciiLowerCase(link.as);
864
+ let destination = null;
865
+ switch (as) {
866
+ case "script":
867
+ case "style":
868
+ destination = as;
869
+ break;
870
+ case "fetch":
871
+ case "font":
872
+ case "image":
873
+ case "track":
874
+ break;
875
+ default:
876
+ return null;
877
+ }
878
+ const responsive = as === "image";
879
+ let srcset = null;
880
+ let sizes = null;
881
+ if (responsive) {
882
+ for (const name of RESPONSIVE_ATTRIBUTES) {
883
+ const value = link[name];
884
+ if (!isSetAttr(value)) continue;
885
+ if (typeof value !== "string") {
886
+ continue;
887
+ }
888
+ if (name === "imagesrcset") srcset = value;else sizes = value;
889
+ }
890
+ }
891
+ const href = typeof link.href === "string" && link.href ? link.href : null;
892
+ if (!href && !srcset) {
893
+ return null;
894
+ }
895
+ const props = {
896
+ rel: "preload"
897
+ };
898
+ if (href) props.href = href;
899
+ props.as = as;
900
+ for (let i = 0; i < PRELOAD_LINK_ATTRIBUTES.length; i++) {
901
+ const name = PRELOAD_LINK_ATTRIBUTES[i];
902
+ if (RESPONSIVE_ATTRIBUTES.indexOf(name) !== -1) {
903
+ const value = name === "imagesrcset" ? srcset : sizes;
904
+ if (value !== null) props[name] = value;
905
+ continue;
906
+ }
907
+ const value = link[name];
908
+ if (value == null || value === false) continue;
909
+ props[name] = value === true ? "" : String(value);
910
+ }
911
+ const identity = resourceIdentity("link", props);
912
+ if (headRegistry.resources.has(identity)) return null;
913
+ const attrs = headAttrRecord(props);
914
+ const nonceValue = destination && nonce && nonce[destination];
915
+ if (typeof nonceValue === "string" && nonceValue) attrs.nonce = nonceValue;
916
+ const entry = {
917
+ href: props.href,
918
+ attrs,
919
+ attrHtml: renderHeadAttrHtml(props) + nonceAttr(nonce, destination)
920
+ };
921
+ headRegistry.resources.add(identity);
922
+ let links = tracking.preloadLinks;
923
+ if (!links) tracking.preloadLinks = links = [];
924
+ links.push(entry);
925
+ return entry;
926
+ }
927
+ function createHeadRegistry() {
928
+ return {
929
+ pending: [],
930
+ committed: [],
931
+ seq: 0,
932
+ uniq: 0,
933
+ resources: new Set(),
934
+ eagerHtml: "",
935
+ flushed: null,
936
+ shellFlushed: false,
937
+ parkedResources: []
938
+ };
939
+ }
940
+ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags) {
941
+ const boundary = context._currentBoundaryId || "";
942
+ if (typeof tags === "function") {
943
+ registry.pending.push({
944
+ boundary,
945
+ list: tags,
946
+ resource: (desc, rel) => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel)
947
+ });
948
+ return;
949
+ }
950
+ if (!Array.isArray(tags)) tags = [tags];
951
+ const probe = sharedConfig.context && sharedConfig.context._loadingPhase;
952
+ let replaceable = null;
953
+ for (let i = 0; i < tags.length; i++) {
954
+ const desc = tags[i];
955
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
956
+ continue;
957
+ }
958
+ const cls = classifyHeadTag(desc);
959
+ if (probe && !cls.resource) {
960
+ try {
961
+ evalHeadProps(desc.props || {}, cls.rel !== undefined ? {
962
+ rel: cls.rel
963
+ } : undefined);
964
+ evalHeadValue(desc.key);
965
+ } catch (err) {
966
+ if (ssrHandleError(err)) throw err;
967
+ }
968
+ }
969
+ if (cls.resource) {
970
+ emitHeadResource(registry, context, tracking, emitResource, nonce, desc, cls.rel);
971
+ } else {
972
+ (replaceable || (replaceable = [])).push(cls.rel !== undefined ? {
973
+ tag: desc.tag,
974
+ props: desc.props,
975
+ key: desc.key,
976
+ rel: cls.rel
977
+ } : desc);
978
+ }
979
+ }
980
+ if (replaceable) registry.pending.push({
981
+ boundary,
982
+ tags: replaceable
983
+ });
984
+ }
985
+ function headShellReady(registry, block) {
986
+ let ready = true;
987
+ const pends = err => {
988
+ const source = ssrHandleError(err, true);
989
+ if (!source) return false;
990
+ block(source);
991
+ ready = false;
992
+ return true;
993
+ };
994
+ const parked = registry.parkedResources;
995
+ for (let i = parked.length - 1; i >= 0; i--) {
996
+ const {
997
+ desc,
998
+ rel,
999
+ emit
1000
+ } = parked[i];
1001
+ try {
1002
+ evalHeadProps(desc.props || {}, rel !== undefined ? {
1003
+ rel
1004
+ } : undefined);
1005
+ } catch (err) {
1006
+ if (pends(err)) continue;
1007
+ parked.splice(i, 1);
1008
+ continue;
1009
+ }
1010
+ parked.splice(i, 1);
1011
+ emit();
1012
+ }
1013
+ for (let i = 0; i < registry.pending.length; i++) {
1014
+ const reg = registry.pending[i];
1015
+ if (reg.boundary !== "" || reg.list) continue;
1016
+ for (let j = 0; j < reg.tags.length; j++) {
1017
+ const desc = reg.tags[j];
1018
+ try {
1019
+ evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
1020
+ rel: desc.rel
1021
+ } : undefined);
1022
+ evalHeadValue(desc.key);
1023
+ } catch (err) {
1024
+ pends(err);
1025
+ }
1026
+ }
1027
+ }
1028
+ return ready;
1029
+ }
1030
+ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel) {
1031
+ let props;
1032
+ try {
1033
+ props = evalHeadProps(desc.props || {}, rel !== undefined ? {
1034
+ rel
1035
+ } : undefined);
1036
+ } catch (err) {
1037
+ const loadingPhase = sharedConfig.context && sharedConfig.context._loadingPhase;
1038
+ if (loadingPhase && ssrHandleError(err)) throw err;
1039
+ if (!loadingPhase && !context._currentBoundaryId && !registry.shellFlushed && typeof context.block === "function" && ssrHandleError(err, true)) {
1040
+ registry.parkedResources.push({
1041
+ desc,
1042
+ rel,
1043
+ emit: () => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel)
1044
+ });
1045
+ return;
1046
+ }
1047
+ return;
1048
+ }
1049
+ const identity = resourceIdentity(desc.tag, props);
1050
+ if (registry.resources.has(identity)) return;
1051
+ registry.resources.add(identity);
1052
+ if (desc.tag === "link" && (rel === "stylesheet" || rel === "modulepreload")) {
1053
+ let plain = true;
1054
+ let gateable = rel === "stylesheet";
1055
+ for (const name in props) {
1056
+ if (name === "rel" || name === "href") continue;
1057
+ plain = false;
1058
+ if (!STYLESHEET_FETCH_META.has(name)) gateable = false;
1059
+ }
1060
+ if (plain && props.href != null) {
1061
+ const isCss = isCssUrl(props.href);
1062
+ if (rel === "stylesheet" ? isCss : !isCss) {
1063
+ context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href);
1064
+ return;
1065
+ }
1066
+ }
1067
+ if (gateable && props.href != null) {
1068
+ const attrHtml = renderHeadAttrHtml(props);
1069
+ const entry = {
1070
+ href: props.href,
1071
+ attrHtml,
1072
+ attrs: headAttrRecord(props)
1073
+ };
1074
+ if (tracking.currentBoundaryId) {
1075
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
1076
+ if (!styles) tracking.boundaryStyles.set(tracking.currentBoundaryId, styles = new Set());
1077
+ styles.add(entry);
1078
+ }
1079
+ const markup = `<link${attrHtml}${nonceAttr(nonce, "style")}>`;
1080
+ if (emitResource) emitResource(markup, entry);else {
1081
+ registry.eagerHtml += markup;
1082
+ entry.emitted = true;
1083
+ }
1084
+ return;
1085
+ }
1086
+ }
1087
+ const url = props.href || props.src;
1088
+ if (url != null && tracking.emittedAssets.has(url)) return;
1089
+ const markup = renderHeadTagMarkup(desc.tag, props, null, nonce);
1090
+ if (emitResource) emitResource(markup);else registry.eagerHtml += markup;
1091
+ }
1092
+ function commitHeadBoundary(registry, boundary, isPendingFragment) {
1093
+ const keep = [];
1094
+ const groups = [];
1095
+ for (let i = 0; i < registry.pending.length; i++) {
1096
+ const reg = registry.pending[i];
1097
+ const mine = boundary === "" ? !(isPendingFragment && reg.boundary !== "" && isPendingFragment(reg.boundary)) : reg.boundary === boundary;
1098
+ if (!mine) {
1099
+ keep.push(reg);
1100
+ continue;
1101
+ }
1102
+ let descs = reg.tags;
1103
+ if (reg.list) {
1104
+ let resolved;
1105
+ try {
1106
+ resolved = reg.list();
1107
+ } catch (err) {
1108
+ continue;
1109
+ }
1110
+ if (!Array.isArray(resolved)) resolved = [resolved];
1111
+ descs = [];
1112
+ for (let j = 0; j < resolved.length; j++) {
1113
+ const desc = resolved[j];
1114
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
1115
+ continue;
1116
+ }
1117
+ const cls = classifyHeadTag(desc);
1118
+ if (cls.resource) {
1119
+ reg.resource(desc, cls.rel);
1120
+ } else {
1121
+ descs.push(cls.rel !== undefined ? {
1122
+ tag: desc.tag,
1123
+ props: desc.props,
1124
+ key: desc.key,
1125
+ rel: cls.rel
1126
+ } : desc);
1127
+ }
1128
+ }
1129
+ }
1130
+ const tags = [];
1131
+ for (let j = 0; j < descs.length; j++) {
1132
+ const desc = descs[j];
1133
+ let props, key;
1134
+ try {
1135
+ props = evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
1136
+ rel: desc.rel
1137
+ } : undefined);
1138
+ key = evalHeadValue(desc.key);
1139
+ } catch (err) {
1140
+ continue;
1141
+ }
1142
+ const identity = replaceableIdentity(desc.tag, props, key, "u:" + registry.uniq++);
1143
+ if ((identity === "base" || identity === "charset") && registry.shellFlushed) {
1144
+ continue;
1145
+ }
1146
+ tags.push({
1147
+ tag: desc.tag,
1148
+ props,
1149
+ identity
1150
+ });
1151
+ }
1152
+ if (tags.length) groups.push({
1153
+ seq: registry.seq++,
1154
+ tags
1155
+ });
1156
+ }
1157
+ registry.pending = keep;
1158
+ for (let i = 0; i < groups.length; i++) registry.committed.push(groups[i]);
1159
+ return groups;
1160
+ }
1161
+ function adoptHeadBoundary(registry, childKey, parentKey) {
1162
+ for (let i = 0; i < registry.pending.length; i++) {
1163
+ if (registry.pending[i].boundary === childKey) registry.pending[i].boundary = parentKey;
1164
+ }
1165
+ }
1166
+ function dropHeadBoundary(registry, boundary) {
1167
+ registry.pending = registry.pending.filter(reg => reg.boundary !== boundary);
1168
+ }
1169
+ function headGroupSignature(winner) {
1170
+ let sig = "" + winner.seq;
1171
+ for (let i = 0; i < winner.tags.length; i++) {
1172
+ const t = winner.tags[i];
1173
+ sig += "|" + t.tag + JSON.stringify(t.props);
1174
+ }
1175
+ return sig;
1176
+ }
1177
+ function renderShellHead(registry, nonce, isPendingFragment, noScripts, traceMetas = "") {
1178
+ commitHeadBoundary(registry, "", isPendingFragment);
1179
+ registry.shellFlushed = true;
1180
+ const winners = resolveHead(registry.committed);
1181
+ registry.flushed = new Map();
1182
+ let prelude = "";
1183
+ let links = "";
1184
+ let metas = "";
1185
+ let others = "";
1186
+ let scripts = "";
1187
+ let title = null;
1188
+ for (const [identity, winner] of winners) {
1189
+ registry.flushed.set(identity, headGroupSignature(winner));
1190
+ if (identity === "title") {
1191
+ const children = winner.tags[0].props.children;
1192
+ title = children == null ? "" : String(children);
1193
+ continue;
1194
+ }
1195
+ for (let i = 0; i < winner.tags.length; i++) {
1196
+ const t = winner.tags[i];
1197
+ const markup = renderHeadTagMarkup(t.tag, t.props, identity, nonce);
1198
+ if (identity === "charset" || identity === "base") prelude += markup;else if (t.tag === "link" || t.tag === "style") links += markup;else if (t.tag === "meta") metas += markup;else if (t.tag === "script") scripts += markup;else others += markup;
1199
+ }
1200
+ }
1201
+ return {
1202
+ prelude,
1203
+ html: registry.eagerHtml + links + metas + traceMetas + others + scripts,
1204
+ title,
1205
+ noScripts
1206
+ };
1207
+ }
1208
+ function flushHeadFragment(registry, boundary, nonce) {
1209
+ const groups = commitHeadBoundary(registry, boundary);
1210
+ if (!groups.length) return null;
1211
+ const winners = resolveHead(registry.committed);
1212
+ const affected = new Set();
1213
+ for (let i = 0; i < groups.length; i++) for (let j = 0; j < groups[i].tags.length; j++) affected.add(groups[i].tags[j].identity);
1214
+ const ops = [];
1215
+ for (const identity of affected) {
1216
+ const winner = winners.get(identity);
1217
+ const sig = headGroupSignature(winner);
1218
+ if (registry.flushed.get(identity) === sig) continue;
1219
+ const existed = registry.flushed.has(identity);
1220
+ registry.flushed.set(identity, sig);
1221
+ if (identity === "title") {
1222
+ const children = winner.tags[0].props.children;
1223
+ ops.push(["t", children == null ? "" : String(children)]);
1224
+ continue;
1225
+ }
1226
+ if (existed) ops.push(["r", identity]);
1227
+ for (let i = 0; i < winner.tags.length; i++) {
1228
+ const t = winner.tags[i];
1229
+ const attrs = {};
1230
+ for (const name in t.props) {
1231
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1232
+ if (!HEAD_ATTR_NAME.test(name)) {
1233
+ continue;
1234
+ }
1235
+ const v = t.props[name];
1236
+ if (v == null || v === false) continue;
1237
+ attrs[name] = v === true ? "" : String(v);
1238
+ }
1239
+ if (nonce && !hasNonceProp(t.props)) {
1240
+ const destination = nonceDestination(t.tag, t.props);
1241
+ const value = destination && nonce[destination];
1242
+ if (value) attrs.nonce = String(value);
1243
+ }
1244
+ const children = t.props.children;
1245
+ ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
1246
+ }
1247
+ }
1248
+ return ops.length ? ops : null;
1249
+ }
1250
+ function normalizeNonce(nonce) {
1251
+ if (nonce == null) return undefined;
1252
+ if (typeof nonce === "string") {
1253
+ const attr = nonce ? ` nonce="${escape(nonce, true)}"` : "";
1254
+ return {
1255
+ script: nonce,
1256
+ style: nonce,
1257
+ scriptAttr: attr,
1258
+ styleAttr: attr
1259
+ };
1260
+ }
1261
+ const script = nonce.script;
1262
+ const style = nonce.style;
1263
+ if (!script && !style) return undefined;
1264
+ return {
1265
+ script,
1266
+ style,
1267
+ scriptAttr: typeof script === "string" && script ? ` nonce="${escape(script, true)}"` : "",
1268
+ styleAttr: typeof style === "string" && style ? ` nonce="${escape(style, true)}"` : ""
1269
+ };
1270
+ }
1271
+ function hasNonceProp(props) {
1272
+ for (const name in props) if (name.length === 5 && asciiLowerCase(name) === "nonce" && props[name] != null) return true;
1273
+ return false;
1274
+ }
1275
+ function nonceDestination(tag, props) {
1276
+ if (tag === "script") return "script";
1277
+ if (tag === "style") return "style";
1278
+ if (tag !== "link") return null;
1279
+ const rel = props.rel;
1280
+ if (typeof rel !== "string") return null;
1281
+ const rels = asciiLowerCase(rel).split(/[\t\n\f\r ]+/);
1282
+ if (rels.includes("stylesheet")) return "style";
1283
+ const isModulePreload = rels.includes("modulepreload");
1284
+ if (!isModulePreload && !rels.includes("preload")) return null;
1285
+ const as = typeof props.as === "string" ? asciiLowerCase(props.as) : "";
1286
+ if (as === "style") return "style";
1287
+ if (as === "script") return "script";
1288
+ if (!isModulePreload) return null;
1289
+ switch (as) {
1290
+ case "fetch":
1291
+ case "font":
1292
+ case "image":
1293
+ case "json":
1294
+ case "text":
1295
+ case "track":
1296
+ return null;
1297
+ default:
1298
+ return "script";
1299
+ }
1300
+ }
1301
+ function nonceAttr(nonce, destination) {
1302
+ if (!nonce || !destination) return "";
1303
+ return destination === "script" ? nonce.scriptAttr : nonce.styleAttr;
1304
+ }
1305
+ function renderHeadAttrHtml(props) {
1306
+ let attrs = "";
1307
+ for (const name in props) {
1308
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1309
+ if (!HEAD_ATTR_NAME.test(name)) {
1310
+ continue;
1311
+ }
1312
+ const v = props[name];
1313
+ if (v == null || v === false) continue;
1314
+ attrs += v === true ? ` ${name}` : ` ${name}="${escape(String(v), true)}"`;
1315
+ }
1316
+ return attrs;
1317
+ }
1318
+ function headAttrRecord(props, skipRelHref) {
1319
+ let attrs = null;
1320
+ for (const name in props) {
1321
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1322
+ if ((name === "rel" || name === "href")) continue;
1323
+ if (!HEAD_ATTR_NAME.test(name)) continue;
1324
+ const v = props[name];
1325
+ if (v == null || v === false) continue;
1326
+ (attrs || (attrs = {}))[name] = v === true ? "" : String(v);
1327
+ }
1328
+ return attrs;
1329
+ }
1330
+ function renderHeadTagMarkup(tag, props, identity, nonce) {
1331
+ let attrs = renderHeadAttrHtml(props);
1332
+ if (identity != null) attrs += ` data-dh="${escape(identity, true)}"`;
1333
+ if (nonce && !hasNonceProp(props)) attrs += nonceAttr(nonce, nonceDestination(tag, props));
1334
+ if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
1335
+ let body = props.children == null ? "" : String(props.children);
1336
+ if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
1337
+ return `<${tag}${attrs}>${body}</${tag}>`;
1338
+ }
1339
+ const REPLACE_SCRIPT = `function $df(e){return _$HY.f?_$HY.f(e):$dfr(e)}function $dfr(e,n,o,t){if(!(n=document.getElementById(e)))return 0;if(!(o=document.getElementById("pl-"+e)))return(_$HY.dq=_$HY.dq||{})[e]=1,0;for(;o&&(8!==o.nodeType||o.nodeValue!=="pl-"+e);)t=o.nextSibling,o.remove(),o=t;t=o.parentNode,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$HY.fe(e,t),_$HY.hp&&_$HY.hp[e]&&($dh(_$HY.hp[e]),delete _$HY.hp[e]),$dfd();return 1}function $dfl(e,o,n){if(!(o=document.getElementById("pl-"+e)))return(_$HY.dlq=_$HY.dlq||{})[e]=1,0;if(o._$fl)return 1;for(n=o.nextSibling;n;){if(8===n.nodeType&&n.nodeValue==="pl-"+e){o.parentNode&&o.parentNode.insertBefore(o.content.cloneNode(!0),n),o._$fl=1,$dfd();return 1}n=n.nextSibling}return 0}function $dflj(e,i){for(i=0;i<e.length;i++)$dfl(e[i])}function $dfd(e,i){if(e=_$HY.dq){_$HY.dq=0;for(i in e)$df(i)}if(e=_$HY.dlq){_$HY.dlq=0;for(i in e)$dfl(i)}}function $dfs(e,c,d){(_$HY.sc=_$HY.sc||{})[e]=c,d&&((_$HY.sd=_$HY.sd||{})[e]=1)}function $dfg(e,g,i,k){if(!(g=_$HY.sg&&_$HY.sg[e]))return;for(i=0;i<g.length;i++)if(_$HY.sc&&_$HY.sc[g[i]]>0)return;for(i=0;i<g.length;i++)k=g[i],delete _$HY.sg[k],$df(k)}function $dfc(e){if(--_$HY.sc[e]<=0){delete _$HY.sc[e],_$HY.sg&&_$HY.sg[e]?$dfg(e):!(_$HY.sd&&_$HY.sd[e])&&$df(e);_$HY.sd&&delete _$HY.sd[e]}}function $dfj(e,i,n){for(i=0;i<e.length;i++)if(_$HY.sc&&_$HY.sc[e[i]]>0){for(n=0;n<e.length;n++)(_$HY.sg=_$HY.sg||{})[e[n]]=e;return}for(i=0;i<e.length;i++)$df(e[i])}`;
1340
+ const HEAD_SCRIPT = `function $dha(o,i,e,n){for(i=0;i<o.length;i++)e=o[i],"t"==e[0]?((n=document.querySelector("title"))?n.hasAttribute("data-dh")||n.setAttribute("data-dhf",n.textContent):(n=document.createElement("title"),document.head.appendChild(n)),n.textContent=e[1],n.setAttribute("data-dh","title")):"r"==e[0]?$dhr(e[1]):(n=document.createElement(e[2]),Object.keys(e[3]).forEach(function(a){n.setAttribute(a,e[3][a])}),null!=e[4]&&(n.textContent=e[4]),n.setAttribute("data-dh",e[1]),document.head.appendChild(n))}function $dhr(v,l,i){for(l=document.head.querySelectorAll("[data-dh]"),i=0;i<l.length;i++)l[i].getAttribute("data-dh")==v&&l[i].remove()}function $dh(o){_$HY.h?_$HY.h(o):$dha(o)}`;
1341
+ function renderToStream(code, options = {}) {
1342
+ let {
1343
+ onCompleteShell,
1344
+ onCompleteAll,
1345
+ renderId = "",
1346
+ noScripts,
1347
+ manifest,
1348
+ onHead
1349
+ } = options;
1350
+ const nonce = normalizeNonce(options.nonce);
1351
+ const requestEvent = peekRequestEvent();
1352
+ let dispose;
1353
+ let dead = false;
1354
+ const abandon = disconnect => {
1355
+ if (dead) return;
1356
+ if (disconnect) emitFinding({
1357
+ code: "SSR_STREAM_ABANDONED",
1358
+ kind: "ssr",
1359
+ severity: "warn",
1360
+ message: `[SSR_STREAM_ABANDONED] The response stream was abandoned mid-render (${disconnect}) ` + `with ${registry.size} fragment(s) still pending; the render was torn down.`,
1361
+ data: {
1362
+ reason: disconnect,
1363
+ shellFlushed: firstFlushed,
1364
+ pendingFragments: registry.size
1365
+ }
1366
+ }, null);
1367
+ dead = true;
1368
+ completed = true;
1369
+ buffer = {
1370
+ write() {}
1371
+ };
1372
+ writable = {
1373
+ end() {}
1374
+ };
1375
+ if (dispose) {
1376
+ const d = dispose;
1377
+ dispose = () => {};
1378
+ d();
1379
+ }
1380
+ };
1381
+ const failRender = err => {
1382
+ reportServerError(err, {
1383
+ kind: "render",
1384
+ handling: "failed"
1385
+ }, null);
1386
+ if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
1387
+ abandon();
1388
+ };
1389
+ const failRootRender = err => {
1390
+ emitFinding({
1391
+ code: "SSR_RENDER_ERROR_CONTAINED",
1392
+ kind: "ssr",
1393
+ severity: "error",
1394
+ message: `[SSR_RENDER_ERROR_CONTAINED] Render error outside any boundary — the request failed: ` + errorText(err),
1395
+ data: {
1396
+ handling: "failed",
1397
+ error: err
1398
+ }
1399
+ }, null);
1400
+ failRender(err);
1401
+ };
1402
+ const coalesceWrites = (writeRaw, endRaw) => {
1403
+ let buf = "";
1404
+ let scheduled = false;
1405
+ const flush = () => {
1406
+ scheduled = false;
1407
+ if (!buf) return;
1408
+ const out = buf;
1409
+ buf = "";
1410
+ writeRaw(out);
1411
+ };
1412
+ return {
1413
+ write(payload) {
1414
+ buf += payload;
1415
+ if (buf.length >= 16384) return flush();
1416
+ if (!scheduled) {
1417
+ scheduled = true;
1418
+ deferFlush(flush);
1419
+ }
1420
+ },
1421
+ flush,
1422
+ end() {
1423
+ flush();
1424
+ endRaw();
1425
+ }
1426
+ };
1427
+ };
1428
+ const guardSink = w => ({
1429
+ write(payload) {
1430
+ if (dead) return;
1431
+ try {
1432
+ w.write(payload);
1433
+ } catch (_) {
1434
+ abandon("sink");
1435
+ }
1436
+ },
1437
+ end() {
1438
+ if (dead) return;
1439
+ try {
1440
+ w.end();
1441
+ } catch (_) {
1442
+ abandon("sink");
1443
+ }
1444
+ }
1445
+ });
1446
+ const blockingPromises = new Set();
1447
+ const canBatchStubs = !options.serializer && !options.sink;
1448
+ let stubBatch = null;
1449
+ const STUB_BATCH_KEY = "$B";
1450
+ const flushStubBatch = () => {
1451
+ if (!stubBatch) return;
1452
+ const batch = stubBatch;
1453
+ stubBatch = null;
1454
+ if (batch.size === 1) {
1455
+ const [id, p] = batch.entries().next().value;
1456
+ serializer.write(id, p);
1457
+ return;
1458
+ }
1459
+ const obj = {};
1460
+ for (const [id, p] of batch) obj[id] = p;
1461
+ serializer.write(STUB_BATCH_KEY, obj);
1462
+ pushTask(`(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r["${STUB_BATCH_KEY}"]})(_$HY.r["${STUB_BATCH_KEY}"])`);
1463
+ };
1464
+ let headerEmitted = false;
1465
+ const pushTask = task => {
1466
+ if (noScripts) return;
1467
+ if (!headerEmitted) {
1468
+ headerEmitted = true;
1469
+ tasks += getLocalHeaderScript(renderId);
1470
+ }
1471
+ tasks += task + ";";
1472
+ if (!timer && firstFlushed) {
1473
+ timer = true;
1474
+ queue(() => queue(writeTasks));
1475
+ }
1476
+ };
1477
+ const onDone = () => {
1478
+ writeTasks();
1479
+ lastBlockingSize = blockingPromises.size;
1480
+ doShell();
1481
+ onCompleteAll && onCompleteAll({
1482
+ write(v) {
1483
+ !completed && buffer.write(v);
1484
+ }
1485
+ });
1486
+ writable && writable.end();
1487
+ completed = true;
1488
+ if (firstFlushed) dispose();
1489
+ };
1490
+ const sink = {
1491
+ data(payload) {
1492
+ pushTask(payload);
1493
+ },
1494
+ fragment(key, value, meta) {
1495
+ const deferActivation = !!meta.revealGroup;
1496
+ const styles = meta.styles;
1497
+ for (let i = 0; i < styles.inline.length; i++) {
1498
+ buffer.write(renderInlineStyle(styles.inline[i], nonce));
1499
+ }
1500
+ if (styles.links.length) {
1501
+ const styleAttr = nonceAttr(nonce, "style");
1502
+ emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
1503
+ writeTasks();
1504
+ for (const entry of styles.links) {
1505
+ buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}"${styleAttr} onload="$dfc('${key}')" onerror="$dfc('${key}')">` : `<link${entry.attrHtml}${styleAttr} onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
1506
+ }
1507
+ buffer.write(`<template id="${key}">${value}</template>`);
1508
+ } else {
1509
+ buffer.write(`<template id="${key}">${value}</template>`);
1510
+ if (!deferActivation) {
1511
+ emitTask(`$df("${key}")`);
1512
+ }
1513
+ }
1514
+ },
1515
+ reveal(keys, meta) {
1516
+ emitTask(`${meta.fallback ? "$dflj" : "$dfj"}(${JSON.stringify(keys)})`);
1517
+ },
1518
+ asset(type, value) {
1519
+ if (type === "module") {
1520
+ buffer.write(`<link rel="modulepreload" href="${value}"${nonceAttr(nonce, "script")}>`);
1521
+ } else if (type === "preload") {
1522
+ buffer.write(`<link${value.attrHtml}>`);
1523
+ } else if (type === "inline-style") {
1524
+ buffer.write(renderInlineStyle(value, nonce));
1525
+ } else if (type === "head-tag") {
1526
+ buffer.write(value);
1527
+ }
1528
+ },
1529
+ shell(shellHtml, meta) {
1530
+ buffer.write(assembleDocument(shellHtml, meta.preloads, meta.preloadLinks, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
1531
+ },
1532
+ ...options.sink
1533
+ };
1534
+ const serializer = (options.serializer || createHydrationSerializer)({
1535
+ scopeId: options.renderId,
1536
+ plugins: options.plugins,
1537
+ onData: payload => sink.data(payload),
1538
+ onDone,
1539
+ onError: serializerErrorHook(options.onError)
1540
+ });
1541
+ let rootAssetsSerialized = false;
1542
+ const serializeRootAssets = () => {
1543
+ if (rootAssetsSerialized) return;
1544
+ rootAssetsSerialized = true;
1545
+ serializeFragmentAssets("", tracking.boundaryModules, context, renderId);
1546
+ };
1547
+ let holds = 0;
1548
+ const flushEnd = () => {
1549
+ if (!registry.size && !holds) {
1550
+ serializeRootAssets();
1551
+ queue(() => queue(() => {
1552
+ if (context.live.end) {
1553
+ const end = context.live.end;
1554
+ context.live.end = null;
1555
+ end();
1556
+ }
1557
+ flushStubBatch();
1558
+ serializer.flush();
1559
+ }));
1560
+ }
1561
+ };
1562
+ const registry = new Map();
1563
+ const pendingSerialized = new Map();
1564
+ const guardedChannels = new WeakMap();
1565
+ const verdictNow = error => {
1566
+ throw ssrSanitizeError(error, null);
1567
+ };
1568
+ const guardChannel = p => {
1569
+ if (!p || typeof p !== "object" || "__SEROVAL_STREAM__" in p) return p;
1570
+ const thenable = typeof p.then === "function";
1571
+ const iterable = !thenable && typeof p[Symbol.asyncIterator] === "function";
1572
+ if (!thenable && !iterable) return p;
1573
+ let guarded = guardedChannels.get(p);
1574
+ if (guarded === undefined) {
1575
+ guarded = thenable ? p.then(undefined, verdictNow) : {
1576
+ [Symbol.asyncIterator]() {
1577
+ const iterator = p[Symbol.asyncIterator]();
1578
+ return {
1579
+ next: value => iterator.next(value).then(undefined, verdictNow),
1580
+ return: value => iterator.return ? iterator.return(value) : Promise.resolve({
1581
+ done: true,
1582
+ value
1583
+ }),
1584
+ throw: error => iterator.throw ? iterator.throw(error) : Promise.reject(error)
1585
+ };
1586
+ }
1587
+ };
1588
+ guardedChannels.set(p, guarded);
1589
+ }
1590
+ return guarded;
1591
+ };
1592
+ const trackSerialized = (id, p) => {
1593
+ let settle;
1594
+ const raced = Promise.race([p, new Promise(r => settle = r)]);
1595
+ pendingSerialized.set(id, settle);
1596
+ const drop = () => pendingSerialized.delete(id);
1597
+ p.then(drop, drop);
1598
+ return raced;
1599
+ };
1600
+ const abandonSubtree = (key, error) => {
1601
+ let fragments = 0;
1602
+ let serialized = 0;
1603
+ for (const [k, entry] of registry) {
1604
+ if (k.length > key.length && k.startsWith(key)) {
1605
+ registry.delete(k);
1606
+ entry.resolve();
1607
+ fragments++;
1608
+ }
1609
+ }
1610
+ for (const [id, settle] of pendingSerialized) {
1611
+ if (id.startsWith(key)) {
1612
+ pendingSerialized.delete(id);
1613
+ settle();
1614
+ serialized++;
1615
+ }
1616
+ }
1617
+ if ((fragments || serialized)) emitFinding({
1618
+ code: "SSR_SUBTREE_ABANDONED",
1619
+ kind: "ssr",
1620
+ severity: "warn",
1621
+ message: `[SSR_SUBTREE_ABANDONED] Fragment '${key}' failed with ${fragments} nested fragment(s) and ` + `${serialized} serialized value(s) still pending; the subtree was discarded and the client ` + `renders it from scratch.`,
1622
+ data: {
1623
+ fragment: key,
1624
+ fragments,
1625
+ serialized,
1626
+ error
1627
+ }
1628
+ }, null);
1629
+ };
1630
+ const writeTasks = () => {
1631
+ if (tasks.length && !completed && firstFlushed) {
1632
+ buffer.write(`<script${nonceAttr(nonce, "script")}>${tasks}</script>`);
1633
+ tasks = "";
1634
+ }
1635
+ timer = null;
1636
+ };
1637
+ let context;
1638
+ let writable;
1639
+ let tmp = "";
1640
+ let tasks = "";
1641
+ let firstFlushed = false;
1642
+ let completed = false;
1643
+ let shellCompleted = false;
1644
+ let scriptFlushed = false;
1645
+ let headStyles;
1646
+ const revealGroups = new Map();
1647
+ let timer = null;
1648
+ const emitTask = task => {
1649
+ pushTask(`${task}${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
1650
+ scriptFlushed = true;
1651
+ };
1652
+ function resolveRevealKeys(groupOrKeys, release, consume) {
1653
+ if (Array.isArray(groupOrKeys)) return groupOrKeys.slice();
1654
+ let group = revealGroups.get(groupOrKeys);
1655
+ if (!group) {
1656
+ if (!release) return;
1657
+ group = {
1658
+ order: [],
1659
+ keys: new Set(),
1660
+ released: true
1661
+ };
1662
+ revealGroups.set(groupOrKeys, group);
1663
+ } else if (release) group.released = true;
1664
+ if (!group.order.length) return;
1665
+ const keys = group.order.slice();
1666
+ if (consume) revealGroups.delete(groupOrKeys);
1667
+ return keys;
1668
+ }
1669
+ let rootHoles = null;
1670
+ let nextHoleId = 0;
1671
+ let buffer = {
1672
+ write(payload) {
1673
+ tmp += payload;
1674
+ }
1675
+ };
1676
+ const tracking = createAssetTracking();
1677
+ const headRegistry = createHeadRegistry();
1678
+ let headScriptFlushed = false;
1679
+ const emitHeadOps = (key, ops) => {
1680
+ const payload = JSON.stringify(ops).replace(/</g, "\\u003C");
1681
+ emitTask(`${!headScriptFlushed ? HEAD_SCRIPT : ""}(_$HY.hp=_$HY.hp||{})[${JSON.stringify(key)}]=${payload}`);
1682
+ headScriptFlushed = true;
1683
+ };
1684
+ sharedConfig.context = context = {
1685
+ async: true,
1686
+ nonce: options.nonce,
1687
+ live: {},
1688
+ registerHeadTags(tags) {
1689
+ registerHeadTags(headRegistry, context, tracking,
1690
+ (markup, gateEntry) => {
1691
+ if (!firstFlushed) {
1692
+ headRegistry.eagerHtml += markup;
1693
+ if (gateEntry) gateEntry.emitted = true;
1694
+ } else if (!gateEntry || !tracking.currentBoundaryId) {
1695
+ sink.asset("head-tag", markup);
1696
+ }
1697
+ }, nonce, tags);
1698
+ },
1699
+ registerAsset(type, value) {
1700
+ if (type === "preload") {
1701
+ const entry = registerPreloadLink(tracking, headRegistry, value, nonce);
1702
+ if (entry && firstFlushed) sink.asset("preload", entry);
1703
+ return;
1704
+ }
1705
+ if (type === "inline-style") {
1706
+ const entry = tracking.registerInlineStyle(value);
1707
+ if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
1708
+ entry.emitted = true;
1709
+ sink.asset("inline-style", entry);
1710
+ }
1711
+ return;
1712
+ }
1713
+ if (tracking.currentBoundaryId && type === "style") {
1714
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
1715
+ if (!styles) {
1716
+ styles = new Set();
1717
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
1718
+ }
1719
+ styles.add(value);
1720
+ }
1721
+ if (!tracking.emittedAssets.has(value)) {
1722
+ tracking.emittedAssets.add(value);
1723
+ if (firstFlushed) sink.asset(type, value);
1724
+ }
1725
+ },
1726
+ block(p) {
1727
+ if (!firstFlushed) blockingPromises.add(p);
1728
+ },
1729
+ hold() {
1730
+ holds++;
1731
+ let released = false;
1732
+ return () => {
1733
+ if (released) return;
1734
+ released = true;
1735
+ holds--;
1736
+ if (!holds) queue(flushEnd);
1737
+ };
1738
+ },
1739
+ replace(id, payloadFn) {
1740
+ if (firstFlushed) return;
1741
+ const placeholder = `<!--!$${id}-->`;
1742
+ const first = html.indexOf(placeholder);
1743
+ if (first === -1) return;
1744
+ const last = html.indexOf(`<!--!$/${id}-->`, first + placeholder.length);
1745
+ html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
1746
+ },
1747
+ serialize(id, p, deferStream) {
1748
+ if (sharedConfig.context.noHydrate) return;
1749
+ p = guardChannel(p);
1750
+ if (p && typeof p === "object" && typeof p.then === "function") {
1751
+ if (!firstFlushed && deferStream) {
1752
+ blockingPromises.add(p);
1753
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
1754
+ return;
1755
+ }
1756
+ p = trackSerialized(id, p);
1757
+ if (!firstFlushed && canBatchStubs && !shellCompleted) {
1758
+ (stubBatch ||= new Map()).set(id, p);
1759
+ return;
1760
+ }
1761
+ }
1762
+ serializer.write(id, p);
1763
+ },
1764
+ escape: escape,
1765
+ resolve: resolveSSRNode,
1766
+ ssr: ssr,
1767
+ registerFragment(key, options) {
1768
+ const revealGroup = options && options.revealGroup;
1769
+ if (revealGroup) {
1770
+ let group = revealGroups.get(revealGroup);
1771
+ if (!group) {
1772
+ group = {
1773
+ order: [],
1774
+ keys: new Set(),
1775
+ released: false
1776
+ };
1777
+ revealGroups.set(revealGroup, group);
1778
+ }
1779
+ if (!group.keys.has(key)) {
1780
+ group.keys.add(key);
1781
+ group.order.push(key);
1782
+ }
1783
+ if (group.released) {
1784
+ throw new Error("registerFragment() for reveal group '" + revealGroup + "' was called after revealFragments(). Ensure template payload is emitted before grouped reveal.");
1785
+ }
1786
+ }
1787
+ if (!registry.has(key)) {
1788
+ let resolve, reject;
1789
+ const p = new Promise((r, rej) => (resolve = r, reject = rej));
1790
+ registry.set(key, {
1791
+ resolve: err => queue(() => queue(() => {
1792
+ err ? reject(ssrSanitizeError(err, null)) : resolve(true);
1793
+ queue(flushEnd);
1794
+ }))
1795
+ });
1796
+ if (canBatchStubs && !shellCompleted) (stubBatch ||= new Map()).set(key + "_fr", p);else serializer.write(key + "_fr", p);
1797
+ }
1798
+ return (value, error) => {
1799
+ if (registry.has(key)) {
1800
+ const item = registry.get(key);
1801
+ registry.delete(key);
1802
+ if (error) abandonSubtree(key, error);
1803
+ if (item.children && !error) {
1804
+ for (const k in item.children) {
1805
+ value = replacePlaceholder(value, k, item.children[k]);
1806
+ }
1807
+ }
1808
+ const parentKey = waitForFragments(registry, key);
1809
+ if (parentKey) {
1810
+ const parent = registry.get(parentKey);
1811
+ parent.children ||= {};
1812
+ parent.children[key] = value !== undefined ? value : "";
1813
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
1814
+ propagateBoundaryStyles(key, parentKey, tracking);
1815
+ adoptHeadBoundary(headRegistry, key, parentKey);
1816
+ item.resolve();
1817
+ return;
1818
+ }
1819
+ if (!completed) {
1820
+ if (error) dropHeadBoundary(headRegistry, key);
1821
+ if (!firstFlushed) {
1822
+ queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
1823
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
1824
+ item.resolve(error);
1825
+ } else {
1826
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
1827
+ const styles = collectStreamStyles(key, tracking, headStyles);
1828
+ const headOps = error ? null : flushHeadFragment(headRegistry, key, nonce);
1829
+ if (headOps) emitHeadOps(key, headOps);
1830
+ sink.fragment(key, resolveSSRSelectValues(value !== undefined ? value : " "), {
1831
+ styles,
1832
+ revealGroup,
1833
+ error: error ? ssrSanitizeError(error, null) : error
1834
+ });
1835
+ item.resolve(error);
1836
+ }
1837
+ }
1838
+ }
1839
+ return firstFlushed;
1840
+ };
1841
+ },
1842
+ revealFragments(groupOrKeys) {
1843
+ const keys = resolveRevealKeys(groupOrKeys, true, true);
1844
+ if (!keys) return;
1845
+ sink.reveal(keys, {
1846
+ fallback: false
1847
+ });
1848
+ },
1849
+ revealFallbacks(groupOrKeys) {
1850
+ const keys = resolveRevealKeys(groupOrKeys, false, false);
1851
+ if (!keys) return;
1852
+ sink.reveal(keys, {
1853
+ fallback: true
1854
+ });
1855
+ }
1856
+ };
1857
+ applyAssetTracking(context, tracking, manifest, noScripts);
1858
+ context.failRender = failRender;
1859
+ context.errorPolicy = options.onError;
1860
+ context.flushed = () => firstFlushed;
1861
+ context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
1862
+ registerEntryAssets(manifest);
1863
+ let html = createRoot(d => {
1864
+ dispose = () => {
1865
+ context.trace = undefined;
1866
+ d();
1867
+ };
1868
+ const res = resolveSSRNode(escape(code()));
1869
+ if (!res.h.length) return res.t[0];
1870
+ rootHoles = [];
1871
+ let out = res.t[0];
1872
+ for (let i = 0; i < res.h.length; i++) {
1873
+ const id = nextHoleId++;
1874
+ rootHoles.push({
1875
+ id,
1876
+ fn: res.h[i]
1877
+ });
1878
+ out += `<!--rh${id}-->` + res.t[i + 1];
1879
+ }
1880
+ for (const p of res.p) blockingPromises.add(p);
1881
+ return out;
1882
+ }, {
1883
+ id: renderId
1884
+ });
1885
+ function resolveRootHoles() {
1886
+ if (!rootHoles) return true;
1887
+ const pending = [];
1888
+ for (const {
1889
+ id,
1890
+ fn
1891
+ } of rootHoles) {
1892
+ const marker = `<!--rh${id}-->`;
1893
+ const res = resolveSSRNode(fn);
1894
+ if (!res.h.length) {
1895
+ html = html.replace(marker, res.t[0]);
1896
+ } else {
1897
+ let out = res.t[0];
1898
+ for (let j = 0; j < res.h.length; j++) {
1899
+ const newId = nextHoleId++;
1900
+ pending.push({
1901
+ id: newId,
1902
+ fn: res.h[j]
1903
+ });
1904
+ out += `<!--rh${newId}-->` + res.t[j + 1];
1905
+ }
1906
+ html = html.replace(marker, out);
1907
+ for (const p of res.p) blockingPromises.add(p);
1908
+ }
1909
+ }
1910
+ if (pending.length) {
1911
+ rootHoles = pending;
1912
+ return false;
1913
+ }
1914
+ rootHoles = null;
1915
+ return true;
1916
+ }
1917
+ function doShell() {
1918
+ if (shellCompleted) return;
1919
+ sharedConfig.context = context;
1920
+ if (blockingPromises.size !== lastBlockingSize) return;
1921
+ if (!resolveRootHoles()) return;
1922
+ if (blockingPromises.size !== lastBlockingSize) return;
1923
+ if (!headShellReady(headRegistry, p => blockingPromises.add(p))) return;
1924
+ headStyles = new Set();
1925
+ for (const url of tracking.emittedAssets) {
1926
+ if (isCssUrl(url)) headStyles.add(url);
1927
+ }
1928
+ serializeRootAssets();
1929
+ flushStubBatch();
1930
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k), noScripts, traceMetaMarkup(context.trace));
1931
+ sink.shell(resolveSSRSelectValues(html), {
1932
+ preloads: tracking.emittedAssets,
1933
+ preloadLinks: tracking.preloadLinks,
1934
+ inlineStyles: tracking.inlineStyles,
1935
+ tasks,
1936
+ head
1937
+ });
1938
+ tasks = "";
1939
+ onCompleteShell && onCompleteShell({
1940
+ write(v) {
1941
+ !completed && buffer.write(v);
1942
+ }
1943
+ });
1944
+ shellCompleted = true;
1945
+ }
1946
+ const MIN_DRAIN_TURNS = 8;
1947
+ let lastBlockingSize = -1;
1948
+ let lastRegistrySize = -1;
1949
+ let drainTurn = 0;
1950
+ const scheduleFlush = (fn, awaited) => {
1951
+ const attempt = () => {
1952
+ flushStubBatch();
1953
+ if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1954
+ if (registry.size !== lastRegistrySize) drainTurn = 0;
1955
+ lastRegistrySize = registry.size;
1956
+ queue(attempt);
1957
+ return;
1958
+ }
1959
+ fn();
1960
+ };
1961
+ const progressed = awaited !== lastBlockingSize;
1962
+ lastBlockingSize = awaited;
1963
+ lastRegistrySize = -1;
1964
+ drainTurn = 0;
1965
+ progressed ? queue(attempt) : setTimeout(attempt);
1966
+ };
1967
+ let cachedReadable;
1968
+ let consumer;
1969
+ const claimConsumer = name => {
1970
+ if (consumer && consumer !== name) {
1971
+ throw new Error(`renderToStream result was already consumed via \`${consumer}\`; cannot also consume it via \`${name}\`. Use exactly one of \`pipe\`, \`pipeTo\`, or \`readable\`.`);
1972
+ }
1973
+ consumer = name;
1974
+ };
1975
+ const pipeToImpl = w => {
1976
+ let resolve;
1977
+ const p = new Promise(r => resolve = r);
1978
+ function flush() {
1979
+ allSettled(blockingPromises).then(awaited => {
1980
+ scheduleFlush(() => {
1981
+ if (dead) return resolve();
1982
+ try {
1983
+ doShell();
1984
+ } catch (err) {
1985
+ failRootRender(err);
1986
+ return resolve();
1987
+ }
1988
+ if (!shellCompleted) return flush();
1989
+ const encoder = new TextEncoder();
1990
+ const writer = w.getWriter();
1991
+ let pendingWrites = Promise.resolve();
1992
+ let ended = false;
1993
+ const failed = () => {
1994
+ if (!ended) {
1995
+ abandon("consumer");
1996
+ resolve();
1997
+ }
1998
+ };
1999
+ writer.closed && writer.closed.catch(failed);
2000
+ buffer = writable = coalesceWrites(payload => {
2001
+ pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
2002
+ }, () => {
2003
+ pendingWrites.then(() => {
2004
+ ended = true;
2005
+ writer.releaseLock();
2006
+ w.close().catch(() => {});
2007
+ resolve();
2008
+ });
2009
+ });
2010
+ buffer.write(tmp);
2011
+ buffer.flush();
2012
+ firstFlushed = true;
2013
+ if (completed) {
2014
+ dispose();
2015
+ writable.end();
2016
+ } else flushEnd();
2017
+ }, awaited);
2018
+ });
2019
+ }
2020
+ flush();
2021
+ return p;
2022
+ };
2023
+ return {
2024
+ then(onFulfilled, onRejected) {
2025
+ const freezeHead = () => {
2026
+ if (requestEvent && requestEvent.response) commitResponseStub(requestEvent.response, {
2027
+ event: requestEvent
2028
+ });
2029
+ };
2030
+ const p = new Promise(resolve => {
2031
+ function complete() {
2032
+ freezeHead();
2033
+ dispose();
2034
+ resolve(tmp);
2035
+ }
2036
+ if (onCompleteAll) {
2037
+ let ogComplete = onCompleteAll;
2038
+ onCompleteAll = options => {
2039
+ ogComplete(options);
2040
+ complete();
2041
+ };
2042
+ } else onCompleteAll = complete;
2043
+ function flush() {
2044
+ allSettled(blockingPromises).then(awaited => {
2045
+ scheduleFlush(() => {
2046
+ try {
2047
+ if (blockingPromises.size !== lastBlockingSize || !resolveRootHoles() || blockingPromises.size !== lastBlockingSize || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
2048
+ } catch (err) {
2049
+ failRootRender(err);
2050
+ return resolve(tmp);
2051
+ }
2052
+ queue(flushEnd);
2053
+ }, awaited);
2054
+ });
2055
+ }
2056
+ flush();
2057
+ });
2058
+ return p.then(onFulfilled, onRejected);
2059
+ },
2060
+ pipe(w) {
2061
+ claimConsumer("pipe");
2062
+ function flush() {
2063
+ allSettled(blockingPromises).then(awaited => {
2064
+ scheduleFlush(() => {
2065
+ if (dead) return;
2066
+ try {
2067
+ doShell();
2068
+ } catch (err) {
2069
+ failRootRender(err);
2070
+ try {
2071
+ w.end();
2072
+ } catch (_) {}
2073
+ return;
2074
+ }
2075
+ if (!shellCompleted) return flush();
2076
+ const sink = guardSink(w);
2077
+ buffer = writable = coalesceWrites(sink.write, sink.end);
2078
+ buffer.write(tmp);
2079
+ buffer.flush();
2080
+ firstFlushed = true;
2081
+ if (completed) {
2082
+ dispose();
2083
+ writable.end();
2084
+ } else flushEnd();
2085
+ }, awaited);
2086
+ });
2087
+ }
2088
+ flush();
2089
+ },
2090
+ pipeTo(w) {
2091
+ claimConsumer("pipeTo");
2092
+ return pipeToImpl(w);
2093
+ },
2094
+ get readable() {
2095
+ claimConsumer("readable");
2096
+ if (!cachedReadable) {
2097
+ const t = new TransformStream();
2098
+ pipeToImpl(t.writable);
2099
+ cachedReadable = t.readable;
2100
+ }
2101
+ return cachedReadable;
2102
+ }
2103
+ };
2104
+ }
2105
+ function buildAsyncWrap(err, node) {
2106
+ const p = ssrHandleError(err);
2107
+ if (!p) return null;
2108
+ if (node.$rw) return {
2109
+ fn: node,
2110
+ p
2111
+ };
2112
+ const owner = getOwner();
2113
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
2114
+ const suppress = node.$lhSuppress || live && (live.suppressed || live.sweeping);
2115
+ if (!owner) {
2116
+ if (suppress) node.$lhSuppress = true;
2117
+ return {
2118
+ fn: node,
2119
+ p
2120
+ };
2121
+ }
2122
+ const fn = () => runWithOwner(owner, node);
2123
+ fn.$rw = true;
2124
+ if (suppress) fn.$lhSuppress = true;
2125
+ if (node.$lhSkip) fn.$lhSkip = true;
2126
+ if (node.$lhBinding) fn.$lhBinding = node.$lhBinding;
2127
+ return {
2128
+ fn,
2129
+ p
2130
+ };
2131
+ }
2132
+ function ssrFirstGroupHit(hole) {
2133
+ try {
2134
+ return hole();
2135
+ } catch (err) {
2136
+ return buildAsyncWrap(err, hole);
2137
+ }
2138
+ }
2139
+ function tryResolveFunctionHole(hole) {
2140
+ let value;
2141
+ try {
2142
+ value = hole();
2143
+ } catch (err) {
2144
+ return buildAsyncWrap(err, hole) || "";
2145
+ }
2146
+ const t = typeof value;
2147
+ if (t === "string") return value;
2148
+ if (t === "number") return "" + value;
2149
+ if (value == null || t === "boolean") return "";
2150
+ return tryResolveString(value);
2151
+ }
2152
+ function mergeTemplateInto(result, node) {
2153
+ result.t[result.t.length - 1] += node.t[0];
2154
+ if (node.t.length > 1) {
2155
+ result.t.push(...node.t.slice(1));
2156
+ result.h.push(...node.h);
2157
+ result.p.push(...node.p);
2158
+ }
2159
+ }
2160
+ function appendResolvedNode(result, node) {
2161
+ if (node.fn !== undefined) {
2162
+ result.h.push(node.fn);
2163
+ result.p.push(node.p);
2164
+ result.t.push("");
2165
+ } else if (node.merge !== undefined) mergeTemplateInto(result, node.merge);else resolveSSRNode(node.bail, result);
2166
+ }
2167
+ let _lastGroupFn = null;
2168
+ let _lastGroupArr = null;
2169
+ let _lastGroupErr = null;
2170
+ function ssrGroupSlot(fn, idx) {
2171
+ return () => {
2172
+ if (idx > 0 && _lastGroupFn === fn) {
2173
+ if (_lastGroupArr !== null) return _lastGroupArr[idx];
2174
+ throw _lastGroupErr;
2175
+ }
2176
+ _lastGroupFn = fn;
2177
+ _lastGroupArr = null;
2178
+ _lastGroupErr = null;
2179
+ try {
2180
+ _lastGroupArr = fn();
2181
+ return _lastGroupArr[idx];
2182
+ } catch (err) {
2183
+ _lastGroupErr = err;
2184
+ throw err;
2185
+ }
2186
+ };
2187
+ }
2188
+ function wireErrorMessage(err) {
2189
+ const wire = ssrSanitizeError(err, null);
2190
+ return String(wire && wire.message || wire);
2191
+ }
2192
+ const holePositionCache = new WeakMap();
2193
+ function holeContentPositions(t) {
2194
+ let cached = holePositionCache.get(t);
2195
+ if (cached) return cached;
2196
+ const pos = [];
2197
+ const openOff = [];
2198
+ const closeOff = [];
2199
+ let inTag = false;
2200
+ let quote = "";
2201
+ let curOpen = null;
2202
+ let scanningName = false;
2203
+ for (let i = 0; i < t.length; i++) {
2204
+ const seg = t[i];
2205
+ let close = -1;
2206
+ const openAtStart = inTag;
2207
+ let reopened = false;
2208
+ for (let j = 0; j < seg.length; j++) {
2209
+ const ch = seg[j];
2210
+ if (quote) {
2211
+ if (ch === quote) quote = "";
2212
+ } else if (inTag) {
2213
+ if (scanningName && (ch === " " || ch === "\t" || ch === "\n" || ch === ">" || ch === "/")) {
2214
+ scanningName = false;
2215
+ curOpen = {
2216
+ seg: i,
2217
+ off: j
2218
+ };
2219
+ }
2220
+ if (ch === '"' || ch === "'") quote = ch;else if (ch === ">") {
2221
+ inTag = false;
2222
+ if (openAtStart && !reopened && close === -1) close = j;
2223
+ curOpen = null;
2224
+ }
2225
+ } else if (ch === "<") {
2226
+ inTag = true;
2227
+ scanningName = true;
2228
+ reopened = true;
2229
+ curOpen = null;
2230
+ }
2231
+ }
2232
+ if (inTag && scanningName) {
2233
+ scanningName = false;
2234
+ curOpen = {
2235
+ seg: i,
2236
+ off: seg.length
2237
+ };
2238
+ }
2239
+ closeOff.push(close);
2240
+ openOff.push(inTag && curOpen && curOpen.seg === i ? curOpen.off : -1);
2241
+ if (i < t.length - 1) pos.push(!inTag);
2242
+ }
2243
+ cached = {
2244
+ pos,
2245
+ openOff,
2246
+ closeOff
2247
+ };
2248
+ holePositionCache.set(t, cached);
2249
+ return cached;
2250
+ }
2251
+ function createLiveHoles(sink, scoped) {
2252
+ let nextId = 0;
2253
+ const stamp = typeof creationStamp === "function" ? creationStamp : () => 0;
2254
+ const inScope = scoped && typeof inServerComponentScope === "function" ? inServerComponentScope : null;
2255
+ const stripMarkers = html => html.replace(/<!--lh:\/?\d+-->/g, "");
2256
+ const swept = (owner, ctx, fn) => {
2257
+ const prev = sharedConfig.context;
2258
+ sharedConfig.context = ctx;
2259
+ try {
2260
+ return owner ? runWithOwner(owner, fn) : fn();
2261
+ } finally {
2262
+ sharedConfig.context = prev;
2263
+ }
2264
+ };
2265
+ function resolveHoleValue(hole) {
2266
+ const result = {
2267
+ t: [""],
2268
+ h: [],
2269
+ p: []
2270
+ };
2271
+ try {
2272
+ resolveSSRNode(hole(), result);
2273
+ } catch (err) {
2274
+ const wrap = buildAsyncWrap(err, hole);
2275
+ if (!wrap) throw err;
2276
+ result.h.push(wrap.fn);
2277
+ result.p.push(wrap.p);
2278
+ result.t.push("");
2279
+ }
2280
+ return result;
2281
+ }
2282
+ function closeChildren(b) {
2283
+ for (const c of b.children) {
2284
+ c.closed = true;
2285
+ if (c.key) sink.closeBinding(c.key);
2286
+ closeChildren(c);
2287
+ }
2288
+ b.children.length = 0;
2289
+ }
2290
+ const engine = {
2291
+ suppressed: 0,
2292
+ sweeping: false,
2293
+ parent: null,
2294
+ recordStamp: 0,
2295
+ gateHit: false,
2296
+ content(hole) {
2297
+ if (hole.$lhSuppress) {
2298
+ const r = {
2299
+ t: [""],
2300
+ h: [],
2301
+ p: []
2302
+ };
2303
+ engine.suppressed++;
2304
+ try {
2305
+ try {
2306
+ resolveSSRNode(hole(), r);
2307
+ } catch (err) {
2308
+ const wrap = buildAsyncWrap(err, hole);
2309
+ if (wrap) {
2310
+ r.h.push(wrap.fn);
2311
+ r.p.push(wrap.p);
2312
+ r.t.push("");
2313
+ }
2314
+ }
2315
+ } finally {
2316
+ engine.suppressed--;
2317
+ }
2318
+ const b = hole.$lhBinding;
2319
+ if (b && !b.closed && !r.h.length && !engine.sweeping) {
2320
+ b.last = stripMarkers(r.t[0]);
2321
+ }
2322
+ return r.h.length ? r : r.t[0];
2323
+ }
2324
+ if (engine.suppressed || engine.sweeping) return null;
2325
+ if (hole.$lhSkip) return null;
2326
+ if (inScope && !inScope()) return null;
2327
+ const recordsBefore = engine.recordStamp;
2328
+ const ownersBefore = stamp();
2329
+ const owner = getOwner();
2330
+ const holeCtx = sharedConfig.context;
2331
+ const b = {
2332
+ key: null,
2333
+ children: [],
2334
+ last: null,
2335
+ closed: false,
2336
+ sweep() {
2337
+ if (b.closed) return;
2338
+ const prevSweeping = engine.sweeping;
2339
+ engine.sweeping = true;
2340
+ engine.gateHit = false;
2341
+ const sweepOwnersBefore = stamp();
2342
+ let res;
2343
+ try {
2344
+ res = swept(owner, holeCtx, () => resolveHoleValue(hole));
2345
+ } catch (err) {
2346
+ b.closed = true;
2347
+ sink.closeBinding(b.key);
2348
+ sink.error(b.key, wireErrorMessage(err));
2349
+ return;
2350
+ } finally {
2351
+ engine.sweeping = prevSweeping;
2352
+ }
2353
+ if (engine.gateHit || stamp() !== sweepOwnersBefore) {
2354
+ b.closed = true;
2355
+ sink.closeBinding(b.key);
2356
+ return;
2357
+ }
2358
+ if (res.h.length) return;
2359
+ const html = res.t[0];
2360
+ if (b.last === null || html === b.last) return;
2361
+ b.last = html;
2362
+ closeChildren(b);
2363
+ sink.hole(b.key, html);
2364
+ }
2365
+ };
2366
+ if (engine.parent) engine.parent.children.push(b);
2367
+ const prevParent = engine.parent;
2368
+ engine.parent = b;
2369
+ let value;
2370
+ let escalated = null;
2371
+ try {
2372
+ value = hole();
2373
+ } catch (err) {
2374
+ const wrap = buildAsyncWrap(err, hole);
2375
+ if (!wrap) {
2376
+ engine.parent = prevParent;
2377
+ closeChildren(b);
2378
+ return "";
2379
+ }
2380
+ escalated = wrap;
2381
+ }
2382
+ if (!escalated && (typeof value === "function" && value.$lhSkip || value !== null && typeof value === "object" && value.$slot)) {
2383
+ engine.parent = prevParent;
2384
+ const r = {
2385
+ t: [""],
2386
+ h: [],
2387
+ p: []
2388
+ };
2389
+ engine.suppressed++;
2390
+ try {
2391
+ resolveSSRNode(value, r);
2392
+ } finally {
2393
+ engine.suppressed--;
2394
+ }
2395
+ return r.h.length ? r : r.t[0];
2396
+ }
2397
+ let res;
2398
+ if (escalated) {
2399
+ closeChildren(b);
2400
+ escalated.fn.$lhSuppress = true;
2401
+ escalated.fn.$lhBinding = b;
2402
+ res = {
2403
+ t: ["", ""],
2404
+ h: [escalated.fn],
2405
+ p: [escalated.p]
2406
+ };
2407
+ } else {
2408
+ res = {
2409
+ t: [""],
2410
+ h: [],
2411
+ p: []
2412
+ };
2413
+ try {
2414
+ resolveSSRNode(value, res);
2415
+ } catch (_) {
2416
+ engine.parent = prevParent;
2417
+ closeChildren(b);
2418
+ return "";
2419
+ }
2420
+ }
2421
+ engine.parent = prevParent;
2422
+ if (engine.recordStamp !== recordsBefore || stamp() !== ownersBefore) {
2423
+ return res.h.length ? res : res.t[0];
2424
+ }
2425
+ const id = nextId++;
2426
+ const key = b.key = "lh:" + id;
2427
+ const open = `<!--lh:${id}-->`;
2428
+ const close = `<!--lh:/${id}-->`;
2429
+ if (!res.h.length) {
2430
+ b.last = stripMarkers(res.t[0]);
2431
+ sink.openBinding(key, b);
2432
+ return open + res.t[0] + close;
2433
+ }
2434
+ const t = res.t.slice();
2435
+ t[0] = open + t[0];
2436
+ t[t.length - 1] += close;
2437
+ sink.openBinding(key, b);
2438
+ return {
2439
+ t,
2440
+ h: res.h,
2441
+ p: res.p
2442
+ };
2443
+ },
2444
+ mint() {
2445
+ return nextId++;
2446
+ },
2447
+ active() {
2448
+ return !inScope || inScope();
2449
+ },
2450
+ attr(cap) {
2451
+ const owner = getOwner();
2452
+ const holeCtx = sharedConfig.context;
2453
+ const b = {
2454
+ key: "lha:" + cap.id,
2455
+ children: [],
2456
+ last: cap.base,
2457
+ closed: false,
2458
+ sweep() {
2459
+ if (b.closed) return;
2460
+ const prevSweeping = engine.sweeping;
2461
+ engine.sweeping = true;
2462
+ engine.gateHit = false;
2463
+ const sweepOwnersBefore = stamp();
2464
+ let html = "";
2465
+ try {
2466
+ let group = null;
2467
+ let groupVal = null;
2468
+ const run = () => {
2469
+ for (const part of cap.parts) {
2470
+ if (typeof part === "string") {
2471
+ html += part;
2472
+ continue;
2473
+ }
2474
+ let v;
2475
+ if (part.g) {
2476
+ if (group !== part.g) {
2477
+ group = part.g;
2478
+ groupVal = part.g();
2479
+ }
2480
+ v = groupVal[part.i];
2481
+ } else {
2482
+ v = part.f();
2483
+ }
2484
+ const vt = typeof v;
2485
+ if (vt === "string" || vt === "number") html += v;
2486
+ }
2487
+ };
2488
+ swept(owner, holeCtx, run);
2489
+ } catch (err) {
2490
+ if (ssrHandleError(err, true)) return;
2491
+ b.closed = true;
2492
+ sink.closeBinding(b.key);
2493
+ sink.error("lha:" + cap.id, wireErrorMessage(err));
2494
+ return;
2495
+ } finally {
2496
+ engine.sweeping = prevSweeping;
2497
+ }
2498
+ if (engine.gateHit || stamp() !== sweepOwnersBefore) {
2499
+ b.closed = true;
2500
+ sink.closeBinding(b.key);
2501
+ return;
2502
+ }
2503
+ if (html === b.last) return;
2504
+ const before = attrNames(b.last);
2505
+ const after = attrNames(html);
2506
+ const removed = before.filter(n => !after.includes(n));
2507
+ b.last = html;
2508
+ sink.attr(String(cap.id), html, removed);
2509
+ }
2510
+ };
2511
+ sink.openBinding(b.key, b);
2512
+ }
2513
+ };
2514
+ return engine;
2515
+ }
2516
+ function attrNames(text) {
2517
+ const names = [];
2518
+ const re = /(?:^|\s)([^\s=/>"']+)(?:="[^"]*")?/g;
2519
+ let m;
2520
+ while (m = re.exec(text)) names.push(m[1]);
2521
+ return names;
2522
+ }
2523
+ function ssr(t) {
2524
+ const len = arguments.length;
2525
+ if (len === 1) return {
2526
+ t
2527
+ };
2528
+ let s = t[0];
2529
+ let result = null;
2530
+ let lastGroup = null;
2531
+ let lastGroupVal = null;
2532
+ let lastGroupIdx = 0;
2533
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
2534
+ const hp = live ? holeContentPositions(t) : null;
2535
+ let lastOpen = null;
2536
+ let cap = null;
2537
+ if (live && hp.openOff[0] >= 0) lastOpen = {
2538
+ r: null,
2539
+ seg: -1,
2540
+ off: hp.openOff[0]
2541
+ };
2542
+ const captureStart = () => {
2543
+ if (cap) return true;
2544
+ if (!lastOpen || live.suppressed || live.sweeping || !live.active()) return false;
2545
+ if (lastOpen.r !== result || result !== null && lastOpen.seg !== result.t.length - 1) {
2546
+ return false;
2547
+ }
2548
+ const id = live.mint();
2549
+ const inject = ` data-lha="${id}"`;
2550
+ let prefix;
2551
+ if (result === null) {
2552
+ s = s.slice(0, lastOpen.off) + inject + s.slice(lastOpen.off);
2553
+ prefix = s.slice(lastOpen.off + inject.length);
2554
+ } else {
2555
+ const seg = result.t[lastOpen.seg];
2556
+ result.t[lastOpen.seg] = seg.slice(0, lastOpen.off) + inject + seg.slice(lastOpen.off);
2557
+ prefix = result.t[lastOpen.seg].slice(lastOpen.off + inject.length);
2558
+ }
2559
+ cap = {
2560
+ id,
2561
+ parts: [prefix],
2562
+ base: prefix
2563
+ };
2564
+ return true;
2565
+ };
2566
+ for (let i = 1; i < len; i++) {
2567
+ const hole = arguments[i];
2568
+ const ht = typeof hole;
2569
+ if (ht === "string") {
2570
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
2571
+ if (cap) {
2572
+ cap.parts.push(hole);
2573
+ cap.base += hole;
2574
+ }
2575
+ } else if (ht === "number") {
2576
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
2577
+ if (cap) {
2578
+ cap.parts.push("" + hole);
2579
+ cap.base += hole;
2580
+ }
2581
+ } else if (hole == null || ht === "boolean") ; else if (ht === "function" && hole.$g) {
2582
+ let value;
2583
+ let hasValue = false;
2584
+ if (lastGroup !== hole) {
2585
+ const r = ssrFirstGroupHit(hole);
2586
+ if (r !== null) {
2587
+ lastGroup = hole;
2588
+ lastGroupVal = r;
2589
+ lastGroupIdx = 0;
2590
+ if (!Array.isArray(r) && result === null) {
2591
+ result = {
2592
+ t: [s],
2593
+ h: [],
2594
+ p: []
2595
+ };
2596
+ s = "";
2597
+ }
2598
+ }
2599
+ }
2600
+ if (lastGroup === hole) {
2601
+ if (Array.isArray(lastGroupVal)) {
2602
+ value = lastGroupVal[lastGroupIdx++];
2603
+ hasValue = true;
2604
+ if (live && !hp.pos[i - 1] && captureStart()) {
2605
+ cap.parts.push({
2606
+ g: hole,
2607
+ i: lastGroupIdx - 1
2608
+ });
2609
+ }
2610
+ } else {
2611
+ cap = null;
2612
+ result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
2613
+ result.p.push(lastGroupVal.p);
2614
+ result.t.push("");
2615
+ }
2616
+ }
2617
+ if (hasValue) {
2618
+ const vt = typeof value;
2619
+ if (vt === "string" || vt === "number") {
2620
+ if (result === null) s += value;else result.t[result.t.length - 1] += value;
2621
+ if (cap && !hp.pos[i - 1]) cap.base += value;
2622
+ } else if (value == null || vt === "boolean") ; else if (result !== null) {
2623
+ resolveSSRNode(value, result);
2624
+ } else {
2625
+ const rs = tryResolveString(value);
2626
+ if (typeof rs === "string") {
2627
+ s += rs;
2628
+ } else {
2629
+ result = {
2630
+ t: [s],
2631
+ h: [],
2632
+ p: []
2633
+ };
2634
+ s = "";
2635
+ if (rs.merge !== undefined) mergeTemplateInto(result, rs.merge);else resolveSSRNode(rs.bail, result);
2636
+ }
2637
+ }
2638
+ }
2639
+ } else if (ht === "function") {
2640
+ let liveNode = null;
2641
+ if (live && hp.pos[i - 1] && (liveNode = live.content(hole)) !== null) {
2642
+ if (typeof liveNode === "string") {
2643
+ if (result === null) s += liveNode;else result.t[result.t.length - 1] += liveNode;
2644
+ } else {
2645
+ if (result === null) {
2646
+ result = {
2647
+ t: [s],
2648
+ h: [],
2649
+ p: []
2650
+ };
2651
+ s = "";
2652
+ }
2653
+ resolveSSRNode(liveNode, result);
2654
+ }
2655
+ } else if (result !== null) {
2656
+ const inTag = live && !hp.pos[i - 1];
2657
+ const capturing = inTag && captureStart();
2658
+ const li = capturing ? result.t.length - 1 : 0;
2659
+ const before = capturing ? result.t[li].length : 0;
2660
+ if (live) live.suppressed++;
2661
+ try {
2662
+ resolveSSRNode(hole, result);
2663
+ } finally {
2664
+ if (live) live.suppressed--;
2665
+ }
2666
+ if (capturing) {
2667
+ if (result.t.length - 1 === li) {
2668
+ cap.base += result.t[li].slice(before);
2669
+ cap.parts.push({
2670
+ f: hole
2671
+ });
2672
+ } else {
2673
+ cap = null;
2674
+ }
2675
+ }
2676
+ } else {
2677
+ const capturing = live && !hp.pos[i - 1] && captureStart();
2678
+ const r = tryResolveFunctionHole(hole);
2679
+ if (typeof r === "string") {
2680
+ s += r;
2681
+ if (capturing) {
2682
+ cap.base += r;
2683
+ cap.parts.push({
2684
+ f: hole
2685
+ });
2686
+ }
2687
+ } else {
2688
+ if (capturing) cap = null;
2689
+ result = {
2690
+ t: [s],
2691
+ h: [],
2692
+ p: []
2693
+ };
2694
+ s = "";
2695
+ appendResolvedNode(result, r);
2696
+ }
2697
+ }
2698
+ } else if (result !== null) {
2699
+ resolveSSRNode(hole, result);
2700
+ } else {
2701
+ const r = tryResolveString(hole);
2702
+ if (typeof r === "string") {
2703
+ s += r;
2704
+ } else {
2705
+ result = {
2706
+ t: [s],
2707
+ h: [],
2708
+ p: []
2709
+ };
2710
+ s = "";
2711
+ appendResolvedNode(result, r);
2712
+ }
2713
+ }
2714
+ const next = t[i];
2715
+ if (live) {
2716
+ if (cap) {
2717
+ const co = hp.closeOff[i];
2718
+ if (co >= 0) {
2719
+ const tail = next.slice(0, co);
2720
+ cap.parts.push(tail);
2721
+ cap.base += tail;
2722
+ live.attr(cap);
2723
+ cap = null;
2724
+ } else {
2725
+ cap.parts.push(next);
2726
+ cap.base += next;
2727
+ }
2728
+ }
2729
+ if (hp.openOff[i] >= 0) {
2730
+ lastOpen = result === null ? {
2731
+ r: null,
2732
+ seg: -1,
2733
+ off: s.length + hp.openOff[i]
2734
+ } : {
2735
+ r: result,
2736
+ seg: result.t.length - 1,
2737
+ off: result.t[result.t.length - 1].length + hp.openOff[i]
2738
+ };
2739
+ }
2740
+ }
2741
+ if (result === null) s += next;else result.t[result.t.length - 1] += next;
2742
+ }
2743
+ if (result === null) return {
2744
+ t: s
2745
+ };
2746
+ return result;
2747
+ }
2748
+ const CLAIM_PROP = /*#__PURE__*/Symbol.for("solid.claim-prop");
2749
+ const CLAIMS_STREAM = 1;
2750
+ const CLAIMS_DOCUMENT = 2;
2751
+ function resolveSSRSelectValues(html) {
2752
+ return html;
2753
+ }
2754
+ function escape(s, attr) {
2755
+ const t = typeof s;
2756
+ if (t !== "string") {
2757
+ if (!attr && Array.isArray(s)) {
2758
+ const joined = tryJoinPlainSSRArray(s);
2759
+ if (joined !== undefined) return joined;
2760
+ const src = s;
2761
+ s = s.slice();
2762
+ for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
2763
+ if (src.$slot) s.$slot = true;
2764
+ return s;
2765
+ }
2766
+ if (!attr && t === "function") return escapeLate(s);
2767
+ if (attr) {
2768
+ if (s == null || t === "boolean" || t === "number") return s;
2769
+ return escape(String(s), attr);
2770
+ }
2771
+ return s;
2772
+ }
2773
+ const i = s.search(attr ? ESCAPE_ATTR : ESCAPE_CONTENT);
2774
+ if (i < 0) return s;
2775
+ return escapeSlow(s, attr, i);
2776
+ }
2777
+ function escapeLate(fn) {
2778
+ if (fn.$esc) return fn;
2779
+ const w = () => escape(fn());
2780
+ w.$esc = true;
2781
+ if (fn.$lhSkip) w.$lhSkip = true;
2782
+ if (fn.$lhSuppress) w.$lhSuppress = true;
2783
+ if (fn.$lhBinding) w.$lhBinding = fn.$lhBinding;
2784
+ return w;
2785
+ }
2786
+ const ESCAPE_CONTENT = /[&<]/;
2787
+ const ESCAPE_ATTR = /[&"<]/;
2788
+ function escapeSlow(s, attr, start) {
2789
+ if (attr) return escapeAttrSlow(s, start);
2790
+ const c0 = s.charCodeAt(start);
2791
+ let iDelim = c0 === 60 ? start : s.indexOf("<", start);
2792
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
2793
+ let left = 0,
2794
+ out = "";
2795
+ while (iDelim >= 0 && iAmp >= 0) {
2796
+ if (iDelim < iAmp) {
2797
+ if (left < iDelim) out += s.substring(left, iDelim);
2798
+ out += "&lt;";
2799
+ left = iDelim + 1;
2800
+ iDelim = s.indexOf("<", left);
2801
+ } else {
2802
+ if (left < iAmp) out += s.substring(left, iAmp);
2803
+ out += "&amp;";
2804
+ left = iAmp + 1;
2805
+ iAmp = s.indexOf("&", left);
2806
+ }
2807
+ }
2808
+ if (iDelim >= 0) {
2809
+ do {
2810
+ if (left < iDelim) out += s.substring(left, iDelim);
2811
+ out += "&lt;";
2812
+ left = iDelim + 1;
2813
+ iDelim = s.indexOf("<", left);
2814
+ } while (iDelim >= 0);
2815
+ } else while (iAmp >= 0) {
2816
+ if (left < iAmp) out += s.substring(left, iAmp);
2817
+ out += "&amp;";
2818
+ left = iAmp + 1;
2819
+ iAmp = s.indexOf("&", left);
2820
+ }
2821
+ return left < s.length ? out + s.substring(left) : out;
2822
+ }
2823
+ function escapeAttrSlow(s, start) {
2824
+ const c0 = s.charCodeAt(start);
2825
+ let iQuot = c0 === 34 ? start : s.indexOf('"', start);
2826
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
2827
+ let iLt = c0 === 60 ? start : s.indexOf("<", start);
2828
+ let left = 0,
2829
+ out = "";
2830
+ for (;;) {
2831
+ let i = -1,
2832
+ ent;
2833
+ if (iQuot >= 0) {
2834
+ i = iQuot;
2835
+ ent = "&quot;";
2836
+ }
2837
+ if (iAmp >= 0 && (i < 0 || iAmp < i)) {
2838
+ i = iAmp;
2839
+ ent = "&amp;";
2840
+ }
2841
+ if (iLt >= 0 && (i < 0 || iLt < i)) {
2842
+ i = iLt;
2843
+ ent = "&lt;";
2844
+ }
2845
+ if (i < 0) break;
2846
+ if (left < i) out += s.substring(left, i);
2847
+ out += ent;
2848
+ left = i + 1;
2849
+ if (i === iQuot) iQuot = s.indexOf('"', left);else if (i === iAmp) iAmp = s.indexOf("&", left);else iLt = s.indexOf("<", left);
2850
+ }
2851
+ return left < s.length ? out + s.substring(left) : out;
2852
+ }
2853
+ function tryJoinPlainSSRArray(nodes) {
2854
+ if (nodes.length === 0) return undefined;
2855
+ let out = "";
2856
+ for (let i = 0, len = nodes.length; i < len; i++) {
2857
+ const node = nodes[i];
2858
+ if (node == null || typeof node !== "object" || node.h || typeof node.t !== "string") {
2859
+ return undefined;
2860
+ }
2861
+ out += node.t;
2862
+ }
2863
+ return out;
2864
+ }
2865
+ function queue(fn) {
2866
+ return Promise.resolve().then(fn);
2867
+ }
2868
+ const deferFlush = typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
2869
+ function allSettled(promises) {
2870
+ let size = promises.size;
2871
+ return Promise.allSettled(promises).then(() => {
2872
+ if (promises.size !== size) return allSettled(promises);
2873
+ return size;
2874
+ });
2875
+ }
2876
+ function assembleDocument(html, emittedAssets, preloadLinks, inlineStyles, scripts, nonce, headTags, onHead) {
2877
+ const scriptTag = scripts ? `<script${nonceAttr(nonce, "script")}>${scripts}</script>` : "";
2878
+ const title = headTags ? headTags.title : null;
2879
+ let headTagsHtml = headTags ? headTags.html : "";
2880
+ const headPrelude = headTags ? headTags.prelude : "";
2881
+ if (!onHead && title == null && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !preloadLinks && !(inlineStyles && inlineStyles.size)) {
2882
+ if (!scriptTag) return html;
2883
+ const xs = html.indexOf("<!--xs-->");
2884
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
2885
+ }
2886
+ if (headPrelude) {
2887
+ const open = html.match(/<head(?:\s[^>]*)?>/);
2888
+ if (open) {
2889
+ const at = open.index + open[0].length;
2890
+ html = html.slice(0, at) + headPrelude + html.slice(at);
2891
+ }
2892
+ }
2893
+ let headIdx = html.indexOf("</head>");
2894
+ if (headIdx === -1) {
2895
+ if (onHead) {
2896
+ let titleHtml = "";
2897
+ if (title != null) {
2898
+ titleHtml = headTags.noScripts ? `<title data-dh="title">${escape(title)}</title>` : `<script${nonceAttr(nonce, "script")}>(function(x,t){(t=document.querySelector("title"))?(t.hasAttribute("data-dh")||t.setAttribute("data-dhf",t.textContent),t.textContent=x):(document.title=x,t=document.querySelector("title"));t&&t.setAttribute("data-dh","title")})(${JSON.stringify(title).replace(/</g, "\\u003C")})</script>`;
2899
+ }
2900
+ onHead(headPrelude + headTagsHtml + titleHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce));
2901
+ }
2902
+ if (!scriptTag) return html;
2903
+ const xs = html.indexOf("<!--xs-->");
2904
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
2905
+ }
2906
+ if (title != null) {
2907
+ const winner = escape(title);
2908
+ const open = html.match(/<head(?:\s[^>]*)?>/);
2909
+ const from = open ? open.index + open[0].length : 0;
2910
+ const m = /<title(\s[^>]*)?>([\s\S]*?)<\/title>/.exec(html.slice(from, headIdx));
2911
+ if (m) {
2912
+ const at = from + m.index;
2913
+ const stash = m[2].replace(/"/g, "&quot;");
2914
+ html = html.slice(0, at) + `<title${m[1] || ""} data-dh="title" data-dhf="${stash}">${winner}</title>` + html.slice(at + m[0].length);
2915
+ headIdx = html.indexOf("</head>");
2916
+ } else {
2917
+ headTagsHtml = `<title data-dh="title">${winner}</title>` + headTagsHtml;
2918
+ }
2919
+ }
2920
+ const head = headTagsHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce);
2921
+ if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
2922
+ const xsIdx = html.indexOf("<!--xs-->");
2923
+ if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
2924
+ return xsIdx < headIdx ? html.slice(0, xsIdx) + scriptTag + html.slice(xsIdx, headIdx) + head + html.slice(headIdx) : html.slice(0, headIdx) + head + html.slice(headIdx, xsIdx) + scriptTag + html.slice(xsIdx);
2925
+ }
2926
+ function renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce) {
2927
+ let head = "";
2928
+ const styleAttr = nonceAttr(nonce, "style");
2929
+ const scriptAttr = nonceAttr(nonce, "script");
2930
+ if (emittedAssets && emittedAssets.size) {
2931
+ for (const url of emittedAssets) {
2932
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}"${styleAttr}>` : `<link rel="modulepreload" href="${url}"${scriptAttr}>`;
2933
+ }
2934
+ }
2935
+ if (preloadLinks) {
2936
+ for (const entry of preloadLinks) head += `<link${entry.attrHtml}>`;
2937
+ }
2938
+ if (inlineStyles && inlineStyles.size) {
2939
+ for (const entry of inlineStyles.values()) {
2940
+ if (entry.emitted) continue;
2941
+ entry.emitted = true;
2942
+ head += renderInlineStyle(entry, nonce);
2943
+ }
2944
+ }
2945
+ return head;
2946
+ }
2947
+ function serializeFragmentAssets(key, boundaryModules, context, name = key) {
2948
+ const map = boundaryModules.get(key);
2949
+ if (!map || !Object.keys(map).length) return;
2950
+ context.serialize(name + "_assets", {
2951
+ ...map
2952
+ });
2953
+ }
2954
+ function propagateBoundaryStyles(childKey, parentKey, tracking) {
2955
+ const childStyles = tracking.getBoundaryStyles(childKey);
2956
+ if (!childStyles) return;
2957
+ let parentStyles = tracking.boundaryStyles.get(parentKey);
2958
+ if (!parentStyles) {
2959
+ parentStyles = new Set();
2960
+ tracking.boundaryStyles.set(parentKey, parentStyles);
2961
+ }
2962
+ for (const url of childStyles) {
2963
+ parentStyles.add(url);
2964
+ }
2965
+ }
2966
+ function collectStreamStyles(key, tracking, headStyles) {
2967
+ const styles = tracking.getBoundaryStyles(key);
2968
+ const links = [];
2969
+ const inline = [];
2970
+ if (!styles) return {
2971
+ links,
2972
+ inline
2973
+ };
2974
+ for (const entry of styles) {
2975
+ if (typeof entry === "string") {
2976
+ if (!headStyles || !headStyles.has(entry)) links.push(entry);
2977
+ } else if (entry.emitted) {
2978
+ continue;
2979
+ } else if (entry.attrHtml !== undefined) {
2980
+ entry.emitted = true;
2981
+ links.push(entry);
2982
+ } else {
2983
+ entry.emitted = true;
2984
+ inline.push(entry);
2985
+ }
2986
+ }
2987
+ return {
2988
+ links,
2989
+ inline
2990
+ };
2991
+ }
2992
+ function escapeStyleContent(content) {
2993
+ return content.replace(/<\/(style)/gi, "<\\/$1");
2994
+ }
2995
+ function renderInlineStyle(entry, nonce) {
2996
+ let attrs = "";
2997
+ let hasNonce = false;
2998
+ if (entry.attrs) {
2999
+ for (const name in entry.attrs) {
3000
+ if (name.length === 5 && asciiLowerCase(name) === "nonce") hasNonce = true;
3001
+ attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
3002
+ }
3003
+ }
3004
+ const nonceHtml = hasNonce ? "" : nonceAttr(nonce, "style");
3005
+ return `<style${nonceHtml} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
3006
+ }
3007
+ function waitForFragments(registry, key) {
3008
+ for (const k of [...registry.keys()].reverse()) {
3009
+ if (key.startsWith(k)) return k;
3010
+ }
3011
+ return false;
3012
+ }
3013
+ function replacePlaceholder(html, key, value) {
3014
+ const marker = `<template id="pl-${key}">`;
3015
+ const close = `<!--pl-${key}-->`;
3016
+ const first = html.indexOf(marker);
3017
+ if (first === -1) return html;
3018
+ const last = html.indexOf(close, first + marker.length);
3019
+ return html.slice(0, first) + value + html.slice(last + close.length);
3020
+ }
3021
+ let ssrTextTail = false;
3022
+ function tryResolveString(node, nested) {
3023
+ if (!nested) ssrTextTail = false;
3024
+ const t = typeof node;
3025
+ if (t === "string" || t === "number") {
3026
+ const s = ssrTextTail ? "<!--!$-->" + node : "" + node;
3027
+ ssrTextTail = true;
3028
+ return s;
3029
+ }
3030
+ if (node == null || t === "boolean") return "";
3031
+ if (t === "object") {
3032
+ if (Array.isArray(node)) {
3033
+ const joined = tryJoinPlainSSRArray(node);
3034
+ if (joined !== undefined) {
3035
+ ssrTextTail = false;
3036
+ return joined;
3037
+ }
3038
+ let s = "";
3039
+ for (let i = 0, len = node.length; i < len; i++) {
3040
+ const r = tryResolveString(node[i], true);
3041
+ if (typeof r !== "string") return {
3042
+ bail: node
3043
+ };
3044
+ s += r;
3045
+ }
3046
+ return s;
3047
+ }
3048
+ if (node.h && node.h.length > 0) return {
3049
+ merge: node
3050
+ };
3051
+ if (node.t === undefined) {
3052
+ return "";
3053
+ }
3054
+ ssrTextTail = false;
3055
+ return Array.isArray(node.t) ? node.t[0] : node.t;
3056
+ }
3057
+ if (t === "function") {
3058
+ let v;
3059
+ try {
3060
+ v = node();
3061
+ } catch (err) {
3062
+ const wrap = buildAsyncWrap(err, node);
3063
+ if (wrap) ssrTextTail = true;
3064
+ return wrap || "";
3065
+ }
3066
+ return tryResolveString(v, true);
3067
+ }
3068
+ return "";
3069
+ }
3070
+ function resolveSSRNode(node, result = {
3071
+ t: [""],
3072
+ h: [],
3073
+ p: []
3074
+ }, top, nested) {
3075
+ if (!nested) ssrTextTail = false;
3076
+ const t = typeof node;
3077
+ if (t === "string" || t === "number") {
3078
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + node : node;
3079
+ ssrTextTail = true;
3080
+ } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
3081
+ const slotLive = node.$slot && sharedConfig.context && sharedConfig.context.liveHoles;
3082
+ if (slotLive) slotLive.suppressed++;
3083
+ try {
3084
+ for (let i = 0, len = node.length; i < len; i++) {
3085
+ if (top) ssrTextTail = false;
3086
+ resolveSSRNode(node[i], result, false, true);
3087
+ }
3088
+ } finally {
3089
+ if (slotLive) slotLive.suppressed--;
3090
+ }
3091
+ } else if (t === "object") {
3092
+ if (node.h) {
3093
+ result.t[result.t.length - 1] += node.t[0];
3094
+ if (node.t.length > 1) {
3095
+ result.t.push(...node.t.slice(1));
3096
+ result.h.push(...node.h);
3097
+ result.p.push(...node.p);
3098
+ }
3099
+ ssrTextTail = false;
3100
+ } else if (node.t !== undefined) {
3101
+ result.t[result.t.length - 1] += node.t;
3102
+ ssrTextTail = false;
3103
+ } else ;
3104
+ } else if (t === "function") {
3105
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
3106
+ let liveNode = null;
3107
+ if (live && (liveNode = live.content(node)) !== null) {
3108
+ if (typeof liveNode === "string") {
3109
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + liveNode : liveNode;
3110
+ ssrTextTail = true;
3111
+ } else resolveSSRNode(liveNode, result, false, true);
3112
+ } else {
3113
+ try {
3114
+ resolveSSRNode(node(), result, false, true);
3115
+ } catch (err) {
3116
+ const wrap = buildAsyncWrap(err, node);
3117
+ if (wrap) {
3118
+ if (ssrTextTail) result.t[result.t.length - 1] += "<!--!$-->";
3119
+ result.h.push(wrap.fn);
3120
+ result.p.push(wrap.p);
3121
+ result.t.push("");
3122
+ ssrTextTail = true;
3123
+ }
3124
+ }
3125
+ }
3126
+ }
3127
+ return result;
3128
+ }
3129
+ function resolveSSRSync(node) {
3130
+ const res = resolveSSRNode(node);
3131
+ if (!res.h.length) return res.t[0];
3132
+ throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
3133
+ }
3134
+ const RequestContext = Symbol.for("solid.RequestContext");
3135
+ const ServerErrors = Symbol.for("solid-js/server/errors");
3136
+ function serializerErrorHook(hook) {
3137
+ return hook === undefined ? undefined : err => {
3138
+ reportServerError(err, {
3139
+ kind: "render",
3140
+ handling: "serialize"
3141
+ }, null);
3142
+ };
3143
+ }
3144
+ function ambientServerErrorHook() {
3145
+ const slot = globalThis[ServerErrors];
3146
+ return slot === undefined ? undefined : slot.hook;
3147
+ }
3148
+ function peekRequestEvent() {
3149
+ const store = globalThis[RequestContext];
3150
+ return store ? store.getStore() : undefined;
3151
+ }
3152
+ function traceForEvent(event) {
3153
+ return traceFor(event.request || event, event.request);
3154
+ }
3155
+ function traceForStub(stub, event) {
3156
+ if (!event) {
3157
+ event = peekRequestEvent();
3158
+ if (!event || event.response !== stub) return undefined;
3159
+ }
3160
+ return traceForEvent(event);
3161
+ }
3162
+ function reportLostHeaderWrite(method, name) {
3163
+ const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
3164
+ recordFinding({
3165
+ code: "LATE_HEADER_WRITE",
3166
+ kind: "head",
3167
+ severity: "error",
3168
+ message,
3169
+ data: {
3170
+ method,
3171
+ name: String(name)
3172
+ }
3173
+ });
3174
+ console.error(message);
3175
+ }
3176
+ function commitResponseStub(stub, {
3177
+ allowLateLocation = false,
3178
+ event
3179
+ } = {}) {
3180
+ if (!stub || stub.committed) return stub;
3181
+ const headers = stub.headers;
3182
+ if (headers && typeof headers.append === "function") {
3183
+ const trace = traceForStub(stub, event);
3184
+ if (trace) appendTraceServerTiming(headers, trace);
3185
+ }
3186
+ stub.committed = true;
3187
+ if (!headers || typeof headers.set !== "function") return stub;
3188
+ for (const method of ["set", "append", "delete"]) {
3189
+ const original = headers[method].bind(headers);
3190
+ headers[method] = function (name, ...rest) {
3191
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
3192
+ return original(name, ...rest);
3193
+ }
3194
+ reportLostHeaderWrite(method, name);
3195
+ };
3196
+ }
3197
+ return stub;
3198
+ }
3199
+ /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
3200
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
3201
+
3202
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
3203
+ function records() {
3204
+ return globalThis[RECORDS];
3205
+ }
3206
+ function frameCensus(event, type, own) {
3207
+ event.chunks++;
3208
+ switch (type) {
3209
+ case "html":
3210
+ if (!own) event.regions++;else if (event.shellMs === undefined) event.shellMs = performance.now() - event.at;
3211
+ break;
3212
+ case "fragment":
3213
+ event.fragments++;
3214
+ break;
3215
+ case "slot":
3216
+ event.slots++;
3217
+ break;
3218
+ case "error":
3219
+ event.errors++;
3220
+ break;
3221
+ }
3222
+ }
3223
+
3224
+ function observeFrame(frame) {
3225
+ const channel = records();
3226
+ if (channel === undefined || !channel.observed("frame")) return undefined;
3227
+ const event = {
3228
+ side: "server",
3229
+ id: frame.id,
3230
+ version: frame.version,
3231
+ at: performance.now(),
3232
+ durationMs: 0,
3233
+ outcome: "complete",
3234
+ chunks: 0,
3235
+ fragments: 0,
3236
+ slots: 0,
3237
+ regions: 0,
3238
+ errors: 0
3239
+ };
3240
+ let settled = false;
3241
+ return {
3242
+ chunk(chunk) {
3243
+ if (chunk.type === "complete") return;
3244
+ frameCensus(event, chunk.type, chunk.id === frame.id);
3245
+ },
3246
+ settle(outcome, error) {
3247
+ if (settled) return;
3248
+ settled = true;
3249
+ event.durationMs = performance.now() - event.at;
3250
+ event.outcome = outcome;
3251
+ const live = {};
3252
+ if (outcome === "error") live.error = error;
3253
+ channel.emit("frame", event, live);
3254
+ }
3255
+ };
3256
+ }
3257
+
3258
+ function scopeDeferredResult(value, scope) {
3259
+ const bound = bindDeferredBody(value, scope);
3260
+ if (bound !== value || value === null || typeof value !== "object") return bound;
3261
+ return scopeDeferredContents(value, scope);
3262
+ }
3263
+ class ScopeFrame {
3264
+ constructor(value, next, keys, descriptors) {
3265
+ this.value = value;
3266
+ this.next = next;
3267
+ this.keys = keys;
3268
+ this.descriptors = descriptors;
3269
+ this.i = 0;
3270
+ this.changed = false;
3271
+ }
3272
+ }
3273
+ function enterScopeCarrier(value, state) {
3274
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
3275
+ if (state.seen.has(value)) {
3276
+ state.cyclic.add(value);
3277
+ return state.seen.get(value);
3278
+ }
3279
+ const bound = bindDeferredBody(value, state.scope);
3280
+ if (bound !== value) {
3281
+ state.seen.set(value, bound);
3282
+ return bound;
3283
+ }
3284
+ if (typeof value !== "object") return value;
3285
+ if (Array.isArray(value)) {
3286
+ if (Object.isFrozen(value)) {
3287
+ state.seen.set(value, value);
3288
+ return value;
3289
+ }
3290
+ const next = value.slice();
3291
+ state.seen.set(value, next);
3292
+ return new ScopeFrame(value, next, null, null);
3293
+ }
3294
+ const prototype = Object.getPrototypeOf(value);
3295
+ if (prototype !== Object.prototype && prototype !== null || Object.isFrozen(value)) {
3296
+ state.seen.set(value, value);
3297
+ return value;
3298
+ }
3299
+ const descriptors = Object.getOwnPropertyDescriptors(value);
3300
+ const next = Object.create(prototype, descriptors);
3301
+ state.seen.set(value, next);
3302
+ return new ScopeFrame(value, next, Object.keys(value), descriptors);
3303
+ }
3304
+ function scopeDeferredContents(root, scope) {
3305
+ const state = {
3306
+ seen: new Map(),
3307
+ cyclic: new Set(),
3308
+ scope
3309
+ };
3310
+ const entered = enterScopeCarrier(root, state);
3311
+ if (!(entered instanceof ScopeFrame)) return entered;
3312
+ const stack = [entered];
3313
+ let delivered = NOTHING;
3314
+ for (;;) {
3315
+ const top = stack[stack.length - 1];
3316
+ const length = top.keys ? top.keys.length : top.value.length;
3317
+ let pushed = null;
3318
+ while (top.i < length) {
3319
+ const i = top.i;
3320
+ let original;
3321
+ let writable = true;
3322
+ if (top.keys) {
3323
+ const descriptor = top.descriptors[top.keys[i]];
3324
+ writable = "value" in descriptor && descriptor.writable === true;
3325
+ original = writable ? descriptor.value : undefined;
3326
+ } else {
3327
+ original = top.value[i];
3328
+ }
3329
+ if (!writable) {
3330
+ top.i++;
3331
+ continue;
3332
+ }
3333
+ let bound;
3334
+ if (delivered !== NOTHING) {
3335
+ bound = delivered;
3336
+ delivered = NOTHING;
3337
+ } else {
3338
+ bound = enterScopeCarrier(original, state);
3339
+ if (bound instanceof ScopeFrame) {
3340
+ pushed = bound;
3341
+ break;
3342
+ }
3343
+ }
3344
+ if (bound !== original) {
3345
+ if (top.keys) top.next[top.keys[i]] = bound;else top.next[i] = bound;
3346
+ top.changed = true;
3347
+ }
3348
+ top.i++;
3349
+ }
3350
+ if (pushed !== null) {
3351
+ stack.push(pushed);
3352
+ continue;
3353
+ }
3354
+ stack.pop();
3355
+ let out;
3356
+ if (top.changed || state.cyclic.has(top.value)) {
3357
+ out = top.next;
3358
+ } else {
3359
+ state.seen.set(top.value, top.value);
3360
+ out = top.value;
3361
+ }
3362
+ if (stack.length === 0) return out;
3363
+ delivered = out;
3364
+ }
3365
+ }
3366
+ function bindDeferredBody(value, scope) {
3367
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
3368
+ const promised = scope(() => nativePromise(value));
3369
+ if (promised) {
3370
+ return promised.then(result => scope(() => scopeDeferredResult(result, scope)));
3371
+ }
3372
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
3373
+ let reader;
3374
+ return new ReadableStream({
3375
+ async pull(controller) {
3376
+ try {
3377
+ const step = await scope(() => {
3378
+ if (!reader) reader = value.getReader();
3379
+ return reader.read();
3380
+ });
3381
+ if (step.done) controller.close();else controller.enqueue(step.value);
3382
+ } catch (error) {
3383
+ controller.error(error);
3384
+ }
3385
+ },
3386
+ cancel(reason) {
3387
+ return scope(() => reader ? reader.cancel(reason) : value.cancel(reason));
3388
+ }
3389
+ }, {
3390
+ highWaterMark: 0
3391
+ });
3392
+ }
3393
+ const scopedIterator = symbol => ({
3394
+ [symbol]() {
3395
+ const iterator = scope(() => value[symbol]());
3396
+ return new Proxy(iterator, {
3397
+ get(target, property) {
3398
+ const member = Reflect.get(target, property, target);
3399
+ return typeof member === "function" && (property === "next" || property === "return" || property === "throw") ? (...args) => scope(() => member.apply(target, args)) : member;
3400
+ }
3401
+ });
3402
+ }
3403
+ });
3404
+ if (typeof value[Symbol.asyncIterator] === "function") {
3405
+ return scopedIterator(Symbol.asyncIterator);
3406
+ }
3407
+ if (typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
3408
+ return scopedIterator(Symbol.iterator);
3409
+ }
3410
+ return value;
3411
+ }
3412
+ function processState(key, create) {
3413
+ const slot = Symbol.for(key);
3414
+ return globalThis[slot] || (globalThis[slot] = create());
3415
+ }
3416
+ processState("solid.ServerFunctionRegistrations", () => new Map());
3417
+ processState("solid.ServerFunctionMethods", () => new Map());
3418
+ processState("solid.ServerFunctionReferenceBindings", () => new WeakMap());
3419
+ const INVOCATIONS = new WeakMap();
3420
+ function getEventServerFunctionInvocation(event) {
3421
+ return event && INVOCATIONS.get(event);
3422
+ }
3423
+ new Set(Object.values(BodyFormat));
3424
+ function guardFailures(value, state) {
3425
+ if (!state) state = {
3426
+ seen: new WeakMap(),
3427
+ cyclic: new WeakSet()
3428
+ };
3429
+ const entered = enterGuard(value, state);
3430
+ if (!(entered instanceof Frame)) return entered;
3431
+ const stack = [entered];
3432
+ let delivered = NOTHING;
3433
+ for (;;) {
3434
+ const top = stack[stack.length - 1];
3435
+ const items = top.items;
3436
+ let pushed = null;
3437
+ while (top.i < items.length) {
3438
+ const i = top.i;
3439
+ let original;
3440
+ if (top.kind === OBJECT) {
3441
+ const descriptor = top.descriptors[items[i]];
3442
+ if ("value" in descriptor) {
3443
+ original = descriptor.value;
3444
+ } else if (typeof descriptor.get === "function") {
3445
+ if (top.accessorRead !== i) {
3446
+ try {
3447
+ top.accessorValue = descriptor.get.call(top.value);
3448
+ } catch (error) {
3449
+ throw wireServerFunctionError(error, "channel");
3450
+ }
3451
+ top.accessorRead = i;
3452
+ }
3453
+ original = top.accessorValue;
3454
+ } else {
3455
+ top.i++;
3456
+ continue;
3457
+ }
3458
+ } else {
3459
+ original = items[i];
3460
+ }
3461
+ let guarded;
3462
+ if (delivered !== NOTHING) {
3463
+ guarded = delivered;
3464
+ delivered = NOTHING;
3465
+ } else {
3466
+ guarded = enterGuard(original, state);
3467
+ if (guarded instanceof Frame) {
3468
+ pushed = guarded;
3469
+ break;
3470
+ }
3471
+ }
3472
+ if (top.kind === ARRAY) {
3473
+ if (guarded !== original) {
3474
+ top.next[i] = guarded;
3475
+ top.changed = true;
3476
+ }
3477
+ } else if (top.kind === MAP) {
3478
+ if ((i & 1) === 0) top.pendingKey = guarded;else top.next.set(top.pendingKey, guarded);
3479
+ if (guarded !== original) top.changed = true;
3480
+ } else if (top.kind === SET) {
3481
+ top.next.add(guarded);
3482
+ if (guarded !== original) top.changed = true;
3483
+ } else if (guarded !== original || top.accessorRead === i) {
3484
+ Object.defineProperty(top.next, items[i], {
3485
+ value: guarded,
3486
+ writable: true,
3487
+ configurable: true,
3488
+ enumerable: top.descriptors[items[i]].enumerable
3489
+ });
3490
+ top.changed = true;
3491
+ }
3492
+ top.i++;
3493
+ }
3494
+ if (pushed !== null) {
3495
+ stack.push(pushed);
3496
+ continue;
3497
+ }
3498
+ stack.pop();
3499
+ const out = keepGuarded(top.value, top.next, top.changed, state);
3500
+ if (stack.length === 0) return out;
3501
+ delivered = out;
3502
+ }
3503
+ }
3504
+ const NOTHING = Symbol();
3505
+ const ARRAY = 0;
3506
+ const MAP = 1;
3507
+ const SET = 2;
3508
+ const OBJECT = 3;
3509
+ class Frame {
3510
+ constructor(kind, value, next, items, descriptors) {
3511
+ this.kind = kind;
3512
+ this.value = value;
3513
+ this.next = next;
3514
+ this.items = items;
3515
+ this.descriptors = descriptors;
3516
+ this.i = 0;
3517
+ this.changed = false;
3518
+ this.accessorRead = -1;
3519
+ this.accessorValue = undefined;
3520
+ this.pendingKey = undefined;
3521
+ }
3522
+ }
3523
+ function guardOperation(state, run) {
3524
+ return state.scope ? state.scope(run) : run();
3525
+ }
3526
+ function enterGuard(value, state) {
3527
+ if (value === null || typeof value !== "object") return value;
3528
+ if (state.seen.has(value)) {
3529
+ state.cyclic.add(value);
3530
+ return state.seen.get(value);
3531
+ }
3532
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) {
3533
+ let reader;
3534
+ const gate = state.gate;
3535
+ let finished = false;
3536
+ const close = () => {
3537
+ if (finished) return;
3538
+ finished = true;
3539
+ try {
3540
+ const cancelled = guardOperation(state, () => reader ? reader.cancel() : value.cancel());
3541
+ if (cancelled && typeof cancelled.then === "function") cancelled.then(undefined, () => {});
3542
+ } catch {}
3543
+ };
3544
+ const guardedStream = new ReadableStream({
3545
+ async pull(controller) {
3546
+ try {
3547
+ if (gate && !finished && !gate.wantsMore()) await gate.awaitDemand();
3548
+ if (finished) {
3549
+ controller.close();
3550
+ return;
3551
+ }
3552
+ if (!reader) reader = guardOperation(state, () => value.getReader());
3553
+ const {
3554
+ done,
3555
+ value: chunk
3556
+ } = await guardOperation(state, () => reader.read());
3557
+ done ? controller.close() : controller.enqueue(guardOperation(state, () => guardFailures(chunk, state)));
3558
+ } catch (error) {
3559
+ controller.error(guardOperation(state, () => wireServerFunctionError(error, "channel")));
3560
+ }
3561
+ },
3562
+ cancel(reason) {
3563
+ finished = true;
3564
+ return guardOperation(state, () => reader ? reader.cancel(reason) : value.cancel(reason));
3565
+ }
3566
+ });
3567
+ if (gate) gate.onOpen(close);
3568
+ state.seen.set(value, guardedStream);
3569
+ return guardedStream;
3570
+ }
3571
+ if (typeof value.then === "function") {
3572
+ const guardedPromise = Promise.resolve(value).then(resolved => guardOperation(state, () => guardFailures(resolved, state)), error => {
3573
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
3574
+ });
3575
+ guardedPromise.catch(() => {});
3576
+ state.seen.set(value, guardedPromise);
3577
+ return guardedPromise;
3578
+ }
3579
+ if (typeof value[Symbol.asyncIterator] === "function") {
3580
+ const source = value;
3581
+ const gate = state.gate;
3582
+ const guardedIterable = {
3583
+ [Symbol.asyncIterator]() {
3584
+ const iterator = guardOperation(state, () => source[Symbol.asyncIterator]());
3585
+ let finished = false;
3586
+ const close = () => {
3587
+ if (finished) return;
3588
+ finished = true;
3589
+ try {
3590
+ const returned = iterator.return && guardOperation(state, () => iterator.return());
3591
+ if (returned && typeof returned.then === "function") returned.then(undefined, () => {});
3592
+ } catch {}
3593
+ };
3594
+ if (gate) gate.onOpen(close);
3595
+ const step = () => finished ? Promise.resolve({
3596
+ done: true,
3597
+ value: undefined
3598
+ }) : guardOperation(state, () => iterator.next()).then(step => {
3599
+ if (step.done) {
3600
+ finished = true;
3601
+ return step;
3602
+ }
3603
+ return {
3604
+ done: false,
3605
+ value: guardOperation(state, () => guardFailures(step.value, state))
3606
+ };
3607
+ }, error => {
3608
+ throw guardOperation(state, () => wireServerFunctionError(error, "channel"));
3609
+ });
3610
+ return {
3611
+ next: () => finished || !gate || gate.wantsMore() ? step() : gate.awaitDemand().then(step),
3612
+ return: () => {
3613
+ close();
3614
+ return Promise.resolve({
3615
+ done: true,
3616
+ value: undefined
3617
+ });
3618
+ }
3619
+ };
3620
+ }
3621
+ };
3622
+ state.seen.set(value, guardedIterable);
3623
+ return guardedIterable;
3624
+ }
3625
+ if (state.scope && typeof value[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value)) {
3626
+ const scopedIterable = scopeDeferredResult(value, state.scope);
3627
+ state.seen.set(value, scopedIterable);
3628
+ return scopedIterable;
3629
+ }
3630
+ if (Array.isArray(value)) {
3631
+ const next = value.slice();
3632
+ state.seen.set(value, next);
3633
+ return new Frame(ARRAY, value, next, value, null);
3634
+ }
3635
+ if (value instanceof Map) {
3636
+ const next = new Map();
3637
+ state.seen.set(value, next);
3638
+ const items = [];
3639
+ for (const entry of value) items.push(entry[0], entry[1]);
3640
+ return new Frame(MAP, value, next, items, null);
3641
+ }
3642
+ if (value instanceof Set) {
3643
+ const next = new Set();
3644
+ state.seen.set(value, next);
3645
+ return new Frame(SET, value, next, [...value], null);
3646
+ }
3647
+ const prototype = Object.getPrototypeOf(value);
3648
+ if (prototype !== Object.prototype && prototype !== null && !(value instanceof Error)) {
3649
+ state.seen.set(value, value);
3650
+ return value;
3651
+ }
3652
+ const descriptors = Object.getOwnPropertyDescriptors(value);
3653
+ for (const key of Object.keys(descriptors)) {
3654
+ descriptors[key].configurable = true;
3655
+ if ("value" in descriptors[key]) descriptors[key].writable = true;
3656
+ }
3657
+ const next = Object.create(prototype, descriptors);
3658
+ state.seen.set(value, next);
3659
+ const children = !(value instanceof Error) ? Object.keys(value) : Object.getOwnPropertyNames(value).filter(key => {
3660
+ const descriptor = descriptors[key];
3661
+ return descriptor.enumerable || "value" in descriptor;
3662
+ });
3663
+ return new Frame(OBJECT, value, next, children, descriptors);
3664
+ }
3665
+ function keepGuarded(value, next, changed, state) {
3666
+ if (changed || state.cyclic.has(value)) return next;
3667
+ state.seen.set(value, value);
3668
+ return value;
3669
+ }
3670
+ const GENERIC_SERVER_ERROR_MESSAGE = "Internal Server Error";
3671
+ const REQUEST_ERROR_HOOKS = new WeakMap();
3672
+ function siteFor(handling, event, direct) {
3673
+ const invocation = event ? INVOCATIONS.get(event) : undefined;
3674
+ const site = {
3675
+ kind: "server-function",
3676
+ handling,
3677
+ direct
3678
+ };
3679
+ if (invocation) site.functionId = invocation.id;
3680
+ if (event) site.event = event;
3681
+ return site;
3682
+ }
3683
+ function wireServerFunctionError(value, handling, event = currentEvent()) {
3684
+ const report = reportServerError(value, siteFor(handling, event, false), null, event ? REQUEST_ERROR_HOOKS.get(event) : undefined);
3685
+ return report.mapped ? report.value : sanitizeServerError(value);
3686
+ }
3687
+ function currentEvent() {
3688
+ const store = globalThis[RequestContext];
3689
+ return store ? store.getStore() : undefined;
3690
+ }
3691
+ function sanitizeServerError(value) {
3692
+ if (isSafeError(value)) return value;
3693
+ emitFinding({
3694
+ code: "SERVER_FN_ERROR_SANITIZED",
3695
+ kind: "ssr",
3696
+ severity: "error",
3697
+ message: `[SERVER_FN_ERROR_SANITIZED] Server function error replaced with a generic Error before serialization: ${errorText(value)}`,
3698
+ data: {
3699
+ error: value
3700
+ }
3701
+ }, null);
3702
+ return new Error(GENERIC_SERVER_ERROR_MESSAGE);
3703
+ }
3704
+ function nativePromise(value) {
3705
+ if (value instanceof Promise) return value;
3706
+ try {
3707
+ if (Object.prototype.toString.call(value) === "[object Promise]") return Promise.prototype.then.call(value, value => value);
3708
+ } catch {}
3709
+ }
3710
+
3711
+ const FRAME_STREAM_HEADER = "X-Frame-Stream";
3712
+ function isFrameStreamResponse(response) {
3713
+ return response.headers.has(FRAME_STREAM_HEADER);
3714
+ }
3715
+ const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("solid.server-component");
3716
+ const SERVER_COMPONENT_SOURCE = /*#__PURE__*/Symbol.for("solid.server-component-source");
3717
+ const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("solid.server-component-address");
3718
+ let serverComponentRegistryExpr;
3719
+ function setServerComponentBootstrap(resolve) {
3720
+ serverComponentRegistryExpr = resolve;
3721
+ }
3722
+ function parseServerComponent(value, ctx) {
3723
+ return {
3724
+ id: ctx.parse(value[SERVER_COMPONENT]),
3725
+ address: ctx.parse(value[SERVER_COMPONENT_ADDRESS])
3726
+ };
3727
+ }
3728
+ const ServerComponentPlugin = {
3729
+ tag: "solid/server-component",
3730
+ test(value) {
3731
+ return typeof value === "function" && SERVER_COMPONENT in value;
3732
+ },
3733
+ parse: {
3734
+ sync: parseServerComponent,
3735
+ async async(value, ctx) {
3736
+ return {
3737
+ id: await ctx.parse(value[SERVER_COMPONENT]),
3738
+ address: await ctx.parse(value[SERVER_COMPONENT_ADDRESS])
3739
+ };
3740
+ },
3741
+ stream: parseServerComponent
3742
+ },
3743
+ serialize(node, ctx) {
3744
+ const registry = serverComponentRegistryExpr ? serverComponentRegistryExpr(ctx) : "self._$SC";
3745
+ return registry + ".r(" + ctx.serialize(node.id) + "," + ctx.serialize(node.address) + ")";
3746
+ },
3747
+ deserialize(node, ctx) {
3748
+ const id = ctx.deserialize(node.id);
3749
+ ctx.deserialize(node.address);
3750
+ return globalThis._$SC.r(id);
3751
+ }
3752
+ };
3753
+ function flightCodec(codec) {
3754
+ const plugins = codec && codec.plugins || [];
3755
+ if (plugins.some(plugin => plugin && plugin.tag === ServerComponentPlugin.tag)) return codec;
3756
+ return {
3757
+ ...codec,
3758
+ plugins: [...plugins, ServerComponentPlugin]
3759
+ };
3760
+ }
3761
+
3762
+ const runWithHydrationScope = (id, fn) => runWithOwner(createOwner({
3763
+ id
3764
+ }), fn);
3765
+ const ssrAsyncValue = value => createMemo(() => value, {
3766
+ serialize: false
3767
+ });
3768
+ const scopeStamp = typeof creationStamp === "function" ? creationStamp : () => 0;
3769
+ function serverOwned(render) {
3770
+ return NoHydration ? NoHydration({
3771
+ get children() {
3772
+ return render();
3773
+ }
3774
+ }) : render();
3775
+ }
3776
+ function serverComponentScope(render) {
3777
+ return runInServerComponentScope ? runInServerComponentScope(render) : render();
3778
+ }
3779
+ function wirePreload(entry) {
3780
+ return entry.href ? {
3781
+ href: entry.href,
3782
+ attrs: entry.attrs
3783
+ } : {
3784
+ attrs: entry.attrs
3785
+ };
3786
+ }
3787
+ const SERVER_COMPONENT_BOOTSTRAP_EXPR = "(self._$SC||(self._$SC={c:{},a:{},r(i,a){a&&(this.a[a]=i,this.reg&&this.reg(a,i));return this.c[i]||(this.c[i]=(p,b)=>self._$SC.impl(i,p,b))}}))";
3788
+ const bootstrappedScripts = new WeakSet();
3789
+ setServerComponentBootstrap(ctx => {
3790
+ if (bootstrappedScripts.has(ctx)) return "self._$SC";
3791
+ bootstrappedScripts.add(ctx);
3792
+ return SERVER_COMPONENT_BOOTSTRAP_EXPR;
3793
+ });
3794
+ const SERVER_COMPONENT_BOOTSTRAP = SERVER_COMPONENT_BOOTSTRAP_EXPR + ";";
3795
+ function createFrameSink(emit, frame) {
3796
+ const {
3797
+ id,
3798
+ version
3799
+ } = frame;
3800
+ const styledKeys = new Set();
3801
+ const bindings = new Map();
3802
+ const sweepMinted = new Set();
3803
+ const argRefVersions = new Map();
3804
+ let sweepScheduled = false;
3805
+ let closed = false;
3806
+ let epoch = 0;
3807
+ const sweep = () => {
3808
+ epoch++;
3809
+ for (const b of [...bindings.values()]) {
3810
+ try {
3811
+ b.sweep();
3812
+ } catch (_) {
3813
+ }
3814
+ }
3815
+ };
3816
+ const scheduleSweep = () => {
3817
+ if (closed || sweepScheduled || !bindings.size) return;
3818
+ sweepScheduled = true;
3819
+ queueMicrotask(() => {
3820
+ sweepScheduled = false;
3821
+ if (!closed) sweep();
3822
+ });
3823
+ };
3824
+ const regionKeys = new Map();
3825
+ const frameOf = key => regionKeys.get(key) || id;
3826
+ return {
3827
+ tagRegion(key, childId) {
3828
+ if (!regionKeys.has(key)) regionKeys.set(key, childId);
3829
+ },
3830
+ shell(html, meta = {}) {
3831
+ if (meta.preloads && meta.preloads.size || meta.preloadLinks) {
3832
+ const chunk = {
3833
+ type: "assets",
3834
+ id,
3835
+ version,
3836
+ key: ""
3837
+ };
3838
+ if (meta.preloads && meta.preloads.size) {
3839
+ const styles = [];
3840
+ const modules = [];
3841
+ for (const url of meta.preloads) {
3842
+ (url.endsWith(".css") ? styles : modules).push(url);
3843
+ }
3844
+ if (styles.length) chunk.styles = styles;
3845
+ if (modules.length) chunk.modules = modules;
3846
+ }
3847
+ if (meta.preloadLinks) {
3848
+ chunk.preloads = [];
3849
+ for (const entry of meta.preloadLinks) {
3850
+ chunk.preloads.push(wirePreload(entry));
3851
+ }
3852
+ }
3853
+ emit(chunk);
3854
+ }
3855
+ emit({
3856
+ type: "html",
3857
+ id,
3858
+ version,
3859
+ html
3860
+ });
3861
+ },
3862
+ data(record) {
3863
+ if (record && typeof record.key === "string" && (record.key.endsWith("_fr") || /^\d+$/.test(record.key))) {
3864
+ return;
3865
+ }
3866
+ if (typeof record === "string") {
3867
+ emit({
3868
+ type: "data",
3869
+ id,
3870
+ version,
3871
+ payload: record
3872
+ });
3873
+ scheduleSweep();
3874
+ } else {
3875
+ emit({
3876
+ type: "data",
3877
+ id,
3878
+ version,
3879
+ key: record.key,
3880
+ node: record.node,
3881
+ initial: record.initial
3882
+ });
3883
+ if (!sweepMinted.has(record.key)) scheduleSweep();
3884
+ }
3885
+ },
3886
+ fragment(key, value, meta = {}) {
3887
+ const fid = frameOf(key);
3888
+ const links = meta.styles && meta.styles.links || [];
3889
+ const inline = meta.styles && meta.styles.inline || [];
3890
+ if (links.length || inline.length) {
3891
+ if (links.length) styledKeys.add(key);
3892
+ const chunk = {
3893
+ type: "assets",
3894
+ id: fid,
3895
+ version,
3896
+ key
3897
+ };
3898
+ if (links.length) {
3899
+ chunk.styles = links.map(e => typeof e === "string" ? e : e.attrs ? {
3900
+ href: e.href,
3901
+ attrs: e.attrs
3902
+ } : e.href);
3903
+ }
3904
+ if (inline.length) {
3905
+ chunk.inlineStyles = inline.map(e => ({
3906
+ id: e.id,
3907
+ content: e.content,
3908
+ attrs: e.attrs
3909
+ }));
3910
+ }
3911
+ emit(chunk);
3912
+ }
3913
+ emit({
3914
+ type: "fragment",
3915
+ id: fid,
3916
+ version,
3917
+ key,
3918
+ html: value
3919
+ });
3920
+ scheduleSweep();
3921
+ if (meta.error) {
3922
+ emit({
3923
+ type: "error",
3924
+ id: fid,
3925
+ version,
3926
+ key,
3927
+ error: {
3928
+ message: String(meta.error && meta.error.message || meta.error)
3929
+ }
3930
+ });
3931
+ }
3932
+ if (!meta.revealGroup) {
3933
+ emit({
3934
+ type: "reveal",
3935
+ id: fid,
3936
+ version,
3937
+ keys: [key],
3938
+ waitForStyles: !!links.length
3939
+ });
3940
+ }
3941
+ },
3942
+ reveal(keys, meta = {}) {
3943
+ const byFrame = new Map();
3944
+ for (const key of keys) {
3945
+ const fid = frameOf(key);
3946
+ let group = byFrame.get(fid);
3947
+ if (!group) byFrame.set(fid, group = []);
3948
+ group.push(key);
3949
+ }
3950
+ for (const [fid, groupKeys] of byFrame) {
3951
+ let waitForStyles = false;
3952
+ for (const key of groupKeys) if (styledKeys.has(key)) waitForStyles = true;
3953
+ const chunk = {
3954
+ type: "reveal",
3955
+ id: fid,
3956
+ version,
3957
+ keys: groupKeys,
3958
+ waitForStyles
3959
+ };
3960
+ if (meta.fallback) chunk.fallback = true;
3961
+ emit(chunk);
3962
+ }
3963
+ },
3964
+ asset(type, value) {
3965
+ if (type === "module") {
3966
+ emit({
3967
+ type: "assets",
3968
+ id,
3969
+ version,
3970
+ key: "",
3971
+ modules: [value]
3972
+ });
3973
+ } else if (type === "preload") {
3974
+ emit({
3975
+ type: "assets",
3976
+ id,
3977
+ version,
3978
+ key: "",
3979
+ preloads: [wirePreload(value)]
3980
+ });
3981
+ }
3982
+ },
3983
+ end() {
3984
+ if (bindings.size) sweep();
3985
+ closed = true;
3986
+ emit({
3987
+ type: "complete",
3988
+ id,
3989
+ version
3990
+ });
3991
+ },
3992
+ error(errorId, error) {
3993
+ emit({
3994
+ type: "error",
3995
+ id,
3996
+ version,
3997
+ key: errorId,
3998
+ error
3999
+ });
4000
+ },
4001
+ slot(key, args) {
4002
+ emit({
4003
+ type: "slot",
4004
+ id,
4005
+ version,
4006
+ key,
4007
+ args
4008
+ });
4009
+ },
4010
+ region(childId, html) {
4011
+ emit({
4012
+ type: "html",
4013
+ id: childId,
4014
+ version,
4015
+ html
4016
+ });
4017
+ },
4018
+ hole(key, html) {
4019
+ emit({
4020
+ type: "hole",
4021
+ id,
4022
+ version,
4023
+ key,
4024
+ html
4025
+ });
4026
+ },
4027
+ attr(key, attrs, removed) {
4028
+ const chunk = {
4029
+ type: "attr",
4030
+ id,
4031
+ version,
4032
+ key,
4033
+ attrs
4034
+ };
4035
+ if (removed && removed.length) chunk.removed = removed;
4036
+ emit(chunk);
4037
+ },
4038
+ openBinding(key, b) {
4039
+ bindings.set(key, b);
4040
+ },
4041
+ closeBinding(key) {
4042
+ bindings.delete(key);
4043
+ },
4044
+ mintRef(ref) {
4045
+ sweepMinted.add(ref);
4046
+ },
4047
+ nextArgRef(ledgerKey) {
4048
+ const n = (argRefVersions.get(ledgerKey) || 0) + 1;
4049
+ argRefVersions.set(ledgerKey, n);
4050
+ return n;
4051
+ },
4052
+ commit: scheduleSweep,
4053
+ get epoch() {
4054
+ return epoch;
4055
+ }
4056
+ };
4057
+ }
4058
+ function renderToFrameStream(code, options = {}) {
4059
+ return frameStream(() => code, options);
4060
+ }
4061
+ function renderServerComponent(component, options = {}) {
4062
+ return frameStream((sink, frame) => {
4063
+ const props = createSlotProps(sink, frame);
4064
+ return () => {
4065
+ const ctx = sharedConfig.context;
4066
+ if (ctx) {
4067
+ ctx.commit = sink.commit;
4068
+ ctx.commitEpoch = () => sink.epoch;
4069
+ ctx.liveHoles = createLiveHoles(sink);
4070
+ ctx.claims = CLAIMS_STREAM;
4071
+ }
4072
+ return serverComponentScope(() => component(props));
4073
+ };
4074
+ }, options);
4075
+ }
4076
+ function frameStream(makeCode, options) {
4077
+ const {
4078
+ id = "",
4079
+ version = 1
4080
+ } = options.frame || {};
4081
+ const frame = {
4082
+ id,
4083
+ version
4084
+ };
4085
+ function stream(w) {
4086
+ const observation = observeFrame(frame);
4087
+ const emit = observation ? chunk => {
4088
+ observation.chunk(chunk);
4089
+ w.write(chunk);
4090
+ } : chunk => w.write(chunk);
4091
+ const sink = createFrameSink(emit, frame);
4092
+ w.write({
4093
+ type: "start",
4094
+ id,
4095
+ version
4096
+ });
4097
+ const code = makeCode(sink, frame);
4098
+ try {
4099
+ renderToStream(() => serverOwned(code), {
4100
+ serializer: createJSONSerializer,
4101
+ ...options,
4102
+ sink
4103
+ }).pipe({
4104
+ write() {},
4105
+ end() {
4106
+ sink.end();
4107
+ observation && observation.settle("complete");
4108
+ w.end && w.end();
4109
+ }
4110
+ });
4111
+ } catch (err) {
4112
+ const wire = ssrSanitizeError(err, null);
4113
+ sink.error("", wire instanceof Error ? wire.message : String(wire));
4114
+ sink.end();
4115
+ observation && observation.settle("error", err);
4116
+ w.end && w.end();
4117
+ }
4118
+ }
4119
+ return {
4120
+ pipe: stream,
4121
+ then(onFulfilled, onRejected) {
4122
+ return new Promise((resolve, reject) => {
4123
+ const chunks = [];
4124
+ try {
4125
+ stream({
4126
+ write: chunk => chunks.push(chunk),
4127
+ end: () => resolve(chunks)
4128
+ });
4129
+ } catch (err) {
4130
+ reject(err);
4131
+ }
4132
+ }).then(onFulfilled, onRejected);
4133
+ }
4134
+ };
4135
+ }
4136
+ function slotRange(occurrence) {
4137
+ return {
4138
+ t: `<!--slot:${occurrence}:start--><!--slot:${occurrence}:end-->`,
4139
+ $slot: true
4140
+ };
4141
+ }
4142
+ const OCCURRENCE_UNSAFE = /[^A-Za-z0-9_.-]/g;
4143
+ function encodeOccurrenceKey(key) {
4144
+ return String(key).replace(OCCURRENCE_UNSAFE, c => {
4145
+ const code = c.codePointAt(0);
4146
+ return "%" + (code < 16 ? "0" : "") + code.toString(16);
4147
+ });
4148
+ }
4149
+ function occurrenceId(prop, raw, counts) {
4150
+ const k = raw.$key;
4151
+ if (typeof k === "string" || typeof k === "number") {
4152
+ return `${prop}#${encodeOccurrenceKey(k)}`;
4153
+ }
4154
+ const n = counts[prop] || 0;
4155
+ counts[prop] = n + 1;
4156
+ return `${prop}#${n}`;
4157
+ }
4158
+ function isAsyncValue(v) {
4159
+ return !!v && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
4160
+ }
4161
+ function tapFirstYield(iterable) {
4162
+ const iter = iterable[Symbol.asyncIterator]();
4163
+ const firstStep = Promise.resolve(iter.next());
4164
+ return {
4165
+ first: firstStep.then(r => r.done ? undefined : r.value),
4166
+ rest: {
4167
+ [Symbol.asyncIterator]() {
4168
+ let replayed = false;
4169
+ return {
4170
+ next: () => {
4171
+ if (!replayed) {
4172
+ replayed = true;
4173
+ return firstStep;
4174
+ }
4175
+ return iter.next();
4176
+ },
4177
+ return: v => iter.return ? iter.return(v) : Promise.resolve({
4178
+ done: true,
4179
+ value: v
4180
+ }),
4181
+ throw: e => iter.throw ? iter.throw(e) : Promise.reject(e)
4182
+ };
4183
+ }
4184
+ }
4185
+ };
4186
+ }
4187
+ function suppressedFill(render) {
4188
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
4189
+ if (!live) return render();
4190
+ live.suppressed++;
4191
+ try {
4192
+ return render();
4193
+ } finally {
4194
+ live.suppressed--;
4195
+ }
4196
+ }
4197
+ function createDocumentSlotProps(clientProps, frameId) {
4198
+ const counts = Object.create(null);
4199
+ const getters = new Map();
4200
+ const range = (occurrence, content) => {
4201
+ const r = [{
4202
+ t: `<!--slot:${occurrence}:start-->`
4203
+ }, content, {
4204
+ t: `<!--slot:${occurrence}:end-->`
4205
+ }];
4206
+ r.$slot = true;
4207
+ return r;
4208
+ };
4209
+ const zoneOwner = getOwner ? getOwner() : null;
4210
+ const scoped = (occurrence, render) => {
4211
+ const id = `sc-${frameId}-${occurrence}-`;
4212
+ const run = () => Hydration ? Hydration({
4213
+ id,
4214
+ get children() {
4215
+ return render();
4216
+ }
4217
+ }) : runWithHydrationScope(id, render);
4218
+ return zoneOwner ? runWithOwner(zoneOwner, run) : run();
4219
+ };
4220
+ return new Proxy(Object.create(null), {
4221
+ has() {
4222
+ return true;
4223
+ },
4224
+ get(_, prop) {
4225
+ if (typeof prop !== "string") return undefined;
4226
+ if (prop === "then") return undefined;
4227
+ let fn = getters.get(prop);
4228
+ if (!fn) {
4229
+ fn = (...callArgs) => {
4230
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
4231
+ return suppressedFill(() => scoped(prop, () => {
4232
+ const value = clientProps[prop];
4233
+ return range(prop, typeof value === "function" ? value() : value);
4234
+ }));
4235
+ }
4236
+ const raw = callArgs[0];
4237
+ const occurrence = occurrenceId(prop, raw, counts);
4238
+ const slot = clientProps[prop];
4239
+ if (typeof slot !== "function") return range(occurrence, undefined);
4240
+ const resolved = {};
4241
+ const liveArgs = sharedConfig.context && sharedConfig.context.live && sharedConfig.context.live.args;
4242
+ const vals = {};
4243
+ const evals = {};
4244
+ const states = {};
4245
+ const minted = {};
4246
+ for (const key of Object.keys(raw)) {
4247
+ if (key === "$key") continue;
4248
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
4249
+ let evaluate = null;
4250
+ let value;
4251
+ if (desc.get) {
4252
+ const get = desc.get;
4253
+ evaluate = () => unwrapThunks(get.call(raw));
4254
+ } else {
4255
+ value = desc.value;
4256
+ if (typeof value === "function") {
4257
+ const fn = value;
4258
+ evaluate = () => unwrapThunks(fn);
4259
+ }
4260
+ }
4261
+ if (evaluate) {
4262
+ evals[key] = evaluate;
4263
+ const stampBefore = scopeStamp();
4264
+ try {
4265
+ value = evaluate();
4266
+ states[key] = {
4267
+ settled: true,
4268
+ last: value
4269
+ };
4270
+ } catch (err) {
4271
+ const blocked = ssrHandleError && ssrHandleError(err);
4272
+ if (!blocked) throw err;
4273
+ const state = states[key] = {
4274
+ settled: false,
4275
+ last: undefined
4276
+ };
4277
+ value = retryArgUntilSettled(evaluate, blocked, key, occurrence, v => {
4278
+ state.settled = true;
4279
+ state.last = v;
4280
+ if (liveArgs) liveArgs.commit();
4281
+ });
4282
+ }
4283
+ if (scopeStamp() !== stampBefore) minted[key] = true;
4284
+ }
4285
+ vals[key] = value;
4286
+ }
4287
+ const regions = [];
4288
+ for (const key of Object.keys(vals)) {
4289
+ const value = vals[key];
4290
+ if (isContainerTraced(value)) {
4291
+ resolved[key] = value;
4292
+ } else if (isServerContent(value)) {
4293
+ const childId = `${frameId}.${occurrence}.${key}`;
4294
+ const region = {
4295
+ key,
4296
+ childId,
4297
+ value,
4298
+ used: false,
4299
+ locked: false
4300
+ };
4301
+ regions.push(region);
4302
+ resolved[key] = () => {
4303
+ if (region.locked) return [];
4304
+ region.used = true;
4305
+ return [{
4306
+ t: frameElementOpen(childId)
4307
+ }, value, {
4308
+ t: FRAME_ELEMENT_CLOSE
4309
+ }];
4310
+ };
4311
+ } else if (ssrAsyncValue && isAsyncValue(value)) {
4312
+ let readable = value;
4313
+ if (typeof value.then !== "function") {
4314
+ const {
4315
+ first,
4316
+ rest
4317
+ } = tapFirstYield(value);
4318
+ readable = first;
4319
+ vals[key] = rest;
4320
+ }
4321
+ const read = ssrAsyncValue(readable);
4322
+ Object.defineProperty(resolved, key, {
4323
+ get: read,
4324
+ enumerable: true,
4325
+ configurable: true
4326
+ });
4327
+ } else {
4328
+ resolved[key] = value;
4329
+ }
4330
+ }
4331
+ const out = suppressedFill(() => scoped(occurrence, () => range(occurrence, slot(resolved))));
4332
+ const unused = regions.filter(r => !r.used);
4333
+ if (sharedConfig.context) {
4334
+ const args = {};
4335
+ for (const key of Object.keys(vals)) {
4336
+ const value = vals[key];
4337
+ const region = regions.find(r => r.key === key);
4338
+ if (region) {
4339
+ args[key] = {
4340
+ $frame: region.childId
4341
+ };
4342
+ continue;
4343
+ }
4344
+ if (!isContainerTraced(value) && isServerContent(value)) continue;
4345
+ args[key] = envelopeContainerTraces(value);
4346
+ }
4347
+ sharedConfig.context.serialize(`sc:slot:${frameId}:${occurrence}`, {
4348
+ ...args
4349
+ });
4350
+ for (const region of unused) {
4351
+ region.locked = true;
4352
+ sharedConfig.context.serialize(`sc:region:${region.childId}`, resolveRegionHtml(sharedConfig.context, region.value));
4353
+ }
4354
+ if (liveArgs) {
4355
+ for (const key of Object.keys(evals)) {
4356
+ if (regions.some(r => r.key === key)) continue;
4357
+ if (minted[key]) continue;
4358
+ const ledgerKey = `${frameId}:${occurrence}:${key}`;
4359
+ openArgBinding(liveArgs, ledgerKey, occurrence, key, evals[key], states[key], value => {
4360
+ args[key] = envelopeContainerTraces(value);
4361
+ liveArgs.slot(frameId, occurrence, {
4362
+ ...args
4363
+ });
4364
+ });
4365
+ }
4366
+ }
4367
+ }
4368
+ return out;
4369
+ };
4370
+ fn.$lhSkip = true;
4371
+ fn[CLAIM_PROP] = prop;
4372
+ getters.set(prop, fn);
4373
+ }
4374
+ return fn;
4375
+ }
4376
+ });
4377
+ }
4378
+ const FRAME_TAG = "solid-frame";
4379
+ const FRAME_ID_ATTR = "data-fid";
4380
+ function frameElementOpen(id) {
4381
+ const escaped = sharedConfig.context ? sharedConfig.context.escape(String(id), true) : String(id);
4382
+ return `<${FRAME_TAG} ${FRAME_ID_ATTR}="${escaped}" style="display:contents">`;
4383
+ }
4384
+ const FRAME_ELEMENT_CLOSE = `</${FRAME_TAG}>`;
4385
+ function armDocumentLiveHoles(ctx) {
4386
+ if (!ctx || ctx.liveHoles !== undefined) return;
4387
+ const live = ctx.live;
4388
+ if (live && live.holes !== undefined) {
4389
+ ctx.liveHoles = live.holes;
4390
+ if (live.holes) {
4391
+ ctx.commit = live.commit;
4392
+ ctx.commitEpoch = live.commitEpoch;
4393
+ }
4394
+ return;
4395
+ }
4396
+ if (!live || !ctx.async || ctx.noHydrate || !ctx.serialize || typeof ReadableStream !== "function") {
4397
+ ctx.liveHoles = null;
4398
+ if (live) live.holes = null;
4399
+ return;
4400
+ }
4401
+ const bindings = new Map();
4402
+ let epoch = 0;
4403
+ let sweepScheduled = false;
4404
+ let closed = false;
4405
+ const sweep = () => {
4406
+ epoch++;
4407
+ for (const b of [...bindings.values()]) {
4408
+ try {
4409
+ b.sweep();
4410
+ } catch (_) {
4411
+ }
4412
+ }
4413
+ };
4414
+ const scheduleSweep = () => {
4415
+ if (closed || sweepScheduled || !bindings.size) return;
4416
+ sweepScheduled = true;
4417
+ queueMicrotask(() => {
4418
+ sweepScheduled = false;
4419
+ if (!closed) sweep();
4420
+ });
4421
+ };
4422
+ let channel;
4423
+ ctx.serialize("sc:live", new ReadableStream({
4424
+ start(c) {
4425
+ channel = c;
4426
+ }
4427
+ }));
4428
+ const push = op => {
4429
+ if (!closed) channel.enqueue(op);
4430
+ };
4431
+ ctx.liveHoles = live.holes = createLiveHoles({
4432
+ openBinding(key, b) {
4433
+ bindings.set(key, b);
4434
+ },
4435
+ closeBinding(key) {
4436
+ bindings.delete(key);
4437
+ },
4438
+ hole(key, html) {
4439
+ push({
4440
+ type: "hole",
4441
+ key,
4442
+ html
4443
+ });
4444
+ },
4445
+ attr(key, attrs, removed) {
4446
+ const op = {
4447
+ type: "attr",
4448
+ key,
4449
+ attrs
4450
+ };
4451
+ if (removed && removed.length) op.removed = removed;
4452
+ push(op);
4453
+ },
4454
+ error(key, error) {
4455
+ push({
4456
+ type: "error",
4457
+ key,
4458
+ error
4459
+ });
4460
+ },
4461
+ commit: scheduleSweep,
4462
+ get epoch() {
4463
+ return epoch;
4464
+ }
4465
+ }, true);
4466
+ ctx.commit = live.commit = scheduleSweep;
4467
+ ctx.commitEpoch = live.commitEpoch = () => epoch;
4468
+ live.args = {
4469
+ openBinding(key, b) {
4470
+ bindings.set(key, b);
4471
+ },
4472
+ closeBinding(key) {
4473
+ bindings.delete(key);
4474
+ },
4475
+ slot(fid, occurrence, args) {
4476
+ push({
4477
+ type: "slot",
4478
+ fid,
4479
+ key: occurrence,
4480
+ args
4481
+ });
4482
+ },
4483
+ commit: scheduleSweep
4484
+ };
4485
+ live.end = () => {
4486
+ if (closed) return;
4487
+ if (bindings.size) sweep();
4488
+ closed = true;
4489
+ channel.close();
4490
+ };
4491
+ }
4492
+ function frameTransformDirectResult(value, {
4493
+ id,
4494
+ args
4495
+ }) {
4496
+ if (typeof value !== "function") return value;
4497
+ const component = value;
4498
+ const wrapped = props => [{
4499
+ t: frameElementOpen(id)
4500
+ },
4501
+ serverOwned(() => {
4502
+ armDocumentLiveHoles(sharedConfig.context);
4503
+ sharedConfig.context.claims = CLAIMS_DOCUMENT;
4504
+ const slotProps = createDocumentSlotProps(props, id);
4505
+ return serverComponentScope(() => component(slotProps));
4506
+ }), {
4507
+ t: FRAME_ELEMENT_CLOSE
4508
+ }];
4509
+ wrapped[SERVER_COMPONENT] = id;
4510
+ wrapped[SERVER_COMPONENT_SOURCE] = component;
4511
+ wrapped[SERVER_COMPONENT_ADDRESS] = frameAddress(id, args);
4512
+ return wrapped;
4513
+ }
4514
+ function resolveRegionHtml(ctx, node) {
4515
+ const res = ctx.resolve(node);
4516
+ if (!res || !res.t) return String(res ?? "");
4517
+ if (!res.h || !res.h.length) return res.t[0];
4518
+ return Promise.all(res.p).then(() => {
4519
+ let out = Promise.resolve(res.t[0]);
4520
+ for (let i = 0; i < res.h.length; i++) {
4521
+ const hole = res.h[i];
4522
+ const tail = res.t[i + 1];
4523
+ out = out.then(acc => Promise.resolve(resolveRegionHtml(ctx, hole)).then(part => acc + part + tail));
4524
+ }
4525
+ return out;
4526
+ });
4527
+ }
4528
+ function isServerContent(value) {
4529
+ if (value && typeof value === "object") {
4530
+ if ("t" in value) return true;
4531
+ if (Array.isArray(value) && value.length > 0) {
4532
+ for (const item of value) {
4533
+ if (!(item && typeof item === "object" && "t" in item)) return false;
4534
+ }
4535
+ return true;
4536
+ }
4537
+ }
4538
+ return false;
4539
+ }
4540
+ function unwrapThunks(value) {
4541
+ for (let d = 0; typeof value === "function" && d < 16; d++) value = value();
4542
+ return value;
4543
+ }
4544
+ function contentArgError(key, occurrence) {
4545
+ return new Error("Async slot arg resolved to JSX (arg '" + key + "' of " + occurrence + "). Async args must resolve to serializable values; render async content through a boundary instead.");
4546
+ }
4547
+ function retryArgUntilSettled(evaluate, blocked, key, occurrence, onSettle) {
4548
+ const owner = getOwner();
4549
+ return new Promise((resolve, reject) => {
4550
+ const retry = () => {
4551
+ try {
4552
+ const value = owner ? runWithOwner(owner, evaluate) : evaluate();
4553
+ if (isServerContent(value)) {
4554
+ reject(contentArgError(key, occurrence));
4555
+ return;
4556
+ }
4557
+ if (onSettle) onSettle(value);
4558
+ resolve(value);
4559
+ } catch (err) {
4560
+ const next = ssrHandleError && ssrHandleError(err);
4561
+ if (next) next.then(retry, retry);else reject(err);
4562
+ }
4563
+ };
4564
+ blocked.then(retry, retry);
4565
+ });
4566
+ }
4567
+ function openArgBinding(sink, ledgerKey, occurrence, key, evaluate, state, emit) {
4568
+ const owner = getOwner();
4569
+ sink.openBinding(ledgerKey, {
4570
+ sweep() {
4571
+ if (!state.settled) return;
4572
+ let value;
4573
+ const stampBefore = scopeStamp();
4574
+ try {
4575
+ value = owner ? runWithOwner(owner, evaluate) : evaluate();
4576
+ } catch (err) {
4577
+ const blocked = ssrHandleError && ssrHandleError(err);
4578
+ if (!blocked) {
4579
+ sink.closeBinding(ledgerKey);
4580
+ emit(Promise.reject(err instanceof Error ? err : new Error(String(err))));
4581
+ return;
4582
+ }
4583
+ if (scopeStamp() !== stampBefore) {
4584
+ sink.closeBinding(ledgerKey);
4585
+ return;
4586
+ }
4587
+ state.settled = false;
4588
+ emit(retryArgUntilSettled(evaluate, blocked, key, occurrence, v => {
4589
+ state.settled = true;
4590
+ state.last = v;
4591
+ sink.commit();
4592
+ }));
4593
+ return;
4594
+ }
4595
+ if (scopeStamp() !== stampBefore) {
4596
+ sink.closeBinding(ledgerKey);
4597
+ return;
4598
+ }
4599
+ if (value === state.last) return;
4600
+ state.last = value;
4601
+ if (isServerContent(value)) {
4602
+ sink.closeBinding(ledgerKey);
4603
+ emit(Promise.reject(contentArgError(key, occurrence)));
4604
+ return;
4605
+ }
4606
+ emit(value);
4607
+ }
4608
+ });
4609
+ }
4610
+ function createSlotProps(sink, frame) {
4611
+ const counts = Object.create(null);
4612
+ const getters = new Map();
4613
+ return new Proxy(Object.create(null), {
4614
+ has() {
4615
+ return true;
4616
+ },
4617
+ get(_, prop) {
4618
+ if (typeof prop !== "string") return undefined;
4619
+ if (prop === "then") return undefined;
4620
+ let fn = getters.get(prop);
4621
+ if (!fn) {
4622
+ fn = (...callArgs) => {
4623
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
4624
+ return slotRange(prop);
4625
+ }
4626
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
4627
+ if (live) {
4628
+ if (live.sweeping) {
4629
+ live.gateHit = true;
4630
+ return {
4631
+ t: "",
4632
+ $slot: true
4633
+ };
4634
+ }
4635
+ live.recordStamp++;
4636
+ }
4637
+ const raw = callArgs[0];
4638
+ const occurrence = occurrenceId(prop, raw, counts);
4639
+ const args = {};
4640
+ const opened = [];
4641
+ for (const key of Object.keys(raw)) {
4642
+ if (key === "$key") continue;
4643
+ const childId = `${frame.id}.${occurrence}.${key}`;
4644
+ const ctx = sharedConfig.context;
4645
+ const origRegister = ctx.registerFragment;
4646
+ ctx.registerFragment = (fragKey, fragOptions) => {
4647
+ sink.tagRegion(fragKey, childId);
4648
+ return origRegister.call(ctx, fragKey, fragOptions);
4649
+ };
4650
+ try {
4651
+ const desc = Object.getOwnPropertyDescriptor(raw, key);
4652
+ let evaluate = null;
4653
+ let value;
4654
+ let state = null;
4655
+ const stampBefore = scopeStamp();
4656
+ try {
4657
+ if (desc.get) {
4658
+ const get = desc.get;
4659
+ evaluate = () => unwrapThunks(get.call(raw));
4660
+ value = evaluate();
4661
+ } else {
4662
+ value = desc.value;
4663
+ if (typeof value === "function") {
4664
+ const fn = value;
4665
+ evaluate = () => unwrapThunks(fn);
4666
+ value = evaluate();
4667
+ }
4668
+ }
4669
+ } catch (err) {
4670
+ const blocked = ssrHandleError && ssrHandleError(err);
4671
+ if (!blocked) throw err;
4672
+ state = {
4673
+ settled: false,
4674
+ last: undefined
4675
+ };
4676
+ const pendingState = state;
4677
+ value = retryArgUntilSettled(evaluate, blocked, key, occurrence, v => {
4678
+ pendingState.settled = true;
4679
+ pendingState.last = v;
4680
+ sink.commit();
4681
+ });
4682
+ }
4683
+ const mintedEval = scopeStamp() !== stampBefore;
4684
+ const t = typeof value;
4685
+ if (value == null || t === "string" || t === "number" || t === "boolean") {
4686
+ args[key] = value;
4687
+ if (evaluate) state = {
4688
+ settled: true,
4689
+ last: value
4690
+ };
4691
+ } else if (!isContainerTraced(value) && isServerContent(value)) {
4692
+ const resolved = ctx.resolve(value);
4693
+ if (resolved.h.length) {
4694
+ throw new Error("Async server content in a slot arg needs a boundary (arg '" + key + "' of " + occurrence + "). Wrap the async read in a <Suspense>, or move it above the slot.");
4695
+ }
4696
+ sink.region(childId, resolved.t[0]);
4697
+ args[key] = {
4698
+ $frame: childId
4699
+ };
4700
+ } else {
4701
+ const ref = `arg:${occurrence}:${key}`;
4702
+ ctx.serialize(ref, envelopeContainerTraces(value));
4703
+ args[key] = {
4704
+ $ref: ref
4705
+ };
4706
+ if (evaluate && !state) state = {
4707
+ settled: true,
4708
+ last: value
4709
+ };
4710
+ }
4711
+ if (evaluate && state && !mintedEval) opened.push({
4712
+ key,
4713
+ evaluate,
4714
+ state
4715
+ });
4716
+ } finally {
4717
+ ctx.registerFragment = origRegister;
4718
+ }
4719
+ }
4720
+ sink.slot(occurrence, {
4721
+ ...args
4722
+ });
4723
+ const ctx = sharedConfig.context;
4724
+ for (const b of opened) {
4725
+ const key = b.key;
4726
+ const ledgerKey = `${occurrence}:${key}`;
4727
+ openArgBinding(sink, ledgerKey, occurrence, key, b.evaluate, b.state, value => {
4728
+ const t = typeof value;
4729
+ if (value == null || t === "string" || t === "number" || t === "boolean") {
4730
+ args[key] = value;
4731
+ } else {
4732
+ const ref = `arg:${occurrence}:${key}@${sink.nextArgRef(ledgerKey)}`;
4733
+ sink.mintRef(ref);
4734
+ ctx.serialize(ref, envelopeContainerTraces(value));
4735
+ args[key] = {
4736
+ $ref: ref
4737
+ };
4738
+ }
4739
+ sink.slot(occurrence, {
4740
+ ...args
4741
+ });
4742
+ });
4743
+ }
4744
+ return slotRange(occurrence);
4745
+ };
4746
+ fn.$lhSkip = true;
4747
+ fn[CLAIM_PROP] = prop;
4748
+ getters.set(prop, fn);
4749
+ }
4750
+ return fn;
4751
+ }
4752
+ });
4753
+ }
4754
+ function copyInitHeaders(init) {
4755
+ if (!init || !init.getSetCookie) return new Headers(init);
4756
+ const headers = new Headers();
4757
+ init.forEach((value, key) => {
4758
+ if (key !== "set-cookie") headers.append(key, value);
4759
+ });
4760
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
4761
+ return headers;
4762
+ }
4763
+ function serverComponentResponse(component, options = {}, init = {}) {
4764
+ const {
4765
+ id = "",
4766
+ version = 1
4767
+ } = options.frame || {};
4768
+ const headers = copyInitHeaders(init.headers);
4769
+ headers.set("Content-Type", "application/x-frame-stream");
4770
+ headers.set(FRAME_STREAM_HEADER, id);
4771
+ headers.set("X-Content-Raw", "1");
4772
+ const stream = renderServerComponent(component, {
4773
+ ...options,
4774
+ frame: {
4775
+ id,
4776
+ version
4777
+ }
4778
+ });
4779
+ let closed = false;
4780
+ const body = new ReadableStream({
4781
+ start(controller) {
4782
+ stream.pipe({
4783
+ write(chunk) {
4784
+ if (closed) return;
4785
+ try {
4786
+ controller.enqueue(createChunk(JSON.stringify(chunk)));
4787
+ } catch (_) {
4788
+ closed = true;
4789
+ }
4790
+ },
4791
+ end() {
4792
+ if (closed) return;
4793
+ closed = true;
4794
+ controller.close();
4795
+ }
4796
+ });
4797
+ },
4798
+ cancel() {
4799
+ closed = true;
4800
+ }
4801
+ });
4802
+ return new Response(body, {
4803
+ status: init.status || 200,
4804
+ headers
4805
+ });
4806
+ }
4807
+ function frameTransformResult(event, result, context) {
4808
+ let init;
4809
+ if (isResponseEnvelope(result)) {
4810
+ const {
4811
+ response,
4812
+ value
4813
+ } = result;
4814
+ if (typeof value !== "function") return result;
4815
+ init = response ? {
4816
+ headers: response.headers,
4817
+ status: response.status
4818
+ } : undefined;
4819
+ result = value;
4820
+ }
4821
+ if (typeof result !== "function") return result;
4822
+ if (context && context.collectsFlight) return init ? {
4823
+ response: init,
4824
+ value: result
4825
+ } : result;
4826
+ const invocation = getEventServerFunctionInvocation(event);
4827
+ return serverComponentResponse(result, {
4828
+ frame: {
4829
+ id: invocation && invocation.id || ""
4830
+ }
4831
+ }, init);
4832
+ }
4833
+ async function frameTransformFlightResult(event, outcome, context) {
4834
+ const {
4835
+ value,
4836
+ data
4837
+ } = outcome;
4838
+ const regions = [];
4839
+ let serialized = data;
4840
+ if (data && typeof data === "object") {
4841
+ serialized = {};
4842
+ const keys = Object.keys(data);
4843
+ const values = await Promise.all(keys.map(key => data[key]));
4844
+ for (let i = 0; i < keys.length; i++) {
4845
+ const entry = values[i];
4846
+ serialized[keys[i]] = entry;
4847
+ if (typeof entry === "function") {
4848
+ regions.push({
4849
+ id: entry[SERVER_COMPONENT_ADDRESS] || keys[i],
4850
+ component: entry[SERVER_COMPONENT_SOURCE] || entry
4851
+ });
4852
+ }
4853
+ }
4854
+ }
4855
+ const invocation = getEventServerFunctionInvocation(event);
4856
+ const primary = typeof value === "function" ? {
4857
+ id: invocation && invocation.id || "",
4858
+ component: value
4859
+ } : undefined;
4860
+ if (!primary && !regions.length) return undefined;
4861
+ return frameFlightResponse({
4862
+ primary,
4863
+ regions,
4864
+ outcome: {
4865
+ value: primary ? undefined : value,
4866
+ data: serialized
4867
+ },
4868
+ codec: context && context.codec
4869
+ });
4870
+ }
4871
+ function frameFlightResponse({
4872
+ primary,
4873
+ regions = [],
4874
+ outcome,
4875
+ codec
4876
+ }, init = {}) {
4877
+ const frames = primary ? [primary, ...regions] : regions;
4878
+ const headers = copyInitHeaders(init.headers);
4879
+ headers.set("Content-Type", "application/x-frame-stream");
4880
+ headers.set(FRAME_STREAM_HEADER, primary ? primary.id : "");
4881
+ headers.set("X-Content-Raw", "1");
4882
+ headers.set(SINGLE_FLIGHT_HEADER, "true");
4883
+ let closed = false;
4884
+ const body = new ReadableStream({
4885
+ async start(controller) {
4886
+ const write = chunk => {
4887
+ if (closed) return;
4888
+ try {
4889
+ controller.enqueue(createChunk(JSON.stringify(chunk)));
4890
+ } catch (_) {
4891
+ closed = true;
4892
+ }
4893
+ };
4894
+ try {
4895
+ for (const {
4896
+ id,
4897
+ component
4898
+ } of frames) {
4899
+ await new Promise(resolve => {
4900
+ renderServerComponent(component, {
4901
+ frame: {
4902
+ id,
4903
+ version: 1
4904
+ }
4905
+ }).pipe({
4906
+ write,
4907
+ end: resolve
4908
+ });
4909
+ });
4910
+ }
4911
+ if (outcome) {
4912
+ const reader = new ChunkReader(serializeStream(guardFailures(outcome), flightCodec(codec)));
4913
+ for (let node = await reader.next(); !node.done; node = await reader.next()) {
4914
+ write({
4915
+ type: "outcome",
4916
+ payload: node.value
4917
+ });
4918
+ }
4919
+ }
4920
+ if (!closed) {
4921
+ closed = true;
4922
+ controller.close();
4923
+ }
4924
+ } catch (err) {
4925
+ if (!closed) {
4926
+ closed = true;
4927
+ controller.error(err);
4928
+ }
4929
+ }
4930
+ },
4931
+ cancel() {
4932
+ closed = true;
4933
+ }
4934
+ });
4935
+ return new Response(body, {
4936
+ status: init.status || 200,
4937
+ headers
4938
+ });
4939
+ }
4940
+
4941
+ setContainerTraceResolver(getProjectionTrace);
4942
+ function asyncArg(value) {
4943
+ return value;
4944
+ }
4945
+
4946
+ export { FRAME_STREAM_HEADER, SERVER_COMPONENT_BOOTSTRAP, ServerComponentPlugin, asyncArg, createFrameSink, frameTransformDirectResult, frameTransformFlightResult, frameTransformResult, isFrameStreamResponse, renderServerComponent, renderToFrameStream, serverComponentResponse };