@solidjs/web 2.0.0-beta.3 → 2.0.0-beta.31

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 (73) hide show
  1. package/README.md +27 -4
  2. package/dist/dev.cjs +1224 -205
  3. package/dist/dev.js +1188 -199
  4. package/dist/server.cjs +1429 -234
  5. package/dist/server.js +1391 -231
  6. package/dist/web.cjs +1207 -195
  7. package/dist/web.js +1171 -189
  8. package/frames/dist/client.cjs +1694 -0
  9. package/frames/dist/client.dev.cjs +1707 -0
  10. package/frames/dist/client.dev.js +1695 -0
  11. package/frames/dist/client.js +1682 -0
  12. package/frames/dist/server.cjs +2520 -0
  13. package/frames/dist/server.js +2508 -0
  14. package/frames/package.json +30 -0
  15. package/package.json +285 -37
  16. package/serialization/dist/serialization.cjs +169 -0
  17. package/serialization/dist/serialization.js +159 -0
  18. package/serialization/package.json +20 -0
  19. package/serialization/types/index.d.ts +157 -0
  20. package/serialization/types-cjs/index.d.cts +157 -0
  21. package/serialization/types-cjs/package.json +3 -0
  22. package/server-functions/dist/client.cjs +613 -0
  23. package/server-functions/dist/client.js +585 -0
  24. package/server-functions/dist/server.cjs +904 -0
  25. package/server-functions/dist/server.js +875 -0
  26. package/server-functions/package.json +30 -0
  27. package/storage/package.json +8 -3
  28. package/storage/types/index.d.ts +26 -0
  29. package/storage/types-cjs/index.d.cts +28 -0
  30. package/storage/types-cjs/package.json +3 -0
  31. package/types/client.d.ts +127 -21
  32. package/types/core.d.ts +4 -3
  33. package/types/frames/client.d.ts +22 -0
  34. package/types/frames/frame-client.d.ts +282 -0
  35. package/types/frames/frame-sink.d.ts +171 -0
  36. package/types/frames/frame-transport.d.ts +190 -0
  37. package/types/frames/serializer.d.ts +157 -0
  38. package/types/frames/server.d.ts +30 -0
  39. package/types/index.d.ts +211 -26
  40. package/types/jsx-properties.d.ts +93 -0
  41. package/types/jsx.d.ts +4150 -1
  42. package/types/response.d.ts +129 -0
  43. package/types/serializer.d.ts +157 -0
  44. package/types/server-functions/client.d.ts +200 -0
  45. package/types/server-functions/flash.d.ts +38 -0
  46. package/types/server-functions/server.d.ts +490 -0
  47. package/types/server-functions/shared.d.ts +445 -0
  48. package/types/server-mock.d.ts +93 -0
  49. package/types/server.d.ts +223 -28
  50. package/types-cjs/client.d.cts +194 -0
  51. package/types-cjs/core.d.cts +4 -0
  52. package/types-cjs/frames/client.d.cts +22 -0
  53. package/types-cjs/frames/frame-client.d.cts +282 -0
  54. package/types-cjs/frames/frame-sink.d.cts +171 -0
  55. package/types-cjs/frames/frame-transport.d.cts +190 -0
  56. package/types-cjs/frames/serializer.d.cts +157 -0
  57. package/types-cjs/frames/server.d.cts +30 -0
  58. package/types-cjs/index.d.cts +231 -0
  59. package/types-cjs/jsx-properties.d.cts +93 -0
  60. package/types-cjs/jsx.d.cts +4150 -0
  61. package/types-cjs/package.json +3 -0
  62. package/types-cjs/response.d.cts +129 -0
  63. package/types-cjs/serializer.d.cts +157 -0
  64. package/types-cjs/server-functions/client.d.cts +200 -0
  65. package/types-cjs/server-functions/flash.d.cts +38 -0
  66. package/types-cjs/server-functions/server.d.cts +490 -0
  67. package/types-cjs/server-functions/shared.d.cts +445 -0
  68. package/types-cjs/server-mock.d.cts +165 -0
  69. package/types-cjs/server.d.cts +351 -0
  70. package/storage/types/src/client.d.ts +0 -1
  71. package/storage/types/src/index.d.ts +0 -46
  72. package/storage/types/src/server-mock.d.ts +0 -72
  73. package/storage/types/storage/src/index.d.ts +0 -2
@@ -0,0 +1,2508 @@
1
+ import { runWithOwner, createOwner, sharedConfig, createRoot, ssrHandleError, getOwner, NoHydration, runInServerComponentScope, Hydration } from 'solid-js';
2
+ import { toCrossJSONStream, Feature, Serializer, getCrossReferenceHeader, createPlugin } from 'seroval';
3
+ import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
4
+
5
+ const runWithHydrationScope = (id, fn) => runWithOwner(createOwner({
6
+ id
7
+ }), fn);
8
+
9
+ const DEFAULT_DISABLED_FEATURES = Feature.AggregateError | Feature.BigIntTypedArray;
10
+ const serializeOnlyDisabledFeatures = () => process.env.NODE_ENV === "development" ? 0 : Feature.ErrorPrototypeStack;
11
+ const HYDRATION_GLOBAL = "_$HY.r";
12
+ const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
13
+ CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
14
+ FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin]);
15
+ function resolveSerializerPlugins(customPlugins) {
16
+ return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
17
+ }
18
+ function createSerializer(options) {
19
+ return new Serializer({
20
+ ...options,
21
+ plugins: resolveSerializerPlugins(options.plugins),
22
+ disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures()
23
+ });
24
+ }
25
+ function createHydrationSerializer({
26
+ onData,
27
+ onDone,
28
+ scopeId,
29
+ onError,
30
+ plugins
31
+ }) {
32
+ return createSerializer({
33
+ scopeId,
34
+ plugins,
35
+ globalIdentifier: HYDRATION_GLOBAL,
36
+ onData,
37
+ onDone,
38
+ onError
39
+ });
40
+ }
41
+ function getLocalHeaderScript(id) {
42
+ return getCrossReferenceHeader(id) + ";";
43
+ }
44
+ const JSON_CODEC_DISABLED_FEATURES = Feature.RegExp;
45
+ const JSON_CODEC_DEPTH_LIMIT = 64;
46
+ function resolveCodecOptions({
47
+ plugins,
48
+ disabledFeatures,
49
+ depthLimit
50
+ } = {}) {
51
+ return {
52
+ plugins: resolveSerializerPlugins(plugins),
53
+ disabledFeatures: disabledFeatures === undefined ? JSON_CODEC_DISABLED_FEATURES : disabledFeatures,
54
+ depthLimit: depthLimit === undefined ? JSON_CODEC_DEPTH_LIMIT : depthLimit
55
+ };
56
+ }
57
+ function serializeJSON(value, {
58
+ onParse,
59
+ onDone,
60
+ onError,
61
+ ...codecOptions
62
+ }) {
63
+ const resolved = resolveCodecOptions(codecOptions);
64
+ return toCrossJSONStream(value, {
65
+ onParse,
66
+ onDone,
67
+ onError,
68
+ ...resolved,
69
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures()
70
+ });
71
+ }
72
+ function createJSONSerializer({
73
+ onData,
74
+ onDone,
75
+ onError,
76
+ plugins,
77
+ disabledFeatures,
78
+ depthLimit
79
+ }) {
80
+ const resolved = resolveCodecOptions({
81
+ plugins,
82
+ disabledFeatures,
83
+ depthLimit
84
+ });
85
+ const refs = new Map();
86
+ const cancels = new Set();
87
+ let pendingWrites = 0;
88
+ let flushed = false;
89
+ let done = false;
90
+ const maybeDone = () => {
91
+ if (flushed && pendingWrites === 0 && !done) {
92
+ done = true;
93
+ onDone && onDone();
94
+ }
95
+ };
96
+ return {
97
+ write(key, value) {
98
+ if (flushed) return;
99
+ pendingWrites++;
100
+ let settled = false;
101
+ let cancel = null;
102
+ const stream = toCrossJSONStream(value, {
103
+ refs,
104
+ plugins: resolved.plugins,
105
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(),
106
+ onParse(node, initial) {
107
+ onData({
108
+ key,
109
+ node,
110
+ initial
111
+ });
112
+ },
113
+ onError,
114
+ onDone() {
115
+ settled = true;
116
+ if (cancel) cancels.delete(cancel);
117
+ pendingWrites--;
118
+ maybeDone();
119
+ }
120
+ });
121
+ if (!settled) {
122
+ cancel = stream;
123
+ cancels.add(cancel);
124
+ }
125
+ },
126
+ flush() {
127
+ flushed = true;
128
+ maybeDone();
129
+ },
130
+ close() {
131
+ flushed = true;
132
+ for (const cancel of cancels) cancel();
133
+ cancels.clear();
134
+ }
135
+ };
136
+ }
137
+
138
+ const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
139
+ const HEAD_ATTR_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;
140
+ const RESOURCE_LINK_RELS = new Set(["preload", "modulepreload", "prefetch", "preconnect", "dns-prefetch", "stylesheet"]);
141
+ const RESOURCE_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
142
+ const STYLESHEET_FETCH_META = new Set(["crossorigin", "integrity", "referrerpolicy", "fetchpriority"]);
143
+ function evalHeadValue(v) {
144
+ return typeof v === "function" ? v() : v;
145
+ }
146
+ function evalHeadProps(props, presets) {
147
+ const out = {};
148
+ for (const name in props) out[name] = presets && name in presets ? presets[name] : evalHeadValue(props[name]);
149
+ return out;
150
+ }
151
+ function classifyHeadTag(desc) {
152
+ const tag = desc.tag;
153
+ if (tag === "link") {
154
+ const rel = evalHeadValue(desc.props && desc.props.rel);
155
+ return {
156
+ resource: RESOURCE_LINK_RELS.has(rel),
157
+ rel
158
+ };
159
+ }
160
+ if (tag === "style") return {
161
+ resource: !!(desc.props && "href" in desc.props)
162
+ };
163
+ if (tag === "script") return {
164
+ resource: !!(desc.props && "src" in desc.props)
165
+ };
166
+ return {
167
+ resource: false
168
+ };
169
+ }
170
+ function resourceIdentity(tag, props) {
171
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
172
+ for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
173
+ const q = RESOURCE_QUALIFIERS[i];
174
+ if (props[q] != null) id += ":" + q + "=" + props[q];
175
+ }
176
+ return id;
177
+ }
178
+ function replaceableIdentity(tag, props, key, unique) {
179
+ if (tag === "title") return "title";
180
+ if (tag === "base") return "base";
181
+ if (tag === "meta" && props.charset != null) return "charset";
182
+ if (key != null) return tag + ":key:" + key;
183
+ if (tag === "meta") {
184
+ for (const ns of ["name", "property", "http-equiv"]) if (props[ns] != null) return "meta:" + ns + ":" + props[ns] + (props.media != null ? ":media=" + props.media : "");
185
+ return unique;
186
+ }
187
+ if (tag === "link") {
188
+ const rel = props.rel || "";
189
+ if (rel === "icon" || rel === "apple-touch-icon") return "link:" + rel + (props.sizes != null ? ":sizes=" + props.sizes : "") + (props.type != null ? ":type=" + props.type : "");
190
+ return "link:" + rel + ":" + (props.href || "");
191
+ }
192
+ return unique;
193
+ }
194
+ function resolveHead(groups) {
195
+ const winners = new Map();
196
+ const sorted = groups.slice().sort((a, b) => a.seq - b.seq);
197
+ for (let i = 0; i < sorted.length; i++) {
198
+ const group = sorted[i];
199
+ const byIdentity = new Map();
200
+ for (let j = 0; j < group.tags.length; j++) {
201
+ const t = group.tags[j];
202
+ let list = byIdentity.get(t.identity);
203
+ if (!list) byIdentity.set(t.identity, list = []);
204
+ list.push(t);
205
+ }
206
+ for (const [identity, tags] of byIdentity) {
207
+ if (identity === "title") {
208
+ if (tags.length > 1) console.warn("Multiple <title> tags in one head group; the last one wins.");
209
+ winners.set(identity, {
210
+ seq: group.seq,
211
+ tags: [tags[tags.length - 1]]
212
+ });
213
+ } else {
214
+ winners.set(identity, {
215
+ seq: group.seq,
216
+ tags
217
+ });
218
+ }
219
+ }
220
+ }
221
+ return winners;
222
+ }
223
+
224
+ function joinAssetPath(base, file) {
225
+ if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
226
+ if (typeof base !== "string" || !base) base = "/";
227
+ if (base[base.length - 1] !== "/") base += "/";
228
+ return base + (file[0] === "/" ? file.slice(1) : file);
229
+ }
230
+ function resolveAssets(moduleUrl, manifest) {
231
+ if (!manifest) return null;
232
+ const base = manifest._base;
233
+ const entry = manifest[moduleUrl];
234
+ if (!entry) return null;
235
+ const css = [];
236
+ const js = [];
237
+ const visited = new Set();
238
+ const walk = key => {
239
+ if (visited.has(key)) return;
240
+ visited.add(key);
241
+ const e = manifest[key];
242
+ if (!e) return;
243
+ js.push(joinAssetPath(base, e.file));
244
+ if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
245
+ if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
246
+ };
247
+ walk(moduleUrl);
248
+ return {
249
+ js,
250
+ css
251
+ };
252
+ }
253
+ function registerEntryAssets(manifest) {
254
+ if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
255
+ const ctx = sharedConfig.context;
256
+ if (!ctx?.registerAsset) return;
257
+ for (const key in manifest) {
258
+ if (manifest[key].isEntry) {
259
+ const assets = resolveAssets(key, manifest);
260
+ if (assets) {
261
+ for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
262
+ }
263
+ return;
264
+ }
265
+ }
266
+ }
267
+ function createAssetTracking() {
268
+ const boundaryModules = new Map();
269
+ const boundaryStyles = new Map();
270
+ const emittedAssets = new Set();
271
+ const inlineStyles = new Map();
272
+ let currentBoundaryId = null;
273
+ return {
274
+ boundaryModules,
275
+ boundaryStyles,
276
+ emittedAssets,
277
+ inlineStyles,
278
+ registerInlineStyle(desc) {
279
+ let entry = inlineStyles.get(desc.id);
280
+ if (!entry) {
281
+ entry = {
282
+ id: desc.id,
283
+ content: desc.content || "",
284
+ attrs: desc.attrs,
285
+ emitted: false
286
+ };
287
+ inlineStyles.set(desc.id, entry);
288
+ }
289
+ if (currentBoundaryId) {
290
+ let styles = boundaryStyles.get(currentBoundaryId);
291
+ if (!styles) {
292
+ styles = new Set();
293
+ boundaryStyles.set(currentBoundaryId, styles);
294
+ }
295
+ styles.add(entry);
296
+ }
297
+ return entry;
298
+ },
299
+ get currentBoundaryId() {
300
+ return currentBoundaryId;
301
+ },
302
+ set currentBoundaryId(v) {
303
+ currentBoundaryId = v;
304
+ },
305
+ registerModule(key, entryUrl) {
306
+ const id = currentBoundaryId || "";
307
+ let map = boundaryModules.get(id);
308
+ if (!map) {
309
+ map = {};
310
+ boundaryModules.set(id, map);
311
+ }
312
+ map[key] = entryUrl;
313
+ },
314
+ getBoundaryModules(id) {
315
+ return boundaryModules.get(id) || null;
316
+ },
317
+ getBoundaryStyles(id) {
318
+ return boundaryStyles.get(id) || null;
319
+ }
320
+ };
321
+ }
322
+ function warnUnresolvedModuleAssets(moduleUrl, warned) {
323
+ if (warned.has(moduleUrl)) return;
324
+ warned.add(moduleUrl);
325
+ 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.");
326
+ }
327
+ function guardResolvedAssets(moduleUrl, result, warned) {
328
+ if (result && typeof result.then === "function") {
329
+ return result.then(assets => {
330
+ if (!assets || !assets.js || !assets.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
331
+ return assets;
332
+ });
333
+ }
334
+ if (!result || !result.js || !result.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
335
+ return result;
336
+ }
337
+ function applyAssetTracking(context, tracking, manifest, noScripts) {
338
+ const warned = new Set();
339
+ const guard = noScripts ? resolve => resolve : resolve => moduleUrl => guardResolvedAssets(moduleUrl, resolve(moduleUrl), warned);
340
+ Object.defineProperty(context, "_currentBoundaryId", {
341
+ get() {
342
+ return tracking.currentBoundaryId;
343
+ },
344
+ set(v) {
345
+ tracking.currentBoundaryId = v;
346
+ },
347
+ configurable: true,
348
+ enumerable: true
349
+ });
350
+ context.registerModule = tracking.registerModule;
351
+ context.getBoundaryModules = tracking.getBoundaryModules;
352
+ if (typeof manifest === "function") {
353
+ context.resolveAssets = guard(manifest);
354
+ } else if (manifest && typeof manifest.resolve === "function") {
355
+ context.resolveAssets = guard(key => manifest.resolve(key));
356
+ if (typeof manifest.resolveSync === "function") {
357
+ context.resolveAssetsSync = key => manifest.resolveSync(key);
358
+ }
359
+ } else if (manifest) {
360
+ const resolve = moduleUrl => resolveAssets(moduleUrl, manifest);
361
+ context.resolveAssets = guard(resolve);
362
+ context.resolveAssetsSync = resolve;
363
+ }
364
+ }
365
+ function isCssUrl(url) {
366
+ const q = url.search(/[?#]/);
367
+ return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
368
+ }
369
+ function createHeadRegistry() {
370
+ return {
371
+ pending: [],
372
+ committed: [],
373
+ seq: 0,
374
+ uniq: 0,
375
+ resources: new Set(),
376
+ eagerHtml: "",
377
+ flushed: null,
378
+ shellFlushed: false
379
+ };
380
+ }
381
+ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags) {
382
+ const boundary = context._currentBoundaryId || "";
383
+ if (typeof tags === "function") {
384
+ registry.pending.push({
385
+ boundary,
386
+ list: tags,
387
+ resource: (desc, rel) => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel)
388
+ });
389
+ return;
390
+ }
391
+ if (!Array.isArray(tags)) tags = [tags];
392
+ let replaceable = null;
393
+ for (let i = 0; i < tags.length; i++) {
394
+ const desc = tags[i];
395
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
396
+ console.warn(`useHead: ignoring non-head tag`, desc);
397
+ continue;
398
+ }
399
+ const cls = classifyHeadTag(desc);
400
+ if (cls.resource) {
401
+ emitHeadResource(registry, context, tracking, emitResource, nonce, desc, cls.rel);
402
+ } else {
403
+ (replaceable || (replaceable = [])).push(cls.rel !== undefined ? {
404
+ tag: desc.tag,
405
+ props: desc.props,
406
+ key: desc.key,
407
+ rel: cls.rel
408
+ } : desc);
409
+ }
410
+ }
411
+ if (replaceable) registry.pending.push({
412
+ boundary,
413
+ tags: replaceable
414
+ });
415
+ }
416
+ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel) {
417
+ let props;
418
+ try {
419
+ props = evalHeadProps(desc.props || {}, rel !== undefined ? {
420
+ rel
421
+ } : undefined);
422
+ } catch (err) {
423
+ console.warn(`useHead: error evaluating resource tag props`, err);
424
+ return;
425
+ }
426
+ const identity = resourceIdentity(desc.tag, props);
427
+ if (registry.resources.has(identity)) return;
428
+ registry.resources.add(identity);
429
+ if (desc.tag === "link" && (rel === "stylesheet" || rel === "modulepreload")) {
430
+ let plain = true;
431
+ let gateable = rel === "stylesheet";
432
+ for (const name in props) {
433
+ if (name === "rel" || name === "href") continue;
434
+ plain = false;
435
+ if (!STYLESHEET_FETCH_META.has(name)) gateable = false;
436
+ }
437
+ if (plain && props.href != null) {
438
+ const isCss = isCssUrl(props.href);
439
+ if (rel === "stylesheet" ? isCss : !isCss) {
440
+ context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href);
441
+ return;
442
+ }
443
+ }
444
+ if (gateable && props.href != null) {
445
+ const attrHtml = renderHeadAttrHtml(props);
446
+ const entry = {
447
+ href: props.href,
448
+ attrHtml,
449
+ attrs: headAttrRecord(props)
450
+ };
451
+ if (tracking.currentBoundaryId) {
452
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
453
+ if (!styles) tracking.boundaryStyles.set(tracking.currentBoundaryId, styles = new Set());
454
+ styles.add(entry);
455
+ }
456
+ const markup = `<link${attrHtml}>`;
457
+ if (emitResource) emitResource(markup, entry);else {
458
+ registry.eagerHtml += markup;
459
+ entry.emitted = true;
460
+ }
461
+ return;
462
+ }
463
+ }
464
+ const url = props.href || props.src;
465
+ if (url != null && tracking.emittedAssets.has(url)) return;
466
+ const markup = renderHeadTagMarkup(desc.tag, props, null, nonce);
467
+ if (emitResource) emitResource(markup);else registry.eagerHtml += markup;
468
+ }
469
+ function commitHeadBoundary(registry, boundary, isPendingFragment) {
470
+ const keep = [];
471
+ const groups = [];
472
+ for (let i = 0; i < registry.pending.length; i++) {
473
+ const reg = registry.pending[i];
474
+ const mine = boundary === "" ? !(isPendingFragment && reg.boundary !== "" && isPendingFragment(reg.boundary)) : reg.boundary === boundary;
475
+ if (!mine) {
476
+ keep.push(reg);
477
+ continue;
478
+ }
479
+ let descs = reg.tags;
480
+ if (reg.list) {
481
+ let resolved;
482
+ try {
483
+ resolved = reg.list();
484
+ } catch (err) {
485
+ console.warn(`useHead: error evaluating head group membership`, err);
486
+ continue;
487
+ }
488
+ if (!Array.isArray(resolved)) resolved = [resolved];
489
+ descs = [];
490
+ for (let j = 0; j < resolved.length; j++) {
491
+ const desc = resolved[j];
492
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
493
+ console.warn(`useHead: ignoring non-head tag`, desc);
494
+ continue;
495
+ }
496
+ const cls = classifyHeadTag(desc);
497
+ if (cls.resource) {
498
+ reg.resource(desc, cls.rel);
499
+ } else {
500
+ descs.push(cls.rel !== undefined ? {
501
+ tag: desc.tag,
502
+ props: desc.props,
503
+ key: desc.key,
504
+ rel: cls.rel
505
+ } : desc);
506
+ }
507
+ }
508
+ }
509
+ const tags = [];
510
+ for (let j = 0; j < descs.length; j++) {
511
+ const desc = descs[j];
512
+ let props, key;
513
+ try {
514
+ props = evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
515
+ rel: desc.rel
516
+ } : undefined);
517
+ key = evalHeadValue(desc.key);
518
+ } catch (err) {
519
+ console.warn(`useHead: error evaluating tag props`, err);
520
+ continue;
521
+ }
522
+ const identity = replaceableIdentity(desc.tag, props, key, "u:" + registry.uniq++);
523
+ if ((identity === "base" || identity === "charset") && registry.shellFlushed) {
524
+ console.warn(`useHead: <${desc.tag}> (${identity}) registered after shell flush is ignored`);
525
+ continue;
526
+ }
527
+ tags.push({
528
+ tag: desc.tag,
529
+ props,
530
+ identity
531
+ });
532
+ }
533
+ if (tags.length) groups.push({
534
+ seq: registry.seq++,
535
+ tags
536
+ });
537
+ }
538
+ registry.pending = keep;
539
+ for (let i = 0; i < groups.length; i++) registry.committed.push(groups[i]);
540
+ return groups;
541
+ }
542
+ function adoptHeadBoundary(registry, childKey, parentKey) {
543
+ for (let i = 0; i < registry.pending.length; i++) {
544
+ if (registry.pending[i].boundary === childKey) registry.pending[i].boundary = parentKey;
545
+ }
546
+ }
547
+ function dropHeadBoundary(registry, boundary) {
548
+ registry.pending = registry.pending.filter(reg => reg.boundary !== boundary);
549
+ }
550
+ function headGroupSignature(winner) {
551
+ let sig = "" + winner.seq;
552
+ for (let i = 0; i < winner.tags.length; i++) {
553
+ const t = winner.tags[i];
554
+ sig += "|" + t.tag + JSON.stringify(t.props);
555
+ }
556
+ return sig;
557
+ }
558
+ function renderShellHead(registry, nonce, isPendingFragment) {
559
+ commitHeadBoundary(registry, "", isPendingFragment);
560
+ registry.shellFlushed = true;
561
+ const winners = resolveHead(registry.committed);
562
+ registry.flushed = new Map();
563
+ let prelude = "";
564
+ let links = "";
565
+ let metas = "";
566
+ let others = "";
567
+ let scripts = "";
568
+ for (const [identity, winner] of winners) {
569
+ registry.flushed.set(identity, headGroupSignature(winner));
570
+ for (let i = 0; i < winner.tags.length; i++) {
571
+ const t = winner.tags[i];
572
+ const markup = renderHeadTagMarkup(t.tag, t.props, identity, nonce);
573
+ 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;
574
+ }
575
+ }
576
+ return {
577
+ prelude,
578
+ html: registry.eagerHtml + links + metas + others + scripts
579
+ };
580
+ }
581
+ function flushHeadFragment(registry, boundary) {
582
+ const groups = commitHeadBoundary(registry, boundary);
583
+ if (!groups.length) return null;
584
+ const winners = resolveHead(registry.committed);
585
+ const affected = new Set();
586
+ 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);
587
+ const ops = [];
588
+ for (const identity of affected) {
589
+ const winner = winners.get(identity);
590
+ const sig = headGroupSignature(winner);
591
+ if (registry.flushed.get(identity) === sig) continue;
592
+ const existed = registry.flushed.has(identity);
593
+ registry.flushed.set(identity, sig);
594
+ if (identity === "title") {
595
+ const children = winner.tags[0].props.children;
596
+ ops.push(["t", children == null ? "" : String(children)]);
597
+ continue;
598
+ }
599
+ if (existed) ops.push(["r", identity]);
600
+ for (let i = 0; i < winner.tags.length; i++) {
601
+ const t = winner.tags[i];
602
+ const attrs = {};
603
+ for (const name in t.props) {
604
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
605
+ if (!HEAD_ATTR_NAME.test(name)) {
606
+ console.warn(`useHead: ignoring invalid attribute name "${name}"`);
607
+ continue;
608
+ }
609
+ const v = t.props[name];
610
+ if (v == null || v === false) continue;
611
+ attrs[name] = v === true ? "" : String(v);
612
+ }
613
+ const children = t.props.children;
614
+ ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
615
+ }
616
+ }
617
+ return ops.length ? ops : null;
618
+ }
619
+ function renderHeadAttrHtml(props) {
620
+ let attrs = "";
621
+ for (const name in props) {
622
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
623
+ if (!HEAD_ATTR_NAME.test(name)) {
624
+ console.warn(`useHead: ignoring invalid attribute name "${name}"`);
625
+ continue;
626
+ }
627
+ const v = props[name];
628
+ if (v == null || v === false) continue;
629
+ attrs += v === true ? ` ${name}` : ` ${name}="${escape(String(v), true)}"`;
630
+ }
631
+ return attrs;
632
+ }
633
+ function headAttrRecord(props, skipRelHref) {
634
+ let attrs = null;
635
+ for (const name in props) {
636
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
637
+ if ((name === "rel" || name === "href")) continue;
638
+ if (!HEAD_ATTR_NAME.test(name)) continue;
639
+ const v = props[name];
640
+ if (v == null || v === false) continue;
641
+ (attrs || (attrs = {}))[name] = v === true ? "" : String(v);
642
+ }
643
+ return attrs;
644
+ }
645
+ function renderHeadTagMarkup(tag, props, identity, nonce) {
646
+ let attrs = renderHeadAttrHtml(props);
647
+ if (identity != null) attrs += ` data-dh="${escape(identity, true)}"`;
648
+ if (nonce && (tag === "script" || tag === "style")) attrs += ` nonce="${nonce}"`;
649
+ if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
650
+ let body = props.children == null ? "" : String(props.children);
651
+ if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
652
+ return `<${tag}${attrs}>${body}</${tag}>`;
653
+ }
654
+ 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])}`;
655
+ 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=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)}`;
656
+ function renderToStream(code, options = {}) {
657
+ let {
658
+ nonce,
659
+ onCompleteShell,
660
+ onCompleteAll,
661
+ renderId = "",
662
+ noScripts,
663
+ manifest,
664
+ onHead
665
+ } = options;
666
+ let dispose;
667
+ let dead = false;
668
+ const abandon = () => {
669
+ if (dead) return;
670
+ dead = true;
671
+ completed = true;
672
+ buffer = {
673
+ write() {}
674
+ };
675
+ writable = {
676
+ end() {}
677
+ };
678
+ if (dispose) {
679
+ const d = dispose;
680
+ dispose = () => {};
681
+ d();
682
+ }
683
+ };
684
+ const guardSink = w => ({
685
+ write(payload) {
686
+ if (dead) return;
687
+ try {
688
+ w.write(payload);
689
+ } catch (_) {
690
+ abandon();
691
+ }
692
+ },
693
+ end() {
694
+ if (dead) return;
695
+ try {
696
+ w.end();
697
+ } catch (_) {
698
+ abandon();
699
+ }
700
+ }
701
+ });
702
+ const blockingPromises = new Set();
703
+ let headerEmitted = false;
704
+ const pushTask = task => {
705
+ if (noScripts) return;
706
+ if (!headerEmitted) {
707
+ headerEmitted = true;
708
+ tasks += getLocalHeaderScript(renderId);
709
+ }
710
+ tasks += task + ";";
711
+ if (!timer && firstFlushed) {
712
+ timer = true;
713
+ queue(() => queue(writeTasks));
714
+ }
715
+ };
716
+ const onDone = () => {
717
+ writeTasks();
718
+ doShell();
719
+ onCompleteAll && onCompleteAll({
720
+ write(v) {
721
+ !completed && buffer.write(v);
722
+ }
723
+ });
724
+ writable && writable.end();
725
+ completed = true;
726
+ if (firstFlushed) dispose();
727
+ };
728
+ const sink = {
729
+ data(payload) {
730
+ pushTask(payload);
731
+ },
732
+ fragment(key, value, meta) {
733
+ const deferActivation = !!meta.revealGroup;
734
+ const styles = meta.styles;
735
+ for (let i = 0; i < styles.inline.length; i++) {
736
+ buffer.write(renderInlineStyle(styles.inline[i], nonce));
737
+ }
738
+ if (styles.links.length) {
739
+ emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
740
+ writeTasks();
741
+ for (const entry of styles.links) {
742
+ buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}" onload="$dfc('${key}')" onerror="$dfc('${key}')">` : `<link${entry.attrHtml} onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
743
+ }
744
+ buffer.write(`<template id="${key}">${value}</template>`);
745
+ } else {
746
+ buffer.write(`<template id="${key}">${value}</template>`);
747
+ if (!deferActivation) {
748
+ emitTask(`$df("${key}")`);
749
+ }
750
+ }
751
+ },
752
+ reveal(keys, meta) {
753
+ emitTask(`${meta.fallback ? "$dflj" : "$dfj"}(${JSON.stringify(keys)})`);
754
+ },
755
+ asset(type, value) {
756
+ if (type === "module") {
757
+ buffer.write(`<link rel="modulepreload" href="${value}">`);
758
+ } else if (type === "inline-style") {
759
+ buffer.write(renderInlineStyle(value, nonce));
760
+ } else if (type === "head-tag") {
761
+ buffer.write(value);
762
+ }
763
+ },
764
+ shell(shellHtml, meta) {
765
+ buffer.write(assembleDocument(shellHtml, meta.assets, meta.preloads, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
766
+ },
767
+ ...options.sink
768
+ };
769
+ const serializer = (options.serializer || createHydrationSerializer)({
770
+ scopeId: options.renderId,
771
+ plugins: options.plugins,
772
+ onData: payload => sink.data(payload),
773
+ onDone,
774
+ onError: options.onError
775
+ });
776
+ let rootAssetsSerialized = false;
777
+ const serializeRootAssets = () => {
778
+ if (rootAssetsSerialized) return;
779
+ rootAssetsSerialized = true;
780
+ serializeFragmentAssets("", tracking.boundaryModules, context);
781
+ };
782
+ const flushEnd = () => {
783
+ if (!registry.size) {
784
+ serializeRootAssets();
785
+ queue(() => queue(() => serializer.flush()));
786
+ }
787
+ };
788
+ const registry = new Map();
789
+ const writeTasks = () => {
790
+ if (tasks.length && !completed && firstFlushed) {
791
+ buffer.write(`<script${nonce ? ` nonce="${nonce}"` : ""}>${tasks}</script>`);
792
+ tasks = "";
793
+ }
794
+ timer = null;
795
+ };
796
+ let context;
797
+ let writable;
798
+ let tmp = "";
799
+ let tasks = "";
800
+ let firstFlushed = false;
801
+ let completed = false;
802
+ let shellCompleted = false;
803
+ let scriptFlushed = false;
804
+ let headStyles;
805
+ const revealGroups = new Map();
806
+ let timer = null;
807
+ const emitTask = task => {
808
+ pushTask(`${task}${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
809
+ scriptFlushed = true;
810
+ };
811
+ function resolveRevealKeys(groupOrKeys, release, consume) {
812
+ if (Array.isArray(groupOrKeys)) return groupOrKeys.slice();
813
+ let group = revealGroups.get(groupOrKeys);
814
+ if (!group) {
815
+ if (!release) return;
816
+ group = {
817
+ order: [],
818
+ keys: new Set(),
819
+ released: true
820
+ };
821
+ revealGroups.set(groupOrKeys, group);
822
+ } else if (release) group.released = true;
823
+ if (!group.order.length) return;
824
+ const keys = group.order.slice();
825
+ if (consume) revealGroups.delete(groupOrKeys);
826
+ return keys;
827
+ }
828
+ let rootHoles = null;
829
+ let nextHoleId = 0;
830
+ let buffer = {
831
+ write(payload) {
832
+ tmp += payload;
833
+ }
834
+ };
835
+ const tracking = createAssetTracking();
836
+ const headRegistry = createHeadRegistry();
837
+ let headScriptFlushed = false;
838
+ const emitHeadOps = (key, ops) => {
839
+ const payload = JSON.stringify(ops).replace(/</g, "\\u003C");
840
+ emitTask(`${!headScriptFlushed ? HEAD_SCRIPT : ""}(_$HY.hp=_$HY.hp||{})[${JSON.stringify(key)}]=${payload}`);
841
+ headScriptFlushed = true;
842
+ };
843
+ sharedConfig.context = context = {
844
+ async: true,
845
+ assets: [],
846
+ nonce,
847
+ registerHeadTags(tags) {
848
+ registerHeadTags(headRegistry, context, tracking,
849
+ (markup, gateEntry) => {
850
+ if (!firstFlushed) {
851
+ headRegistry.eagerHtml += markup;
852
+ if (gateEntry) gateEntry.emitted = true;
853
+ } else if (!gateEntry || !tracking.currentBoundaryId) {
854
+ sink.asset("head-tag", markup);
855
+ }
856
+ }, nonce, tags);
857
+ },
858
+ registerAsset(type, value) {
859
+ if (type === "inline-style") {
860
+ const entry = tracking.registerInlineStyle(value);
861
+ if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
862
+ entry.emitted = true;
863
+ sink.asset("inline-style", entry);
864
+ }
865
+ return;
866
+ }
867
+ if (tracking.currentBoundaryId && type === "style") {
868
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
869
+ if (!styles) {
870
+ styles = new Set();
871
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
872
+ }
873
+ styles.add(value);
874
+ }
875
+ if (!tracking.emittedAssets.has(value)) {
876
+ tracking.emittedAssets.add(value);
877
+ if (firstFlushed) sink.asset(type, value);
878
+ }
879
+ },
880
+ block(p) {
881
+ if (!firstFlushed) blockingPromises.add(p);
882
+ },
883
+ replace(id, payloadFn) {
884
+ if (firstFlushed) return;
885
+ const placeholder = `<!--!$${id}-->`;
886
+ const first = html.indexOf(placeholder);
887
+ if (first === -1) return;
888
+ const last = html.indexOf(`<!--!$/${id}-->`, first + placeholder.length);
889
+ html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
890
+ },
891
+ serialize(id, p, deferStream) {
892
+ if (sharedConfig.context.noHydrate) return;
893
+ if (!firstFlushed && deferStream && typeof p === "object" && "then" in p) {
894
+ blockingPromises.add(p);
895
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
896
+ } else serializer.write(id, p);
897
+ },
898
+ escape: escape,
899
+ resolve: resolveSSRNode,
900
+ ssr: ssr,
901
+ registerFragment(key, options) {
902
+ const revealGroup = options && options.revealGroup;
903
+ if (revealGroup) {
904
+ let group = revealGroups.get(revealGroup);
905
+ if (!group) {
906
+ group = {
907
+ order: [],
908
+ keys: new Set(),
909
+ released: false
910
+ };
911
+ revealGroups.set(revealGroup, group);
912
+ }
913
+ if (!group.keys.has(key)) {
914
+ group.keys.add(key);
915
+ group.order.push(key);
916
+ }
917
+ if (group.released) {
918
+ throw new Error("registerFragment() for reveal group '" + revealGroup + "' was called after revealFragments(). Ensure template payload is emitted before grouped reveal.");
919
+ }
920
+ }
921
+ if (!registry.has(key)) {
922
+ let resolve, reject;
923
+ const p = new Promise((r, rej) => (resolve = r, reject = rej));
924
+ registry.set(key, {
925
+ resolve: err => queue(() => queue(() => {
926
+ err ? reject(err) : resolve(true);
927
+ queue(flushEnd);
928
+ }))
929
+ });
930
+ serializer.write(key + "_fr", p);
931
+ }
932
+ return (value, error) => {
933
+ if (registry.has(key)) {
934
+ const item = registry.get(key);
935
+ registry.delete(key);
936
+ if (item.children) {
937
+ for (const k in item.children) {
938
+ value = replacePlaceholder(value, k, item.children[k]);
939
+ }
940
+ }
941
+ const parentKey = waitForFragments(registry, key);
942
+ if (parentKey) {
943
+ const parent = registry.get(parentKey);
944
+ parent.children ||= {};
945
+ parent.children[key] = value !== undefined ? value : "";
946
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
947
+ propagateBoundaryStyles(key, parentKey, tracking);
948
+ adoptHeadBoundary(headRegistry, key, parentKey);
949
+ item.resolve();
950
+ return;
951
+ }
952
+ if (!completed) {
953
+ if (error) dropHeadBoundary(headRegistry, key);
954
+ if (!firstFlushed) {
955
+ queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
956
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
957
+ item.resolve(error);
958
+ } else {
959
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
960
+ const styles = collectStreamStyles(key, tracking, headStyles);
961
+ const headOps = error ? null : flushHeadFragment(headRegistry, key);
962
+ if (headOps) emitHeadOps(key, headOps);
963
+ sink.fragment(key, value !== undefined ? value : " ", {
964
+ styles,
965
+ revealGroup,
966
+ error
967
+ });
968
+ item.resolve(error);
969
+ }
970
+ }
971
+ }
972
+ return firstFlushed;
973
+ };
974
+ },
975
+ revealFragments(groupOrKeys) {
976
+ const keys = resolveRevealKeys(groupOrKeys, true, true);
977
+ if (!keys) return;
978
+ sink.reveal(keys, {
979
+ fallback: false
980
+ });
981
+ },
982
+ revealFallbacks(groupOrKeys) {
983
+ const keys = resolveRevealKeys(groupOrKeys, false, false);
984
+ if (!keys) return;
985
+ sink.reveal(keys, {
986
+ fallback: true
987
+ });
988
+ }
989
+ };
990
+ applyAssetTracking(context, tracking, manifest, noScripts);
991
+ registerEntryAssets(manifest);
992
+ let html = createRoot(d => {
993
+ dispose = d;
994
+ const res = resolveSSRNode(escape(code()));
995
+ if (!res.h.length) return res.t[0];
996
+ rootHoles = [];
997
+ let out = res.t[0];
998
+ for (let i = 0; i < res.h.length; i++) {
999
+ const id = nextHoleId++;
1000
+ rootHoles.push({
1001
+ id,
1002
+ fn: res.h[i]
1003
+ });
1004
+ out += `<!--rh${id}-->` + res.t[i + 1];
1005
+ }
1006
+ for (const p of res.p) blockingPromises.add(p);
1007
+ return out;
1008
+ }, {
1009
+ id: renderId
1010
+ });
1011
+ function resolveRootHoles() {
1012
+ if (!rootHoles) return true;
1013
+ const pending = [];
1014
+ for (const {
1015
+ id,
1016
+ fn
1017
+ } of rootHoles) {
1018
+ const marker = `<!--rh${id}-->`;
1019
+ const res = resolveSSRNode(fn);
1020
+ if (!res.h.length) {
1021
+ html = html.replace(marker, res.t[0]);
1022
+ } else {
1023
+ let out = res.t[0];
1024
+ for (let j = 0; j < res.h.length; j++) {
1025
+ const newId = nextHoleId++;
1026
+ pending.push({
1027
+ id: newId,
1028
+ fn: res.h[j]
1029
+ });
1030
+ out += `<!--rh${newId}-->` + res.t[j + 1];
1031
+ }
1032
+ html = html.replace(marker, out);
1033
+ for (const p of res.p) blockingPromises.add(p);
1034
+ }
1035
+ }
1036
+ if (pending.length) {
1037
+ rootHoles = pending;
1038
+ return false;
1039
+ }
1040
+ rootHoles = null;
1041
+ return true;
1042
+ }
1043
+ function doShell() {
1044
+ if (shellCompleted) return;
1045
+ sharedConfig.context = context;
1046
+ if (!resolveRootHoles()) return;
1047
+ const assetsHtml = resolveAssetsHtml(context.assets);
1048
+ headStyles = new Set();
1049
+ for (const url of tracking.emittedAssets) {
1050
+ if (isCssUrl(url)) headStyles.add(url);
1051
+ }
1052
+ serializeRootAssets();
1053
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k));
1054
+ sink.shell(html, {
1055
+ assets: assetsHtml,
1056
+ preloads: tracking.emittedAssets,
1057
+ inlineStyles: tracking.inlineStyles,
1058
+ tasks,
1059
+ head
1060
+ });
1061
+ tasks = "";
1062
+ onCompleteShell && onCompleteShell({
1063
+ write(v) {
1064
+ !completed && buffer.write(v);
1065
+ }
1066
+ });
1067
+ shellCompleted = true;
1068
+ }
1069
+ const MIN_DRAIN_TURNS = 8;
1070
+ let lastBlockingSize = -1;
1071
+ let lastRegistrySize = -1;
1072
+ let drainTurn = 0;
1073
+ const scheduleFlush = fn => {
1074
+ const attempt = () => {
1075
+ if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1076
+ if (registry.size !== lastRegistrySize) drainTurn = 0;
1077
+ lastRegistrySize = registry.size;
1078
+ queue(attempt);
1079
+ return;
1080
+ }
1081
+ fn();
1082
+ };
1083
+ const progressed = blockingPromises.size !== lastBlockingSize;
1084
+ lastBlockingSize = blockingPromises.size;
1085
+ lastRegistrySize = -1;
1086
+ drainTurn = 0;
1087
+ progressed ? queue(attempt) : setTimeout(attempt);
1088
+ };
1089
+ let cachedReadable;
1090
+ let consumer;
1091
+ const claimConsumer = name => {
1092
+ if (consumer && consumer !== name) {
1093
+ throw new Error(`renderToStream result was already consumed via \`${consumer}\`; cannot also consume it via \`${name}\`. Use exactly one of \`pipe\`, \`pipeTo\`, or \`readable\`.`);
1094
+ }
1095
+ consumer = name;
1096
+ };
1097
+ const pipeToImpl = w => {
1098
+ let resolve;
1099
+ const p = new Promise(r => resolve = r);
1100
+ function flush() {
1101
+ allSettled(blockingPromises).then(() => {
1102
+ scheduleFlush(() => {
1103
+ if (dead) return resolve();
1104
+ doShell();
1105
+ if (!shellCompleted) return flush();
1106
+ const encoder = new TextEncoder();
1107
+ const writer = w.getWriter();
1108
+ let pendingWrites = Promise.resolve();
1109
+ let ended = false;
1110
+ const failed = () => {
1111
+ if (!ended) {
1112
+ abandon();
1113
+ resolve();
1114
+ }
1115
+ };
1116
+ writer.closed && writer.closed.catch(failed);
1117
+ writable = {
1118
+ end() {
1119
+ pendingWrites.then(() => {
1120
+ ended = true;
1121
+ writer.releaseLock();
1122
+ w.close().catch(() => {});
1123
+ resolve();
1124
+ });
1125
+ }
1126
+ };
1127
+ buffer = {
1128
+ write(payload) {
1129
+ pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
1130
+ }
1131
+ };
1132
+ buffer.write(tmp);
1133
+ firstFlushed = true;
1134
+ if (completed) {
1135
+ dispose();
1136
+ writable.end();
1137
+ } else flushEnd();
1138
+ });
1139
+ });
1140
+ }
1141
+ flush();
1142
+ return p;
1143
+ };
1144
+ return {
1145
+ then(fn) {
1146
+ function complete() {
1147
+ dispose();
1148
+ fn(tmp);
1149
+ }
1150
+ if (onCompleteAll) {
1151
+ let ogComplete = onCompleteAll;
1152
+ onCompleteAll = options => {
1153
+ ogComplete(options);
1154
+ complete();
1155
+ };
1156
+ } else onCompleteAll = complete;
1157
+ function flush() {
1158
+ allSettled(blockingPromises).then(() => {
1159
+ scheduleFlush(() => {
1160
+ if (!resolveRootHoles()) return flush();
1161
+ queue(flushEnd);
1162
+ });
1163
+ });
1164
+ }
1165
+ flush();
1166
+ },
1167
+ pipe(w) {
1168
+ claimConsumer("pipe");
1169
+ function flush() {
1170
+ allSettled(blockingPromises).then(() => {
1171
+ scheduleFlush(() => {
1172
+ if (dead) return;
1173
+ doShell();
1174
+ if (!shellCompleted) return flush();
1175
+ buffer = writable = guardSink(w);
1176
+ buffer.write(tmp);
1177
+ firstFlushed = true;
1178
+ if (completed) {
1179
+ dispose();
1180
+ writable.end();
1181
+ } else flushEnd();
1182
+ });
1183
+ });
1184
+ }
1185
+ flush();
1186
+ },
1187
+ pipeTo(w) {
1188
+ claimConsumer("pipeTo");
1189
+ return pipeToImpl(w);
1190
+ },
1191
+ get readable() {
1192
+ claimConsumer("readable");
1193
+ if (!cachedReadable) {
1194
+ const t = new TransformStream();
1195
+ pipeToImpl(t.writable);
1196
+ cachedReadable = t.readable;
1197
+ }
1198
+ return cachedReadable;
1199
+ }
1200
+ };
1201
+ }
1202
+ function buildAsyncWrap(err, node) {
1203
+ const p = ssrHandleError(err);
1204
+ if (!p) return null;
1205
+ const owner = getOwner();
1206
+ return {
1207
+ fn: owner ? () => runWithOwner(owner, node) : node,
1208
+ p
1209
+ };
1210
+ }
1211
+ function ssrFirstGroupHit(hole) {
1212
+ try {
1213
+ return hole();
1214
+ } catch (err) {
1215
+ return buildAsyncWrap(err, hole);
1216
+ }
1217
+ }
1218
+ function tryResolveFunctionHole(hole) {
1219
+ let value;
1220
+ try {
1221
+ value = hole();
1222
+ } catch (err) {
1223
+ return buildAsyncWrap(err, hole) || "";
1224
+ }
1225
+ const t = typeof value;
1226
+ if (t === "string") return value;
1227
+ if (t === "number") return "" + value;
1228
+ if (value == null || t === "boolean") return "";
1229
+ return tryResolveString(value);
1230
+ }
1231
+ function mergeTemplateInto(result, node) {
1232
+ result.t[result.t.length - 1] += node.t[0];
1233
+ if (node.t.length > 1) {
1234
+ result.t.push(...node.t.slice(1));
1235
+ result.h.push(...node.h);
1236
+ result.p.push(...node.p);
1237
+ }
1238
+ }
1239
+ function appendResolvedNode(result, node) {
1240
+ if (node.fn !== undefined) {
1241
+ result.h.push(node.fn);
1242
+ result.p.push(node.p);
1243
+ result.t.push("");
1244
+ } else if (node.merge !== undefined) mergeTemplateInto(result, node.merge);else resolveSSRNode(node.bail, result);
1245
+ }
1246
+ let _lastGroupFn = null;
1247
+ let _lastGroupArr = null;
1248
+ let _lastGroupErr = null;
1249
+ function ssrGroupSlot(fn, idx) {
1250
+ return () => {
1251
+ if (idx > 0 && _lastGroupFn === fn) {
1252
+ if (_lastGroupArr !== null) return _lastGroupArr[idx];
1253
+ throw _lastGroupErr;
1254
+ }
1255
+ _lastGroupFn = fn;
1256
+ _lastGroupArr = null;
1257
+ _lastGroupErr = null;
1258
+ try {
1259
+ _lastGroupArr = fn();
1260
+ return _lastGroupArr[idx];
1261
+ } catch (err) {
1262
+ _lastGroupErr = err;
1263
+ throw err;
1264
+ }
1265
+ };
1266
+ }
1267
+ function ssr(t) {
1268
+ const len = arguments.length;
1269
+ if (len === 1) return {
1270
+ t
1271
+ };
1272
+ let s = t[0];
1273
+ let result = null;
1274
+ let lastGroup = null;
1275
+ let lastGroupVal = null;
1276
+ let lastGroupIdx = 0;
1277
+ for (let i = 1; i < len; i++) {
1278
+ const hole = arguments[i];
1279
+ const ht = typeof hole;
1280
+ if (ht === "string") {
1281
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
1282
+ } else if (ht === "number") {
1283
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
1284
+ } else if (hole == null || ht === "boolean") ; else if (ht === "function" && hole.$g) {
1285
+ let value;
1286
+ let hasValue = false;
1287
+ if (lastGroup !== hole) {
1288
+ const r = ssrFirstGroupHit(hole);
1289
+ if (r !== null) {
1290
+ lastGroup = hole;
1291
+ lastGroupVal = r;
1292
+ lastGroupIdx = 0;
1293
+ if (!Array.isArray(r) && result === null) {
1294
+ result = {
1295
+ t: [s],
1296
+ h: [],
1297
+ p: []
1298
+ };
1299
+ s = "";
1300
+ }
1301
+ }
1302
+ }
1303
+ if (lastGroup === hole) {
1304
+ if (Array.isArray(lastGroupVal)) {
1305
+ value = lastGroupVal[lastGroupIdx++];
1306
+ hasValue = true;
1307
+ } else {
1308
+ result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
1309
+ result.p.push(lastGroupVal.p);
1310
+ result.t.push("");
1311
+ }
1312
+ }
1313
+ if (hasValue) {
1314
+ const vt = typeof value;
1315
+ if (vt === "string" || vt === "number") {
1316
+ if (result === null) s += value;else result.t[result.t.length - 1] += value;
1317
+ } else if (value == null || vt === "boolean") ; else if (result !== null) {
1318
+ resolveSSRNode(value, result);
1319
+ } else {
1320
+ const rs = tryResolveString(value);
1321
+ if (typeof rs === "string") {
1322
+ s += rs;
1323
+ } else {
1324
+ result = {
1325
+ t: [s],
1326
+ h: [],
1327
+ p: []
1328
+ };
1329
+ s = "";
1330
+ if (rs.merge !== undefined) mergeTemplateInto(result, rs.merge);else resolveSSRNode(rs.bail, result);
1331
+ }
1332
+ }
1333
+ }
1334
+ } else if (result !== null) {
1335
+ resolveSSRNode(hole, result);
1336
+ } else if (ht === "function") {
1337
+ const r = tryResolveFunctionHole(hole);
1338
+ if (typeof r === "string") s += r;else {
1339
+ result = {
1340
+ t: [s],
1341
+ h: [],
1342
+ p: []
1343
+ };
1344
+ s = "";
1345
+ appendResolvedNode(result, r);
1346
+ }
1347
+ } else {
1348
+ const r = tryResolveString(hole);
1349
+ if (typeof r === "string") {
1350
+ s += r;
1351
+ } else {
1352
+ result = {
1353
+ t: [s],
1354
+ h: [],
1355
+ p: []
1356
+ };
1357
+ s = "";
1358
+ appendResolvedNode(result, r);
1359
+ }
1360
+ }
1361
+ const next = t[i];
1362
+ if (result === null) s += next;else result.t[result.t.length - 1] += next;
1363
+ }
1364
+ if (result === null) return {
1365
+ t: s
1366
+ };
1367
+ return result;
1368
+ }
1369
+ function escape(s, attr) {
1370
+ const t = typeof s;
1371
+ if (t !== "string") {
1372
+ if (!attr && Array.isArray(s)) {
1373
+ const joined = tryJoinPlainSSRArray(s);
1374
+ if (joined !== undefined) return joined;
1375
+ s = s.slice();
1376
+ for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
1377
+ return s;
1378
+ }
1379
+ if (attr) {
1380
+ if (s == null || t === "boolean" || t === "number") return s;
1381
+ return escape(String(s), attr);
1382
+ }
1383
+ return s;
1384
+ }
1385
+ const i = s.search(attr ? ESCAPE_ATTR : ESCAPE_CONTENT);
1386
+ if (i < 0) return s;
1387
+ return escapeSlow(s, attr, i);
1388
+ }
1389
+ const ESCAPE_CONTENT = /[&<]/;
1390
+ const ESCAPE_ATTR = /[&"]/;
1391
+ function escapeSlow(s, attr, start) {
1392
+ const delim = attr ? '"' : "<";
1393
+ const delimCode = attr ? 34 : 60;
1394
+ const escDelim = attr ? "&quot;" : "&lt;";
1395
+ const c0 = s.charCodeAt(start);
1396
+ let iDelim = c0 === delimCode ? start : s.indexOf(delim, start);
1397
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
1398
+ let left = 0,
1399
+ out = "";
1400
+ while (iDelim >= 0 && iAmp >= 0) {
1401
+ if (iDelim < iAmp) {
1402
+ if (left < iDelim) out += s.substring(left, iDelim);
1403
+ out += escDelim;
1404
+ left = iDelim + 1;
1405
+ iDelim = s.indexOf(delim, left);
1406
+ } else {
1407
+ if (left < iAmp) out += s.substring(left, iAmp);
1408
+ out += "&amp;";
1409
+ left = iAmp + 1;
1410
+ iAmp = s.indexOf("&", left);
1411
+ }
1412
+ }
1413
+ if (iDelim >= 0) {
1414
+ do {
1415
+ if (left < iDelim) out += s.substring(left, iDelim);
1416
+ out += escDelim;
1417
+ left = iDelim + 1;
1418
+ iDelim = s.indexOf(delim, left);
1419
+ } while (iDelim >= 0);
1420
+ } else while (iAmp >= 0) {
1421
+ if (left < iAmp) out += s.substring(left, iAmp);
1422
+ out += "&amp;";
1423
+ left = iAmp + 1;
1424
+ iAmp = s.indexOf("&", left);
1425
+ }
1426
+ return left < s.length ? out + s.substring(left) : out;
1427
+ }
1428
+ function tryJoinPlainSSRArray(nodes) {
1429
+ if (nodes.length === 0) return undefined;
1430
+ let out = "";
1431
+ for (let i = 0, len = nodes.length; i < len; i++) {
1432
+ const node = nodes[i];
1433
+ if (node == null || typeof node !== "object" || node.h || typeof node.t !== "string") {
1434
+ return undefined;
1435
+ }
1436
+ out += node.t;
1437
+ }
1438
+ return out;
1439
+ }
1440
+ function queue(fn) {
1441
+ return Promise.resolve().then(fn);
1442
+ }
1443
+ function allSettled(promises) {
1444
+ let size = promises.size;
1445
+ return Promise.allSettled(promises).then(() => {
1446
+ if (promises.size !== size) return allSettled(promises);
1447
+ return;
1448
+ });
1449
+ }
1450
+ function resolveAssetsHtml(assets) {
1451
+ if (!assets || !assets.length) return "";
1452
+ let out = "";
1453
+ for (let i = 0, len = assets.length; i < len; i++) out += assets[i]();
1454
+ return out;
1455
+ }
1456
+ function assembleDocument(html, assetsHtml, emittedAssets, inlineStyles, scripts, nonce, headTags, onHead) {
1457
+ const scriptTag = scripts ? `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>` : "";
1458
+ const headTagsHtml = headTags ? headTags.html : "";
1459
+ const headPrelude = headTags ? headTags.prelude : "";
1460
+ if (!onHead && !assetsHtml && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !(inlineStyles && inlineStyles.size)) {
1461
+ if (!scriptTag) return html;
1462
+ const xs = html.indexOf("<!--xs-->");
1463
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
1464
+ }
1465
+ if (headPrelude) {
1466
+ const open = html.match(/<head(?:\s[^>]*)?>/);
1467
+ if (open) {
1468
+ const at = open.index + open[0].length;
1469
+ html = html.slice(0, at) + headPrelude + html.slice(at);
1470
+ }
1471
+ }
1472
+ const headIdx = html.indexOf("</head>");
1473
+ if (headIdx === -1) {
1474
+ if (onHead) {
1475
+ onHead(headPrelude + headTagsHtml + (assetsHtml || "") + renderHeadAssets(emittedAssets, inlineStyles, nonce));
1476
+ }
1477
+ if (!scriptTag) return html;
1478
+ const xs = html.indexOf("<!--xs-->");
1479
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
1480
+ }
1481
+ const head = headTagsHtml + (assetsHtml || "") + renderHeadAssets(emittedAssets, inlineStyles, nonce);
1482
+ if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
1483
+ const xsIdx = html.indexOf("<!--xs-->");
1484
+ if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
1485
+ 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);
1486
+ }
1487
+ function renderHeadAssets(emittedAssets, inlineStyles, nonce) {
1488
+ let head = "";
1489
+ if (emittedAssets && emittedAssets.size) {
1490
+ for (const url of emittedAssets) {
1491
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}">` : `<link rel="modulepreload" href="${url}">`;
1492
+ }
1493
+ }
1494
+ if (inlineStyles && inlineStyles.size) {
1495
+ for (const entry of inlineStyles.values()) {
1496
+ if (entry.emitted) continue;
1497
+ entry.emitted = true;
1498
+ head += renderInlineStyle(entry, nonce);
1499
+ }
1500
+ }
1501
+ return head;
1502
+ }
1503
+ function serializeFragmentAssets(key, boundaryModules, context) {
1504
+ const map = boundaryModules.get(key);
1505
+ if (!map || !Object.keys(map).length) return;
1506
+ context.serialize(key + "_assets", map);
1507
+ }
1508
+ function propagateBoundaryStyles(childKey, parentKey, tracking) {
1509
+ const childStyles = tracking.getBoundaryStyles(childKey);
1510
+ if (!childStyles) return;
1511
+ let parentStyles = tracking.boundaryStyles.get(parentKey);
1512
+ if (!parentStyles) {
1513
+ parentStyles = new Set();
1514
+ tracking.boundaryStyles.set(parentKey, parentStyles);
1515
+ }
1516
+ for (const url of childStyles) {
1517
+ parentStyles.add(url);
1518
+ }
1519
+ }
1520
+ function collectStreamStyles(key, tracking, headStyles) {
1521
+ const styles = tracking.getBoundaryStyles(key);
1522
+ const links = [];
1523
+ const inline = [];
1524
+ if (!styles) return {
1525
+ links,
1526
+ inline
1527
+ };
1528
+ for (const entry of styles) {
1529
+ if (typeof entry === "string") {
1530
+ if (!headStyles || !headStyles.has(entry)) links.push(entry);
1531
+ } else if (entry.emitted) {
1532
+ continue;
1533
+ } else if (entry.attrHtml !== undefined) {
1534
+ entry.emitted = true;
1535
+ links.push(entry);
1536
+ } else {
1537
+ entry.emitted = true;
1538
+ inline.push(entry);
1539
+ }
1540
+ }
1541
+ return {
1542
+ links,
1543
+ inline
1544
+ };
1545
+ }
1546
+ function escapeStyleContent(content) {
1547
+ return content.replace(/<\/(style)/gi, "<\\/$1");
1548
+ }
1549
+ function renderInlineStyle(entry, nonce) {
1550
+ let attrs = "";
1551
+ if (entry.attrs) {
1552
+ for (const name in entry.attrs) {
1553
+ attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
1554
+ }
1555
+ }
1556
+ return `<style${nonce ? ` nonce="${nonce}"` : ""} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
1557
+ }
1558
+ function waitForFragments(registry, key) {
1559
+ for (const k of [...registry.keys()].reverse()) {
1560
+ if (key.startsWith(k)) return k;
1561
+ }
1562
+ return false;
1563
+ }
1564
+ function replacePlaceholder(html, key, value) {
1565
+ const marker = `<template id="pl-${key}">`;
1566
+ const close = `<!--pl-${key}-->`;
1567
+ const first = html.indexOf(marker);
1568
+ if (first === -1) return html;
1569
+ const last = html.indexOf(close, first + marker.length);
1570
+ return html.slice(0, first) + value + html.slice(last + close.length);
1571
+ }
1572
+ function tryResolveString(node) {
1573
+ const t = typeof node;
1574
+ if (t === "string") return node;
1575
+ if (t === "number") return "" + node;
1576
+ if (node == null || t === "boolean") return "";
1577
+ if (t === "object") {
1578
+ if (Array.isArray(node)) {
1579
+ const joined = tryJoinPlainSSRArray(node);
1580
+ if (joined !== undefined) return joined;
1581
+ let s = "";
1582
+ let prevNonObj = false;
1583
+ for (let i = 0, len = node.length; i < len; i++) {
1584
+ const item = node[i];
1585
+ const itemNonObj = item !== null && typeof item !== "object";
1586
+ if (prevNonObj && itemNonObj) s += "<!--!$-->";
1587
+ prevNonObj = itemNonObj;
1588
+ const r = tryResolveString(item);
1589
+ if (typeof r !== "string") return {
1590
+ bail: node
1591
+ };
1592
+ s += r;
1593
+ }
1594
+ return s;
1595
+ }
1596
+ if (node.h && node.h.length > 0) return {
1597
+ merge: node
1598
+ };
1599
+ if (node.t === undefined) {
1600
+ console.warn(`Unrecognized value. Skipped inserting`, node);
1601
+ return "";
1602
+ }
1603
+ return Array.isArray(node.t) ? node.t[0] : node.t;
1604
+ }
1605
+ if (t === "function") {
1606
+ let v;
1607
+ try {
1608
+ v = node();
1609
+ } catch (err) {
1610
+ return buildAsyncWrap(err, node) || "";
1611
+ }
1612
+ return tryResolveString(v);
1613
+ }
1614
+ return "";
1615
+ }
1616
+ function resolveSSRNode(node, result = {
1617
+ t: [""],
1618
+ h: [],
1619
+ p: []
1620
+ }, top) {
1621
+ const t = typeof node;
1622
+ if (t === "string" || t === "number") {
1623
+ result.t[result.t.length - 1] += node;
1624
+ } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
1625
+ let prevNonObj = false;
1626
+ for (let i = 0, len = node.length; i < len; i++) {
1627
+ const item = node[i];
1628
+ const itemNonObj = item !== null && typeof item !== "object";
1629
+ if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
1630
+ prevNonObj = itemNonObj;
1631
+ resolveSSRNode(item, result);
1632
+ }
1633
+ } else if (t === "object") {
1634
+ if (node.h) {
1635
+ result.t[result.t.length - 1] += node.t[0];
1636
+ if (node.t.length > 1) {
1637
+ result.t.push(...node.t.slice(1));
1638
+ result.h.push(...node.h);
1639
+ result.p.push(...node.p);
1640
+ }
1641
+ } else if (node.t !== undefined) {
1642
+ result.t[result.t.length - 1] += node.t;
1643
+ } else console.warn(`Unrecognized value. Skipped inserting`, node);
1644
+ } else if (t === "function") {
1645
+ try {
1646
+ resolveSSRNode(node(), result);
1647
+ } catch (err) {
1648
+ const wrap = buildAsyncWrap(err, node);
1649
+ if (wrap) {
1650
+ result.h.push(wrap.fn);
1651
+ result.p.push(wrap.p);
1652
+ result.t.push("");
1653
+ }
1654
+ }
1655
+ }
1656
+ return result;
1657
+ }
1658
+ function resolveSSRSync(node) {
1659
+ const res = resolveSSRNode(node);
1660
+ if (!res.h.length) return res.t[0];
1661
+ throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
1662
+ }
1663
+
1664
+ function frameAddress(id, args) {
1665
+ return args && args.length ? id + ":" + hashArguments(args) : id;
1666
+ }
1667
+ function hashArguments(args) {
1668
+ let hash = 0;
1669
+ const text = stableString(args);
1670
+ for (let i = 0; i < text.length; i++) {
1671
+ hash = (hash << 5) - hash + text.charCodeAt(i);
1672
+ hash |= 0;
1673
+ }
1674
+ return (hash >>> 0).toString(36);
1675
+ }
1676
+ function stableString(value, seen) {
1677
+ if (value === null || typeof value !== "object") {
1678
+ return typeof value === "bigint" ? value + "n" : String(value);
1679
+ }
1680
+ if (value instanceof Date) return "Date:" + value.getTime();
1681
+ seen || (seen = new Set());
1682
+ if (seen.has(value)) return "~";
1683
+ seen.add(value);
1684
+ if (value instanceof Map) {
1685
+ const entries = [];
1686
+ for (const [k, v] of value) {
1687
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
1688
+ }
1689
+ return "Map{" + entries.sort().join(",") + "}";
1690
+ }
1691
+ if (value instanceof Set) {
1692
+ const members = [];
1693
+ for (const v of value) members.push(stableString(v, seen));
1694
+ return "Set{" + members.sort().join(",") + "}";
1695
+ }
1696
+ if (Array.isArray(value)) {
1697
+ let out = "[";
1698
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
1699
+ return out + "]";
1700
+ }
1701
+ const keys = Object.keys(value).sort();
1702
+ let out = "{";
1703
+ for (let i = 0; i < keys.length; i++) {
1704
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
1705
+ }
1706
+ return out + "}";
1707
+ }
1708
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
1709
+ function createChunk(data) {
1710
+ const encodeData = new TextEncoder().encode(data);
1711
+ const bytes = encodeData.length;
1712
+ const baseHex = bytes.toString(16);
1713
+ const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex;
1714
+ const head = new TextEncoder().encode(`;0x${totalHex};`);
1715
+ const chunk = new Uint8Array(12 + bytes);
1716
+ chunk.set(head);
1717
+ chunk.set(encodeData, 12);
1718
+ return chunk;
1719
+ }
1720
+ class ChunkReader {
1721
+ constructor(stream) {
1722
+ this.reader = stream.getReader();
1723
+ this.buffer = new Uint8Array(0);
1724
+ this.done = false;
1725
+ }
1726
+ async readChunk() {
1727
+ const chunk = await this.reader.read();
1728
+ if (!chunk.done) {
1729
+ const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
1730
+ newBuffer.set(this.buffer);
1731
+ newBuffer.set(chunk.value, this.buffer.length);
1732
+ this.buffer = newBuffer;
1733
+ } else {
1734
+ this.done = true;
1735
+ }
1736
+ }
1737
+ async next() {
1738
+ while (this.buffer.length < 12) {
1739
+ if (this.done) {
1740
+ if (this.buffer.length === 0) return {
1741
+ done: true,
1742
+ value: undefined
1743
+ };
1744
+ throw new Error("Malformed server function stream.");
1745
+ }
1746
+ await this.readChunk();
1747
+ }
1748
+ const head = new TextDecoder().decode(this.buffer.subarray(1, 11));
1749
+ const bytes = Number.parseInt(head, 16);
1750
+ if (Number.isNaN(bytes)) {
1751
+ throw new Error("Malformed server function stream.");
1752
+ }
1753
+ while (bytes > this.buffer.length - 12) {
1754
+ if (this.done) {
1755
+ throw new Error("Malformed server function stream.");
1756
+ }
1757
+ await this.readChunk();
1758
+ }
1759
+ const partial = new TextDecoder().decode(this.buffer.subarray(12, 12 + bytes));
1760
+ this.buffer = this.buffer.subarray(12 + bytes);
1761
+ return {
1762
+ done: false,
1763
+ value: partial
1764
+ };
1765
+ }
1766
+ async drain(interpret) {
1767
+ while (true) {
1768
+ const result = await this.next();
1769
+ if (result.done) {
1770
+ break;
1771
+ }
1772
+ interpret(result.value);
1773
+ }
1774
+ }
1775
+ }
1776
+ function serializeStream(value, codecOptions) {
1777
+ return new ReadableStream({
1778
+ start(controller) {
1779
+ serializeJSON(value, {
1780
+ ...codecOptions,
1781
+ onParse(node) {
1782
+ controller.enqueue(createChunk(JSON.stringify(node)));
1783
+ },
1784
+ onDone() {
1785
+ controller.close();
1786
+ },
1787
+ onError(error) {
1788
+ controller.error(error);
1789
+ }
1790
+ });
1791
+ }
1792
+ });
1793
+ }
1794
+
1795
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
1796
+ function isResponseEnvelope(value) {
1797
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
1798
+ }
1799
+
1800
+ const INVOCATIONS = new WeakMap();
1801
+ function getEventServerFunctionInvocation(event) {
1802
+ return event && INVOCATIONS.get(event);
1803
+ }
1804
+
1805
+ const FRAME_STREAM_HEADER = "X-Frame-Stream";
1806
+ function isFrameStreamResponse(response) {
1807
+ return response.headers.has(FRAME_STREAM_HEADER);
1808
+ }
1809
+ const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("dom-expressions.server-component");
1810
+ const SERVER_COMPONENT_SOURCE = /*#__PURE__*/Symbol.for("dom-expressions.server-component-source");
1811
+ const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("dom-expressions.server-component-address");
1812
+ let serverComponentRegistryExpr;
1813
+ function setServerComponentBootstrap(resolve) {
1814
+ serverComponentRegistryExpr = resolve;
1815
+ }
1816
+ function parseServerComponent(value, ctx) {
1817
+ return {
1818
+ id: ctx.parse(value[SERVER_COMPONENT]),
1819
+ address: ctx.parse(value[SERVER_COMPONENT_ADDRESS])
1820
+ };
1821
+ }
1822
+ const ServerComponentPlugin = /*#__PURE__*/createPlugin({
1823
+ tag: "dom-expressions/server-component",
1824
+ test(value) {
1825
+ return typeof value === "function" && SERVER_COMPONENT in value;
1826
+ },
1827
+ parse: {
1828
+ sync: parseServerComponent,
1829
+ async async(value, ctx) {
1830
+ return {
1831
+ id: await ctx.parse(value[SERVER_COMPONENT]),
1832
+ address: await ctx.parse(value[SERVER_COMPONENT_ADDRESS])
1833
+ };
1834
+ },
1835
+ stream: parseServerComponent
1836
+ },
1837
+ serialize(node, ctx) {
1838
+ const registry = serverComponentRegistryExpr ? serverComponentRegistryExpr(ctx) : "self._$SC";
1839
+ return registry + ".r(" + ctx.serialize(node.id) + "," + ctx.serialize(node.address) + ")";
1840
+ },
1841
+ deserialize(node, ctx) {
1842
+ const id = ctx.deserialize(node.id);
1843
+ ctx.deserialize(node.address);
1844
+ return globalThis._$SC.r(id);
1845
+ }
1846
+ });
1847
+ function flightCodec(codec) {
1848
+ const plugins = codec && codec.plugins || [];
1849
+ for (const plugin of plugins) {
1850
+ if (plugin && plugin.tag === "dom-expressions/server-component") return codec;
1851
+ }
1852
+ return {
1853
+ ...codec,
1854
+ plugins: [...plugins, ServerComponentPlugin]
1855
+ };
1856
+ }
1857
+
1858
+ function serverOwned(render) {
1859
+ return NoHydration ? NoHydration({
1860
+ get children() {
1861
+ return render();
1862
+ }
1863
+ }) : render();
1864
+ }
1865
+ function serverComponentScope(render) {
1866
+ return runInServerComponentScope ? runInServerComponentScope(render) : render();
1867
+ }
1868
+ 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))}}))";
1869
+ const bootstrappedScripts = new WeakSet();
1870
+ setServerComponentBootstrap(ctx => {
1871
+ if (bootstrappedScripts.has(ctx)) return "self._$SC";
1872
+ bootstrappedScripts.add(ctx);
1873
+ return SERVER_COMPONENT_BOOTSTRAP_EXPR;
1874
+ });
1875
+ const SERVER_COMPONENT_BOOTSTRAP = SERVER_COMPONENT_BOOTSTRAP_EXPR + ";";
1876
+ function createFrameSink(emit, frame) {
1877
+ const {
1878
+ id,
1879
+ version
1880
+ } = frame;
1881
+ const styledKeys = new Set();
1882
+ const regionKeys = new Map();
1883
+ const frameOf = key => regionKeys.get(key) || id;
1884
+ return {
1885
+ tagRegion(key, childId) {
1886
+ if (!regionKeys.has(key)) regionKeys.set(key, childId);
1887
+ },
1888
+ shell(html, meta = {}) {
1889
+ if (meta.preloads && meta.preloads.size) {
1890
+ const styles = [];
1891
+ const modules = [];
1892
+ for (const url of meta.preloads) {
1893
+ (url.endsWith(".css") ? styles : modules).push(url);
1894
+ }
1895
+ const chunk = {
1896
+ type: "assets",
1897
+ id,
1898
+ version,
1899
+ key: ""
1900
+ };
1901
+ if (styles.length) chunk.styles = styles;
1902
+ if (modules.length) chunk.modules = modules;
1903
+ emit(chunk);
1904
+ }
1905
+ emit({
1906
+ type: "html",
1907
+ id,
1908
+ version,
1909
+ html
1910
+ });
1911
+ },
1912
+ data(record) {
1913
+ if (record && typeof record.key === "string" && (record.key.endsWith("_fr") || /^\d+$/.test(record.key))) {
1914
+ return;
1915
+ }
1916
+ if (typeof record === "string") {
1917
+ emit({
1918
+ type: "data",
1919
+ id,
1920
+ version,
1921
+ payload: record
1922
+ });
1923
+ } else {
1924
+ emit({
1925
+ type: "data",
1926
+ id,
1927
+ version,
1928
+ key: record.key,
1929
+ node: record.node,
1930
+ initial: record.initial
1931
+ });
1932
+ }
1933
+ },
1934
+ fragment(key, value, meta = {}) {
1935
+ const fid = frameOf(key);
1936
+ const links = meta.styles && meta.styles.links || [];
1937
+ const inline = meta.styles && meta.styles.inline || [];
1938
+ if (links.length || inline.length) {
1939
+ if (links.length) styledKeys.add(key);
1940
+ const chunk = {
1941
+ type: "assets",
1942
+ id: fid,
1943
+ version,
1944
+ key
1945
+ };
1946
+ if (links.length) {
1947
+ chunk.styles = links.map(e => typeof e === "string" ? e : e.attrs ? {
1948
+ href: e.href,
1949
+ attrs: e.attrs
1950
+ } : e.href);
1951
+ }
1952
+ if (inline.length) {
1953
+ chunk.inlineStyles = inline.map(e => ({
1954
+ id: e.id,
1955
+ content: e.content,
1956
+ attrs: e.attrs
1957
+ }));
1958
+ }
1959
+ emit(chunk);
1960
+ }
1961
+ emit({
1962
+ type: "fragment",
1963
+ id: fid,
1964
+ version,
1965
+ key,
1966
+ html: value
1967
+ });
1968
+ if (meta.error) {
1969
+ emit({
1970
+ type: "error",
1971
+ id: fid,
1972
+ version,
1973
+ key,
1974
+ error: {
1975
+ message: String(meta.error && meta.error.message || meta.error)
1976
+ }
1977
+ });
1978
+ }
1979
+ if (!meta.revealGroup) {
1980
+ emit({
1981
+ type: "reveal",
1982
+ id: fid,
1983
+ version,
1984
+ keys: [key],
1985
+ waitForStyles: !!links.length
1986
+ });
1987
+ }
1988
+ },
1989
+ reveal(keys, meta = {}) {
1990
+ const byFrame = new Map();
1991
+ for (const key of keys) {
1992
+ const fid = frameOf(key);
1993
+ let group = byFrame.get(fid);
1994
+ if (!group) byFrame.set(fid, group = []);
1995
+ group.push(key);
1996
+ }
1997
+ for (const [fid, groupKeys] of byFrame) {
1998
+ let waitForStyles = false;
1999
+ for (const key of groupKeys) if (styledKeys.has(key)) waitForStyles = true;
2000
+ const chunk = {
2001
+ type: "reveal",
2002
+ id: fid,
2003
+ version,
2004
+ keys: groupKeys,
2005
+ waitForStyles
2006
+ };
2007
+ if (meta.fallback) chunk.fallback = true;
2008
+ emit(chunk);
2009
+ }
2010
+ },
2011
+ asset(type, url) {
2012
+ if (type !== "module") return;
2013
+ emit({
2014
+ type: "assets",
2015
+ id,
2016
+ version,
2017
+ key: "",
2018
+ modules: [url]
2019
+ });
2020
+ },
2021
+ end() {
2022
+ emit({
2023
+ type: "complete",
2024
+ id,
2025
+ version
2026
+ });
2027
+ },
2028
+ error(errorId, error) {
2029
+ emit({
2030
+ type: "error",
2031
+ id,
2032
+ version,
2033
+ key: errorId,
2034
+ error
2035
+ });
2036
+ },
2037
+ slot(key, args) {
2038
+ emit({
2039
+ type: "slot",
2040
+ id,
2041
+ version,
2042
+ key,
2043
+ args
2044
+ });
2045
+ },
2046
+ region(childId, html) {
2047
+ emit({
2048
+ type: "html",
2049
+ id: childId,
2050
+ version,
2051
+ html
2052
+ });
2053
+ }
2054
+ };
2055
+ }
2056
+ function renderToFrameStream(code, options = {}) {
2057
+ return frameStream(() => code, options);
2058
+ }
2059
+ function renderServerComponent(component, options = {}) {
2060
+ return frameStream((sink, frame) => {
2061
+ const props = createSlotProps(sink, frame);
2062
+ return () => serverComponentScope(() => component(props));
2063
+ }, options);
2064
+ }
2065
+ function frameStream(makeCode, options) {
2066
+ const {
2067
+ id = "",
2068
+ version = 1
2069
+ } = options.frame || {};
2070
+ const frame = {
2071
+ id,
2072
+ version
2073
+ };
2074
+ function stream(w) {
2075
+ const emit = chunk => w.write(chunk);
2076
+ const sink = createFrameSink(emit, frame);
2077
+ emit({
2078
+ type: "start",
2079
+ id,
2080
+ version
2081
+ });
2082
+ const code = makeCode(sink, frame);
2083
+ try {
2084
+ renderToStream(() => serverOwned(code), {
2085
+ serializer: createJSONSerializer,
2086
+ ...options,
2087
+ sink
2088
+ }).pipe({
2089
+ write() {},
2090
+ end() {
2091
+ sink.end();
2092
+ w.end && w.end();
2093
+ }
2094
+ });
2095
+ } catch (err) {
2096
+ sink.error("", err instanceof Error ? err.message : String(err));
2097
+ sink.end();
2098
+ w.end && w.end();
2099
+ }
2100
+ }
2101
+ return {
2102
+ pipe: stream,
2103
+ then(onFulfilled, onRejected) {
2104
+ return new Promise((resolve, reject) => {
2105
+ const chunks = [];
2106
+ try {
2107
+ stream({
2108
+ write: chunk => chunks.push(chunk),
2109
+ end: () => resolve(chunks)
2110
+ });
2111
+ } catch (err) {
2112
+ reject(err);
2113
+ }
2114
+ }).then(onFulfilled, onRejected);
2115
+ }
2116
+ };
2117
+ }
2118
+ function slotRange(occurrence) {
2119
+ return {
2120
+ t: `<!--slot:${occurrence}:start--><!--slot:${occurrence}:end-->`
2121
+ };
2122
+ }
2123
+ const OCCURRENCE_UNSAFE = /[^A-Za-z0-9_.-]/g;
2124
+ function encodeOccurrenceKey(key) {
2125
+ return String(key).replace(OCCURRENCE_UNSAFE, c => {
2126
+ const code = c.codePointAt(0);
2127
+ return "%" + (code < 16 ? "0" : "") + code.toString(16);
2128
+ });
2129
+ }
2130
+ function occurrenceId(prop, raw, counts) {
2131
+ const k = raw.$key;
2132
+ if (typeof k === "string" || typeof k === "number") {
2133
+ return `${prop}#${encodeOccurrenceKey(k)}`;
2134
+ }
2135
+ const n = counts[prop] || 0;
2136
+ counts[prop] = n + 1;
2137
+ return `${prop}#${n}`;
2138
+ }
2139
+ function createDocumentSlotProps(clientProps, frameId) {
2140
+ const counts = Object.create(null);
2141
+ const getters = new Map();
2142
+ const range = (occurrence, content) => [{
2143
+ t: `<!--slot:${occurrence}:start-->`
2144
+ }, content, {
2145
+ t: `<!--slot:${occurrence}:end-->`
2146
+ }];
2147
+ const zoneOwner = getOwner ? getOwner() : null;
2148
+ const scoped = (occurrence, render) => {
2149
+ const id = `sc-${frameId}-${occurrence}-`;
2150
+ const run = () => Hydration ? Hydration({
2151
+ id,
2152
+ get children() {
2153
+ return render();
2154
+ }
2155
+ }) : runWithHydrationScope(id, render);
2156
+ return zoneOwner ? runWithOwner(zoneOwner, run) : run();
2157
+ };
2158
+ return new Proxy(Object.create(null), {
2159
+ has() {
2160
+ return true;
2161
+ },
2162
+ get(_, prop) {
2163
+ if (typeof prop !== "string") return undefined;
2164
+ if (prop === "then") return undefined;
2165
+ let fn = getters.get(prop);
2166
+ if (!fn) {
2167
+ fn = (...callArgs) => {
2168
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
2169
+ return scoped(prop, () => {
2170
+ const value = clientProps[prop];
2171
+ return range(prop, typeof value === "function" ? value() : value);
2172
+ });
2173
+ }
2174
+ const raw = callArgs[0];
2175
+ const occurrence = occurrenceId(prop, raw, counts);
2176
+ const slot = clientProps[prop];
2177
+ if (typeof slot !== "function") return range(occurrence, undefined);
2178
+ const resolved = {};
2179
+ const vals = {};
2180
+ for (const key of Object.keys(raw)) {
2181
+ if (key === "$key") continue;
2182
+ let value = raw[key];
2183
+ for (let d = 0; typeof value === "function" && d < 16; d++) value = value();
2184
+ vals[key] = value;
2185
+ }
2186
+ const regions = [];
2187
+ for (const key of Object.keys(vals)) {
2188
+ const value = vals[key];
2189
+ if (isServerContent(value)) {
2190
+ const childId = `${frameId}.${occurrence}.${key}`;
2191
+ const region = {
2192
+ key,
2193
+ childId,
2194
+ value,
2195
+ used: false,
2196
+ locked: false
2197
+ };
2198
+ regions.push(region);
2199
+ resolved[key] = () => {
2200
+ if (region.locked) return [];
2201
+ region.used = true;
2202
+ return [{
2203
+ t: frameElementOpen(childId)
2204
+ }, value, {
2205
+ t: FRAME_ELEMENT_CLOSE
2206
+ }];
2207
+ };
2208
+ } else {
2209
+ resolved[key] = value;
2210
+ }
2211
+ }
2212
+ const out = scoped(occurrence, () => range(occurrence, slot(resolved)));
2213
+ const unused = regions.filter(r => !r.used);
2214
+ if (sharedConfig.context) {
2215
+ const args = {};
2216
+ for (const key of Object.keys(vals)) {
2217
+ const value = vals[key];
2218
+ const region = regions.find(r => r.key === key);
2219
+ if (region) {
2220
+ args[key] = {
2221
+ $frame: region.childId
2222
+ };
2223
+ continue;
2224
+ }
2225
+ if (isServerContent(value)) continue;
2226
+ args[key] = value;
2227
+ }
2228
+ sharedConfig.context.serialize(`sc:slot:${frameId}:${occurrence}`, args);
2229
+ for (const region of unused) {
2230
+ region.locked = true;
2231
+ sharedConfig.context.serialize(`sc:region:${region.childId}`, resolveRegionHtml(sharedConfig.context, region.value));
2232
+ }
2233
+ }
2234
+ return out;
2235
+ };
2236
+ getters.set(prop, fn);
2237
+ }
2238
+ return fn;
2239
+ }
2240
+ });
2241
+ }
2242
+ const FRAME_TAG = "dx-frame";
2243
+ const FRAME_ID_ATTR = "data-fid";
2244
+ function frameElementOpen(id) {
2245
+ const escaped = sharedConfig.context ? sharedConfig.context.escape(String(id), true) : String(id);
2246
+ return `<${FRAME_TAG} ${FRAME_ID_ATTR}="${escaped}" style="display:contents">`;
2247
+ }
2248
+ const FRAME_ELEMENT_CLOSE = `</${FRAME_TAG}>`;
2249
+ function frameTransformDirectResult(value, {
2250
+ id,
2251
+ args
2252
+ }) {
2253
+ if (typeof value !== "function") return value;
2254
+ const component = value;
2255
+ const wrapped = props => [{
2256
+ t: frameElementOpen(id)
2257
+ },
2258
+ serverOwned(() => {
2259
+ const slotProps = createDocumentSlotProps(props, id);
2260
+ return serverComponentScope(() => component(slotProps));
2261
+ }), {
2262
+ t: FRAME_ELEMENT_CLOSE
2263
+ }];
2264
+ wrapped[SERVER_COMPONENT] = id;
2265
+ wrapped[SERVER_COMPONENT_SOURCE] = component;
2266
+ wrapped[SERVER_COMPONENT_ADDRESS] = frameAddress(id, args);
2267
+ return wrapped;
2268
+ }
2269
+ function resolveRegionHtml(ctx, node) {
2270
+ const res = ctx.resolve(node);
2271
+ if (!res || !res.t) return String(res ?? "");
2272
+ if (!res.h || !res.h.length) return res.t[0];
2273
+ return Promise.all(res.p).then(() => {
2274
+ let out = Promise.resolve(res.t[0]);
2275
+ for (let i = 0; i < res.h.length; i++) {
2276
+ const hole = res.h[i];
2277
+ const tail = res.t[i + 1];
2278
+ out = out.then(acc => Promise.resolve(resolveRegionHtml(ctx, hole)).then(part => acc + part + tail));
2279
+ }
2280
+ return out;
2281
+ });
2282
+ }
2283
+ function isServerContent(value) {
2284
+ if (value && typeof value === "object") {
2285
+ if ("t" in value) return true;
2286
+ if (Array.isArray(value) && value.length > 0) {
2287
+ for (const item of value) {
2288
+ if (!(item && typeof item === "object" && "t" in item)) return false;
2289
+ }
2290
+ return true;
2291
+ }
2292
+ }
2293
+ return false;
2294
+ }
2295
+ function createSlotProps(sink, frame) {
2296
+ const counts = Object.create(null);
2297
+ const getters = new Map();
2298
+ return new Proxy(Object.create(null), {
2299
+ has() {
2300
+ return true;
2301
+ },
2302
+ get(_, prop) {
2303
+ if (typeof prop !== "string") return undefined;
2304
+ if (prop === "then") return undefined;
2305
+ let fn = getters.get(prop);
2306
+ if (!fn) {
2307
+ fn = (...callArgs) => {
2308
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
2309
+ return slotRange(prop);
2310
+ }
2311
+ const raw = callArgs[0];
2312
+ const occurrence = occurrenceId(prop, raw, counts);
2313
+ const args = {};
2314
+ for (const key of Object.keys(raw)) {
2315
+ if (key === "$key") continue;
2316
+ const childId = `${frame.id}.${occurrence}.${key}`;
2317
+ const ctx = sharedConfig.context;
2318
+ const origRegister = ctx.registerFragment;
2319
+ ctx.registerFragment = (fragKey, fragOptions) => {
2320
+ sink.tagRegion(fragKey, childId);
2321
+ return origRegister.call(ctx, fragKey, fragOptions);
2322
+ };
2323
+ try {
2324
+ let value = raw[key];
2325
+ for (let d = 0; typeof value === "function" && d < 16; d++) value = value();
2326
+ const t = typeof value;
2327
+ if (value == null || t === "string" || t === "number" || t === "boolean") {
2328
+ args[key] = value;
2329
+ } else if (isServerContent(value)) {
2330
+ const resolved = ctx.resolve(value);
2331
+ if (resolved.h.length) {
2332
+ 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.");
2333
+ }
2334
+ sink.region(childId, resolved.t[0]);
2335
+ args[key] = {
2336
+ $frame: childId
2337
+ };
2338
+ } else {
2339
+ const ref = `arg:${occurrence}:${key}`;
2340
+ ctx.serialize(ref, value);
2341
+ args[key] = {
2342
+ $ref: ref
2343
+ };
2344
+ }
2345
+ } finally {
2346
+ ctx.registerFragment = origRegister;
2347
+ }
2348
+ }
2349
+ sink.slot(occurrence, args);
2350
+ return slotRange(occurrence);
2351
+ };
2352
+ getters.set(prop, fn);
2353
+ }
2354
+ return fn;
2355
+ }
2356
+ });
2357
+ }
2358
+ function serverComponentResponse(component, options = {}, init = {}) {
2359
+ const {
2360
+ id = "",
2361
+ version = 1
2362
+ } = options.frame || {};
2363
+ const headers = new Headers(init.headers);
2364
+ headers.set("Content-Type", "application/x-frame-stream");
2365
+ headers.set(FRAME_STREAM_HEADER, id);
2366
+ headers.set("X-Content-Raw", "1");
2367
+ const stream = renderServerComponent(component, {
2368
+ ...options,
2369
+ frame: {
2370
+ id,
2371
+ version
2372
+ }
2373
+ });
2374
+ const body = new ReadableStream({
2375
+ start(controller) {
2376
+ stream.pipe({
2377
+ write(chunk) {
2378
+ controller.enqueue(createChunk(JSON.stringify(chunk)));
2379
+ },
2380
+ end() {
2381
+ controller.close();
2382
+ }
2383
+ });
2384
+ }
2385
+ });
2386
+ return new Response(body, {
2387
+ status: init.status || 200,
2388
+ headers
2389
+ });
2390
+ }
2391
+ function frameTransformResult(event, result, context) {
2392
+ let init;
2393
+ if (isResponseEnvelope(result)) {
2394
+ const {
2395
+ response,
2396
+ value
2397
+ } = result;
2398
+ if (typeof value !== "function") return result;
2399
+ init = response ? {
2400
+ headers: response.headers,
2401
+ status: response.status
2402
+ } : undefined;
2403
+ result = value;
2404
+ }
2405
+ if (typeof result !== "function") return result;
2406
+ if (context && context.collectsFlight) return init ? {
2407
+ response: init,
2408
+ value: result
2409
+ } : result;
2410
+ const invocation = getEventServerFunctionInvocation(event);
2411
+ return serverComponentResponse(result, {
2412
+ frame: {
2413
+ id: invocation && invocation.id || ""
2414
+ }
2415
+ }, init);
2416
+ }
2417
+ async function frameTransformFlightResult(event, outcome, context) {
2418
+ const {
2419
+ value,
2420
+ data
2421
+ } = outcome;
2422
+ const regions = [];
2423
+ let serialized = data;
2424
+ if (data && typeof data === "object") {
2425
+ serialized = {};
2426
+ const keys = Object.keys(data);
2427
+ const values = await Promise.all(keys.map(key => data[key]));
2428
+ for (let i = 0; i < keys.length; i++) {
2429
+ const entry = values[i];
2430
+ serialized[keys[i]] = entry;
2431
+ if (typeof entry === "function") {
2432
+ regions.push({
2433
+ id: entry[SERVER_COMPONENT_ADDRESS] || keys[i],
2434
+ component: entry[SERVER_COMPONENT_SOURCE] || entry
2435
+ });
2436
+ }
2437
+ }
2438
+ }
2439
+ const invocation = getEventServerFunctionInvocation(event);
2440
+ const primary = typeof value === "function" ? {
2441
+ id: invocation && invocation.id || "",
2442
+ component: value
2443
+ } : undefined;
2444
+ if (!primary && !regions.length) return undefined;
2445
+ return frameFlightResponse({
2446
+ primary,
2447
+ regions,
2448
+ outcome: {
2449
+ value: primary ? undefined : value,
2450
+ data: serialized
2451
+ },
2452
+ codec: context && context.codec
2453
+ });
2454
+ }
2455
+ function frameFlightResponse({
2456
+ primary,
2457
+ regions = [],
2458
+ outcome,
2459
+ codec
2460
+ }, init = {}) {
2461
+ const frames = primary ? [primary, ...regions] : regions;
2462
+ const headers = new Headers(init.headers);
2463
+ headers.set("Content-Type", "application/x-frame-stream");
2464
+ headers.set(FRAME_STREAM_HEADER, primary ? primary.id : "");
2465
+ headers.set("X-Content-Raw", "1");
2466
+ headers.set(SINGLE_FLIGHT_HEADER, "true");
2467
+ const body = new ReadableStream({
2468
+ async start(controller) {
2469
+ const write = chunk => controller.enqueue(createChunk(JSON.stringify(chunk)));
2470
+ try {
2471
+ for (const {
2472
+ id,
2473
+ component
2474
+ } of frames) {
2475
+ await new Promise(resolve => {
2476
+ renderServerComponent(component, {
2477
+ frame: {
2478
+ id,
2479
+ version: 1
2480
+ }
2481
+ }).pipe({
2482
+ write,
2483
+ end: resolve
2484
+ });
2485
+ });
2486
+ }
2487
+ if (outcome) {
2488
+ const reader = new ChunkReader(serializeStream(outcome, flightCodec(codec)));
2489
+ for (let node = await reader.next(); !node.done; node = await reader.next()) {
2490
+ write({
2491
+ type: "outcome",
2492
+ payload: node.value
2493
+ });
2494
+ }
2495
+ }
2496
+ controller.close();
2497
+ } catch (err) {
2498
+ controller.error(err);
2499
+ }
2500
+ }
2501
+ });
2502
+ return new Response(body, {
2503
+ status: init.status || 200,
2504
+ headers
2505
+ });
2506
+ }
2507
+
2508
+ export { FRAME_STREAM_HEADER, SERVER_COMPONENT_BOOTSTRAP, ServerComponentPlugin, createFrameSink, frameTransformDirectResult, frameTransformFlightResult, frameTransformResult, isFrameStreamResponse, renderServerComponent, renderToFrameStream, serverComponentResponse };