@solidjs/web 2.0.0-beta.22 → 2.0.0-beta.23

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 (42) hide show
  1. package/dist/dev.cjs +25 -1
  2. package/dist/dev.js +25 -2
  3. package/dist/server.cjs +79 -33
  4. package/dist/server.js +79 -34
  5. package/dist/web.cjs +25 -1
  6. package/dist/web.js +25 -2
  7. package/frames/dist/client.cjs +1442 -0
  8. package/frames/dist/client.js +1430 -0
  9. package/frames/dist/server.cjs +1705 -0
  10. package/frames/dist/server.js +1694 -0
  11. package/frames/package.json +30 -0
  12. package/package.json +78 -5
  13. package/serialization/dist/serialization.cjs +83 -0
  14. package/serialization/dist/serialization.js +82 -1
  15. package/serialization/types/index.d.ts +12 -0
  16. package/serialization/types-cjs/index.d.cts +12 -0
  17. package/server-functions/dist/client.cjs +82 -55
  18. package/server-functions/dist/client.js +83 -56
  19. package/server-functions/dist/server.cjs +20 -3
  20. package/server-functions/dist/server.js +20 -3
  21. package/types/client.d.ts +8 -0
  22. package/types/core.d.ts +2 -1
  23. package/types/frames/client.d.ts +53 -0
  24. package/types/frames/frame-client.d.ts +205 -0
  25. package/types/frames/frame-sink.d.ts +145 -0
  26. package/types/frames/frame-transport.d.ts +105 -0
  27. package/types/frames/serializer.d.ts +151 -0
  28. package/types/frames/server.d.ts +21 -0
  29. package/types/serializer.d.ts +12 -0
  30. package/types/server-functions/client.d.ts +24 -0
  31. package/types/server.d.ts +2 -0
  32. package/types-cjs/client.d.cts +8 -0
  33. package/types-cjs/core.d.cts +2 -1
  34. package/types-cjs/frames/client.d.cts +53 -0
  35. package/types-cjs/frames/frame-client.d.cts +205 -0
  36. package/types-cjs/frames/frame-sink.d.cts +145 -0
  37. package/types-cjs/frames/frame-transport.d.cts +105 -0
  38. package/types-cjs/frames/serializer.d.cts +151 -0
  39. package/types-cjs/frames/server.d.cts +21 -0
  40. package/types-cjs/serializer.d.cts +12 -0
  41. package/types-cjs/server-functions/client.d.cts +24 -0
  42. package/types-cjs/server.d.cts +2 -0
@@ -0,0 +1,1694 @@
1
+ import { toCrossJSONStream, Feature, Serializer, getCrossReferenceHeader, createPlugin } from 'seroval';
2
+ import { runWithOwner, createOwner, sharedConfig, createRoot, ssrHandleError, getOwner, NoHydration, Hydration } from 'solid-js';
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 HYDRATION_GLOBAL = "_$HY.r";
11
+ const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
12
+ CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
13
+ FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin]);
14
+ function resolveSerializerPlugins(customPlugins) {
15
+ return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
16
+ }
17
+ function createSerializer(options) {
18
+ return new Serializer({
19
+ ...options,
20
+ plugins: resolveSerializerPlugins(options.plugins),
21
+ disabledFeatures: options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures
22
+ });
23
+ }
24
+ function createHydrationSerializer({
25
+ onData,
26
+ onDone,
27
+ scopeId,
28
+ onError,
29
+ plugins
30
+ }) {
31
+ return createSerializer({
32
+ scopeId,
33
+ plugins,
34
+ globalIdentifier: HYDRATION_GLOBAL,
35
+ onData,
36
+ onDone,
37
+ onError
38
+ });
39
+ }
40
+ function getLocalHeaderScript(id) {
41
+ return getCrossReferenceHeader(id) + ";";
42
+ }
43
+ const JSON_CODEC_DISABLED_FEATURES = Feature.RegExp;
44
+ const JSON_CODEC_DEPTH_LIMIT = 64;
45
+ function resolveCodecOptions({
46
+ plugins,
47
+ disabledFeatures,
48
+ depthLimit
49
+ } = {}) {
50
+ return {
51
+ plugins: resolveSerializerPlugins(plugins),
52
+ disabledFeatures: disabledFeatures === undefined ? JSON_CODEC_DISABLED_FEATURES : disabledFeatures,
53
+ depthLimit: depthLimit === undefined ? JSON_CODEC_DEPTH_LIMIT : depthLimit
54
+ };
55
+ }
56
+ function createJSONSerializer({
57
+ onData,
58
+ onDone,
59
+ onError,
60
+ plugins,
61
+ disabledFeatures,
62
+ depthLimit
63
+ }) {
64
+ const resolved = resolveCodecOptions({
65
+ plugins,
66
+ disabledFeatures,
67
+ depthLimit
68
+ });
69
+ const refs = new Map();
70
+ const cancels = new Set();
71
+ let pendingWrites = 0;
72
+ let flushed = false;
73
+ let done = false;
74
+ const maybeDone = () => {
75
+ if (flushed && pendingWrites === 0 && !done) {
76
+ done = true;
77
+ onDone && onDone();
78
+ }
79
+ };
80
+ return {
81
+ write(key, value) {
82
+ if (flushed) return;
83
+ pendingWrites++;
84
+ let settled = false;
85
+ let cancel = null;
86
+ const stream = toCrossJSONStream(value, {
87
+ refs,
88
+ plugins: resolved.plugins,
89
+ disabledFeatures: resolved.disabledFeatures,
90
+ onParse(node, initial) {
91
+ onData({
92
+ key,
93
+ node,
94
+ initial
95
+ });
96
+ },
97
+ onError,
98
+ onDone() {
99
+ settled = true;
100
+ if (cancel) cancels.delete(cancel);
101
+ pendingWrites--;
102
+ maybeDone();
103
+ }
104
+ });
105
+ if (!settled) {
106
+ cancel = stream;
107
+ cancels.add(cancel);
108
+ }
109
+ },
110
+ flush() {
111
+ flushed = true;
112
+ maybeDone();
113
+ },
114
+ close() {
115
+ flushed = true;
116
+ for (const cancel of cancels) cancel();
117
+ cancels.clear();
118
+ }
119
+ };
120
+ }
121
+
122
+ function joinAssetPath(base, file) {
123
+ if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
124
+ if (typeof base !== "string" || !base) base = "/";
125
+ if (base[base.length - 1] !== "/") base += "/";
126
+ return base + (file[0] === "/" ? file.slice(1) : file);
127
+ }
128
+ function resolveAssets(moduleUrl, manifest) {
129
+ if (!manifest) return null;
130
+ const base = manifest._base;
131
+ const entry = manifest[moduleUrl];
132
+ if (!entry) return null;
133
+ const css = [];
134
+ const js = [];
135
+ const visited = new Set();
136
+ const walk = key => {
137
+ if (visited.has(key)) return;
138
+ visited.add(key);
139
+ const e = manifest[key];
140
+ if (!e) return;
141
+ js.push(joinAssetPath(base, e.file));
142
+ if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
143
+ if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
144
+ };
145
+ walk(moduleUrl);
146
+ return {
147
+ js,
148
+ css
149
+ };
150
+ }
151
+ function registerEntryAssets(manifest) {
152
+ if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
153
+ const ctx = sharedConfig.context;
154
+ if (!ctx?.registerAsset) return;
155
+ for (const key in manifest) {
156
+ if (manifest[key].isEntry) {
157
+ const assets = resolveAssets(key, manifest);
158
+ if (assets) {
159
+ for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
160
+ }
161
+ return;
162
+ }
163
+ }
164
+ }
165
+ function createAssetTracking() {
166
+ const boundaryModules = new Map();
167
+ const boundaryStyles = new Map();
168
+ const emittedAssets = new Set();
169
+ const inlineStyles = new Map();
170
+ let currentBoundaryId = null;
171
+ return {
172
+ boundaryModules,
173
+ boundaryStyles,
174
+ emittedAssets,
175
+ inlineStyles,
176
+ registerInlineStyle(desc) {
177
+ let entry = inlineStyles.get(desc.id);
178
+ if (!entry) {
179
+ entry = {
180
+ id: desc.id,
181
+ content: desc.content || "",
182
+ attrs: desc.attrs,
183
+ emitted: false
184
+ };
185
+ inlineStyles.set(desc.id, entry);
186
+ }
187
+ if (currentBoundaryId) {
188
+ let styles = boundaryStyles.get(currentBoundaryId);
189
+ if (!styles) {
190
+ styles = new Set();
191
+ boundaryStyles.set(currentBoundaryId, styles);
192
+ }
193
+ styles.add(entry);
194
+ }
195
+ return entry;
196
+ },
197
+ get currentBoundaryId() {
198
+ return currentBoundaryId;
199
+ },
200
+ set currentBoundaryId(v) {
201
+ currentBoundaryId = v;
202
+ },
203
+ registerModule(key, entryUrl) {
204
+ const id = currentBoundaryId || "";
205
+ let map = boundaryModules.get(id);
206
+ if (!map) {
207
+ map = {};
208
+ boundaryModules.set(id, map);
209
+ }
210
+ map[key] = entryUrl;
211
+ },
212
+ getBoundaryModules(id) {
213
+ return boundaryModules.get(id) || null;
214
+ },
215
+ getBoundaryStyles(id) {
216
+ return boundaryStyles.get(id) || null;
217
+ }
218
+ };
219
+ }
220
+ function applyAssetTracking(context, tracking, manifest) {
221
+ Object.defineProperty(context, "_currentBoundaryId", {
222
+ get() {
223
+ return tracking.currentBoundaryId;
224
+ },
225
+ set(v) {
226
+ tracking.currentBoundaryId = v;
227
+ },
228
+ configurable: true,
229
+ enumerable: true
230
+ });
231
+ context.registerModule = tracking.registerModule;
232
+ context.getBoundaryModules = tracking.getBoundaryModules;
233
+ if (typeof manifest === "function") {
234
+ context.resolveAssets = manifest;
235
+ } else if (manifest && typeof manifest.resolve === "function") {
236
+ context.resolveAssets = key => manifest.resolve(key);
237
+ if (typeof manifest.resolveSync === "function") {
238
+ context.resolveAssetsSync = key => manifest.resolveSync(key);
239
+ }
240
+ } else if (manifest) {
241
+ const resolve = moduleUrl => resolveAssets(moduleUrl, manifest);
242
+ context.resolveAssets = resolve;
243
+ context.resolveAssetsSync = resolve;
244
+ }
245
+ }
246
+ const REPLACE_SCRIPT = `function $df(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;_$HY.done?o.remove():o.replaceWith(n.content),n.remove(),_$HY.fe(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])}`;
247
+ function renderToStream(code, options = {}) {
248
+ let {
249
+ nonce,
250
+ onCompleteShell,
251
+ onCompleteAll,
252
+ renderId = "",
253
+ noScripts,
254
+ manifest
255
+ } = options;
256
+ let dispose;
257
+ const blockingPromises = new Set();
258
+ let headerEmitted = false;
259
+ const pushTask = task => {
260
+ if (noScripts) return;
261
+ if (!headerEmitted) {
262
+ headerEmitted = true;
263
+ tasks += getLocalHeaderScript(renderId);
264
+ }
265
+ tasks += task + ";";
266
+ if (!timer && firstFlushed) {
267
+ timer = setTimeout(writeTasks);
268
+ }
269
+ };
270
+ const onDone = () => {
271
+ writeTasks();
272
+ doShell();
273
+ onCompleteAll && onCompleteAll({
274
+ write(v) {
275
+ !completed && buffer.write(v);
276
+ }
277
+ });
278
+ writable && writable.end();
279
+ completed = true;
280
+ if (firstFlushed) dispose();
281
+ };
282
+ const sink = {
283
+ data(payload) {
284
+ pushTask(payload);
285
+ },
286
+ fragment(key, value, meta) {
287
+ const deferActivation = !!meta.revealGroup;
288
+ const styles = meta.styles;
289
+ for (let i = 0; i < styles.inline.length; i++) {
290
+ buffer.write(renderInlineStyle(styles.inline[i], nonce));
291
+ }
292
+ if (styles.links.length) {
293
+ emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
294
+ writeTasks();
295
+ for (const url of styles.links) {
296
+ buffer.write(`<link rel="stylesheet" href="${url}" onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
297
+ }
298
+ buffer.write(`<template id="${key}">${value}</template>`);
299
+ } else {
300
+ buffer.write(`<template id="${key}">${value}</template>`);
301
+ if (!deferActivation) {
302
+ emitTask(`$df("${key}")`);
303
+ }
304
+ }
305
+ },
306
+ reveal(keys, meta) {
307
+ emitTask(`${meta.fallback ? "$dflj" : "$dfj"}(${JSON.stringify(keys)})`);
308
+ },
309
+ asset(type, value) {
310
+ if (type === "module") {
311
+ buffer.write(`<link rel="modulepreload" href="${value}">`);
312
+ } else if (type === "inline-style") {
313
+ buffer.write(renderInlineStyle(value, nonce));
314
+ }
315
+ },
316
+ shell(shellHtml, meta) {
317
+ shellHtml = injectBeforeHead(shellHtml, meta.assets);
318
+ shellHtml = injectPreloadLinks(meta.preloads, shellHtml);
319
+ shellHtml = injectInlineStyles(meta.inlineStyles, shellHtml, nonce);
320
+ if (meta.tasks.length) shellHtml = injectScripts(shellHtml, meta.tasks, nonce);
321
+ buffer.write(shellHtml);
322
+ },
323
+ ...options.sink
324
+ };
325
+ const serializer = (options.serializer || createHydrationSerializer)({
326
+ scopeId: options.renderId,
327
+ plugins: options.plugins,
328
+ onData: payload => sink.data(payload),
329
+ onDone,
330
+ onError: options.onError
331
+ });
332
+ let rootAssetsSerialized = false;
333
+ const serializeRootAssets = () => {
334
+ if (rootAssetsSerialized) return;
335
+ rootAssetsSerialized = true;
336
+ serializeFragmentAssets("", tracking.boundaryModules, context);
337
+ };
338
+ const flushEnd = () => {
339
+ if (!registry.size) {
340
+ serializeRootAssets();
341
+ queue(() => queue(() => serializer.flush()));
342
+ }
343
+ };
344
+ const registry = new Map();
345
+ const writeTasks = () => {
346
+ if (tasks.length && !completed && firstFlushed) {
347
+ buffer.write(`<script${nonce ? ` nonce="${nonce}"` : ""}>${tasks}</script>`);
348
+ tasks = "";
349
+ }
350
+ timer && clearTimeout(timer);
351
+ timer = null;
352
+ };
353
+ let context;
354
+ let writable;
355
+ let tmp = "";
356
+ let tasks = "";
357
+ let firstFlushed = false;
358
+ let completed = false;
359
+ let shellCompleted = false;
360
+ let scriptFlushed = false;
361
+ let headStyles;
362
+ const revealGroups = new Map();
363
+ let timer = null;
364
+ const emitTask = task => {
365
+ pushTask(`${task}${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
366
+ scriptFlushed = true;
367
+ };
368
+ function resolveRevealKeys(groupOrKeys, release, consume) {
369
+ if (Array.isArray(groupOrKeys)) return groupOrKeys.slice();
370
+ let group = revealGroups.get(groupOrKeys);
371
+ if (!group) {
372
+ if (!release) return;
373
+ group = {
374
+ order: [],
375
+ keys: new Set(),
376
+ released: true
377
+ };
378
+ revealGroups.set(groupOrKeys, group);
379
+ } else if (release) group.released = true;
380
+ if (!group.order.length) return;
381
+ const keys = group.order.slice();
382
+ if (consume) revealGroups.delete(groupOrKeys);
383
+ return keys;
384
+ }
385
+ let rootHoles = null;
386
+ let nextHoleId = 0;
387
+ let buffer = {
388
+ write(payload) {
389
+ tmp += payload;
390
+ }
391
+ };
392
+ const tracking = createAssetTracking();
393
+ sharedConfig.context = context = {
394
+ async: true,
395
+ assets: [],
396
+ nonce,
397
+ registerAsset(type, value) {
398
+ if (type === "inline-style") {
399
+ const entry = tracking.registerInlineStyle(value);
400
+ if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
401
+ entry.emitted = true;
402
+ sink.asset("inline-style", entry);
403
+ }
404
+ return;
405
+ }
406
+ if (tracking.currentBoundaryId && type === "style") {
407
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
408
+ if (!styles) {
409
+ styles = new Set();
410
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
411
+ }
412
+ styles.add(value);
413
+ }
414
+ if (!tracking.emittedAssets.has(value)) {
415
+ tracking.emittedAssets.add(value);
416
+ if (firstFlushed) sink.asset(type, value);
417
+ }
418
+ },
419
+ block(p) {
420
+ if (!firstFlushed) blockingPromises.add(p);
421
+ },
422
+ replace(id, payloadFn) {
423
+ if (firstFlushed) return;
424
+ const placeholder = `<!--!$${id}-->`;
425
+ const first = html.indexOf(placeholder);
426
+ if (first === -1) return;
427
+ const last = html.indexOf(`<!--!$/${id}-->`, first + placeholder.length);
428
+ html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
429
+ },
430
+ serialize(id, p, deferStream) {
431
+ if (sharedConfig.context.noHydrate) return;
432
+ if (!firstFlushed && deferStream && typeof p === "object" && "then" in p) {
433
+ blockingPromises.add(p);
434
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
435
+ } else serializer.write(id, p);
436
+ },
437
+ escape: escape,
438
+ resolve: resolveSSRNode,
439
+ ssr: ssr,
440
+ registerFragment(key, options) {
441
+ const revealGroup = options && options.revealGroup;
442
+ if (revealGroup) {
443
+ let group = revealGroups.get(revealGroup);
444
+ if (!group) {
445
+ group = {
446
+ order: [],
447
+ keys: new Set(),
448
+ released: false
449
+ };
450
+ revealGroups.set(revealGroup, group);
451
+ }
452
+ if (!group.keys.has(key)) {
453
+ group.keys.add(key);
454
+ group.order.push(key);
455
+ }
456
+ if (group.released) {
457
+ throw new Error("registerFragment() for reveal group '" + revealGroup + "' was called after revealFragments(). Ensure template payload is emitted before grouped reveal.");
458
+ }
459
+ }
460
+ if (!registry.has(key)) {
461
+ let resolve, reject;
462
+ const p = new Promise((r, rej) => (resolve = r, reject = rej));
463
+ registry.set(key, {
464
+ resolve: err => queue(() => queue(() => {
465
+ err ? reject(err) : resolve(true);
466
+ queue(flushEnd);
467
+ }))
468
+ });
469
+ serializer.write(key + "_fr", p);
470
+ }
471
+ return (value, error) => {
472
+ if (registry.has(key)) {
473
+ const item = registry.get(key);
474
+ registry.delete(key);
475
+ if (item.children) {
476
+ for (const k in item.children) {
477
+ value = replacePlaceholder(value, k, item.children[k]);
478
+ }
479
+ }
480
+ const parentKey = waitForFragments(registry, key);
481
+ if (parentKey) {
482
+ const parent = registry.get(parentKey);
483
+ parent.children ||= {};
484
+ parent.children[key] = value !== undefined ? value : "";
485
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
486
+ propagateBoundaryStyles(key, parentKey, tracking);
487
+ item.resolve();
488
+ return;
489
+ }
490
+ if (!completed) {
491
+ if (!firstFlushed) {
492
+ queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
493
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
494
+ item.resolve(error);
495
+ } else {
496
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
497
+ const styles = collectStreamStyles(key, tracking, headStyles);
498
+ sink.fragment(key, value !== undefined ? value : " ", {
499
+ styles,
500
+ revealGroup,
501
+ error
502
+ });
503
+ item.resolve(error);
504
+ }
505
+ }
506
+ }
507
+ return firstFlushed;
508
+ };
509
+ },
510
+ revealFragments(groupOrKeys) {
511
+ const keys = resolveRevealKeys(groupOrKeys, true, true);
512
+ if (!keys) return;
513
+ sink.reveal(keys, {
514
+ fallback: false
515
+ });
516
+ },
517
+ revealFallbacks(groupOrKeys) {
518
+ const keys = resolveRevealKeys(groupOrKeys, false, false);
519
+ if (!keys) return;
520
+ sink.reveal(keys, {
521
+ fallback: true
522
+ });
523
+ }
524
+ };
525
+ applyAssetTracking(context, tracking, manifest);
526
+ registerEntryAssets(manifest);
527
+ let html = createRoot(d => {
528
+ dispose = d;
529
+ const res = resolveSSRNode(escape(code()));
530
+ if (!res.h.length) return res.t[0];
531
+ rootHoles = [];
532
+ let out = res.t[0];
533
+ for (let i = 0; i < res.h.length; i++) {
534
+ const id = nextHoleId++;
535
+ rootHoles.push({
536
+ id,
537
+ fn: res.h[i]
538
+ });
539
+ out += `<!--rh${id}-->` + res.t[i + 1];
540
+ }
541
+ for (const p of res.p) blockingPromises.add(p);
542
+ return out;
543
+ }, {
544
+ id: renderId
545
+ });
546
+ function resolveRootHoles() {
547
+ if (!rootHoles) return true;
548
+ const pending = [];
549
+ for (const {
550
+ id,
551
+ fn
552
+ } of rootHoles) {
553
+ const marker = `<!--rh${id}-->`;
554
+ const res = resolveSSRNode(fn);
555
+ if (!res.h.length) {
556
+ html = html.replace(marker, res.t[0]);
557
+ } else {
558
+ let out = res.t[0];
559
+ for (let j = 0; j < res.h.length; j++) {
560
+ const newId = nextHoleId++;
561
+ pending.push({
562
+ id: newId,
563
+ fn: res.h[j]
564
+ });
565
+ out += `<!--rh${newId}-->` + res.t[j + 1];
566
+ }
567
+ html = html.replace(marker, out);
568
+ for (const p of res.p) blockingPromises.add(p);
569
+ }
570
+ }
571
+ if (pending.length) {
572
+ rootHoles = pending;
573
+ return false;
574
+ }
575
+ rootHoles = null;
576
+ return true;
577
+ }
578
+ function doShell() {
579
+ if (shellCompleted) return;
580
+ if (!resolveRootHoles()) return;
581
+ sharedConfig.context = context;
582
+ const assetsHtml = resolveAssetsHtml(context.assets);
583
+ headStyles = new Set();
584
+ for (const url of tracking.emittedAssets) {
585
+ if (url.endsWith(".css")) headStyles.add(url);
586
+ }
587
+ serializeRootAssets();
588
+ sink.shell(html, {
589
+ assets: assetsHtml,
590
+ preloads: tracking.emittedAssets,
591
+ inlineStyles: tracking.inlineStyles,
592
+ tasks
593
+ });
594
+ tasks = "";
595
+ onCompleteShell && onCompleteShell({
596
+ write(v) {
597
+ !completed && buffer.write(v);
598
+ }
599
+ });
600
+ shellCompleted = true;
601
+ }
602
+ return {
603
+ then(fn) {
604
+ function complete() {
605
+ dispose();
606
+ fn(tmp);
607
+ }
608
+ if (onCompleteAll) {
609
+ let ogComplete = onCompleteAll;
610
+ onCompleteAll = options => {
611
+ ogComplete(options);
612
+ complete();
613
+ };
614
+ } else onCompleteAll = complete;
615
+ function flush() {
616
+ allSettled(blockingPromises).then(() => {
617
+ setTimeout(() => {
618
+ if (!resolveRootHoles()) return flush();
619
+ queue(flushEnd);
620
+ });
621
+ });
622
+ }
623
+ flush();
624
+ },
625
+ pipe(w) {
626
+ function flush() {
627
+ allSettled(blockingPromises).then(() => {
628
+ setTimeout(() => {
629
+ doShell();
630
+ if (!shellCompleted) return flush();
631
+ buffer = writable = w;
632
+ buffer.write(tmp);
633
+ firstFlushed = true;
634
+ if (completed) {
635
+ dispose();
636
+ writable.end();
637
+ } else flushEnd();
638
+ });
639
+ });
640
+ }
641
+ flush();
642
+ },
643
+ pipeTo(w) {
644
+ let resolve;
645
+ const p = new Promise(r => resolve = r);
646
+ function flush() {
647
+ allSettled(blockingPromises).then(() => {
648
+ setTimeout(() => {
649
+ doShell();
650
+ if (!shellCompleted) return flush();
651
+ const encoder = new TextEncoder();
652
+ const writer = w.getWriter();
653
+ writable = {
654
+ end() {
655
+ writer.releaseLock();
656
+ w.close().catch(() => {});
657
+ resolve();
658
+ }
659
+ };
660
+ buffer = {
661
+ write(payload) {
662
+ writer.write(encoder.encode(payload)).catch(() => {});
663
+ }
664
+ };
665
+ buffer.write(tmp);
666
+ firstFlushed = true;
667
+ if (completed) {
668
+ dispose();
669
+ writable.end();
670
+ } else flushEnd();
671
+ });
672
+ });
673
+ }
674
+ flush();
675
+ return p;
676
+ }
677
+ };
678
+ }
679
+ function buildAsyncWrap(err, node) {
680
+ const p = ssrHandleError(err);
681
+ if (!p) return null;
682
+ const owner = getOwner();
683
+ return {
684
+ fn: owner ? () => runWithOwner(owner, node) : node,
685
+ p
686
+ };
687
+ }
688
+ function ssrFirstGroupHit(hole) {
689
+ try {
690
+ return hole();
691
+ } catch (err) {
692
+ return buildAsyncWrap(err, hole);
693
+ }
694
+ }
695
+ function tryResolveFunctionHole(hole) {
696
+ let value;
697
+ try {
698
+ value = hole();
699
+ } catch (err) {
700
+ return buildAsyncWrap(err, hole) || "";
701
+ }
702
+ const t = typeof value;
703
+ if (t === "string") return value;
704
+ if (t === "number") return "" + value;
705
+ if (value == null || t === "boolean") return "";
706
+ return tryResolveString(value);
707
+ }
708
+ function mergeTemplateInto(result, node) {
709
+ result.t[result.t.length - 1] += node.t[0];
710
+ if (node.t.length > 1) {
711
+ result.t.push(...node.t.slice(1));
712
+ result.h.push(...node.h);
713
+ result.p.push(...node.p);
714
+ }
715
+ }
716
+ function appendResolvedNode(result, node) {
717
+ if (node.fn !== undefined) {
718
+ result.h.push(node.fn);
719
+ result.p.push(node.p);
720
+ result.t.push("");
721
+ } else if (node.merge !== undefined) mergeTemplateInto(result, node.merge);else resolveSSRNode(node.bail, result);
722
+ }
723
+ let _lastGroupFn = null;
724
+ let _lastGroupArr = null;
725
+ let _lastGroupErr = null;
726
+ function ssrGroupSlot(fn, idx) {
727
+ return () => {
728
+ if (idx > 0 && _lastGroupFn === fn) {
729
+ if (_lastGroupArr !== null) return _lastGroupArr[idx];
730
+ throw _lastGroupErr;
731
+ }
732
+ _lastGroupFn = fn;
733
+ _lastGroupArr = null;
734
+ _lastGroupErr = null;
735
+ try {
736
+ _lastGroupArr = fn();
737
+ return _lastGroupArr[idx];
738
+ } catch (err) {
739
+ _lastGroupErr = err;
740
+ throw err;
741
+ }
742
+ };
743
+ }
744
+ function ssr(t) {
745
+ const len = arguments.length;
746
+ if (len === 1) return {
747
+ t
748
+ };
749
+ let s = t[0];
750
+ let result = null;
751
+ let lastGroup = null;
752
+ let lastGroupVal = null;
753
+ let lastGroupIdx = 0;
754
+ for (let i = 1; i < len; i++) {
755
+ const hole = arguments[i];
756
+ const ht = typeof hole;
757
+ if (ht === "string") {
758
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
759
+ } else if (ht === "number") {
760
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
761
+ } else if (hole == null || ht === "boolean") ; else if (ht === "function" && hole.$g) {
762
+ let value;
763
+ let hasValue = false;
764
+ if (lastGroup !== hole) {
765
+ const r = ssrFirstGroupHit(hole);
766
+ if (r !== null) {
767
+ lastGroup = hole;
768
+ lastGroupVal = r;
769
+ lastGroupIdx = 0;
770
+ if (!Array.isArray(r) && result === null) {
771
+ result = {
772
+ t: [s],
773
+ h: [],
774
+ p: []
775
+ };
776
+ s = "";
777
+ }
778
+ }
779
+ }
780
+ if (lastGroup === hole) {
781
+ if (Array.isArray(lastGroupVal)) {
782
+ value = lastGroupVal[lastGroupIdx++];
783
+ hasValue = true;
784
+ } else {
785
+ result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
786
+ result.p.push(lastGroupVal.p);
787
+ result.t.push("");
788
+ }
789
+ }
790
+ if (hasValue) {
791
+ const vt = typeof value;
792
+ if (vt === "string" || vt === "number") {
793
+ if (result === null) s += value;else result.t[result.t.length - 1] += value;
794
+ } else if (value == null || vt === "boolean") ; else if (result !== null) {
795
+ resolveSSRNode(value, result);
796
+ } else {
797
+ const rs = tryResolveString(value);
798
+ if (typeof rs === "string") {
799
+ s += rs;
800
+ } else {
801
+ result = {
802
+ t: [s],
803
+ h: [],
804
+ p: []
805
+ };
806
+ s = "";
807
+ if (rs.merge !== undefined) mergeTemplateInto(result, rs.merge);else resolveSSRNode(rs.bail, result);
808
+ }
809
+ }
810
+ }
811
+ } else if (result !== null) {
812
+ resolveSSRNode(hole, result);
813
+ } else if (ht === "function") {
814
+ const r = tryResolveFunctionHole(hole);
815
+ if (typeof r === "string") s += r;else {
816
+ result = {
817
+ t: [s],
818
+ h: [],
819
+ p: []
820
+ };
821
+ s = "";
822
+ appendResolvedNode(result, r);
823
+ }
824
+ } else {
825
+ const r = tryResolveString(hole);
826
+ if (typeof r === "string") {
827
+ s += r;
828
+ } else {
829
+ result = {
830
+ t: [s],
831
+ h: [],
832
+ p: []
833
+ };
834
+ s = "";
835
+ appendResolvedNode(result, r);
836
+ }
837
+ }
838
+ const next = t[i];
839
+ if (result === null) s += next;else result.t[result.t.length - 1] += next;
840
+ }
841
+ if (result === null) return {
842
+ t: s
843
+ };
844
+ return result;
845
+ }
846
+ function escape(s, attr) {
847
+ const t = typeof s;
848
+ if (t !== "string") {
849
+ if (!attr && Array.isArray(s)) {
850
+ const joined = tryJoinPlainSSRArray(s);
851
+ if (joined !== undefined) return joined;
852
+ s = s.slice();
853
+ for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
854
+ return s;
855
+ }
856
+ if (attr) {
857
+ if (s == null || t === "boolean" || t === "number") return s;
858
+ return escape(String(s), attr);
859
+ }
860
+ return s;
861
+ }
862
+ const delimCode = attr ? 34 : 60;
863
+ const len = s.length;
864
+ for (let i = 0; i < len; i++) {
865
+ const c = s.charCodeAt(i);
866
+ if (c === 38 || c === delimCode) return escapeSlow(s, attr, i);
867
+ }
868
+ return s;
869
+ }
870
+ function escapeSlow(s, attr, start) {
871
+ const delim = attr ? '"' : "<";
872
+ const delimCode = attr ? 34 : 60;
873
+ const escDelim = attr ? "&quot;" : "&lt;";
874
+ const c0 = s.charCodeAt(start);
875
+ let iDelim = c0 === delimCode ? start : s.indexOf(delim, start);
876
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
877
+ let left = 0,
878
+ out = "";
879
+ while (iDelim >= 0 && iAmp >= 0) {
880
+ if (iDelim < iAmp) {
881
+ if (left < iDelim) out += s.substring(left, iDelim);
882
+ out += escDelim;
883
+ left = iDelim + 1;
884
+ iDelim = s.indexOf(delim, left);
885
+ } else {
886
+ if (left < iAmp) out += s.substring(left, iAmp);
887
+ out += "&amp;";
888
+ left = iAmp + 1;
889
+ iAmp = s.indexOf("&", left);
890
+ }
891
+ }
892
+ if (iDelim >= 0) {
893
+ do {
894
+ if (left < iDelim) out += s.substring(left, iDelim);
895
+ out += escDelim;
896
+ left = iDelim + 1;
897
+ iDelim = s.indexOf(delim, left);
898
+ } while (iDelim >= 0);
899
+ } else while (iAmp >= 0) {
900
+ if (left < iAmp) out += s.substring(left, iAmp);
901
+ out += "&amp;";
902
+ left = iAmp + 1;
903
+ iAmp = s.indexOf("&", left);
904
+ }
905
+ return left < s.length ? out + s.substring(left) : out;
906
+ }
907
+ function tryJoinPlainSSRArray(nodes) {
908
+ if (nodes.length === 0) return undefined;
909
+ let out = "";
910
+ for (let i = 0, len = nodes.length; i < len; i++) {
911
+ const node = nodes[i];
912
+ if (node == null || typeof node !== "object" || node.h || typeof node.t !== "string") {
913
+ return undefined;
914
+ }
915
+ out += node.t;
916
+ }
917
+ return out;
918
+ }
919
+ function queue(fn) {
920
+ return Promise.resolve().then(fn);
921
+ }
922
+ function allSettled(promises) {
923
+ let size = promises.size;
924
+ return Promise.allSettled(promises).then(() => {
925
+ if (promises.size !== size) return allSettled(promises);
926
+ return;
927
+ });
928
+ }
929
+ function resolveAssetsHtml(assets) {
930
+ if (!assets || !assets.length) return "";
931
+ let out = "";
932
+ for (let i = 0, len = assets.length; i < len; i++) out += assets[i]();
933
+ return out;
934
+ }
935
+ function injectBeforeHead(html, content) {
936
+ if (!content) return html;
937
+ const index = html.indexOf("</head>");
938
+ if (index === -1) return html;
939
+ return html.slice(0, index) + content + html.slice(index);
940
+ }
941
+ function injectPreloadLinks(emittedAssets, html, nonce) {
942
+ if (!emittedAssets.size) return html;
943
+ let links = "";
944
+ for (const url of emittedAssets) {
945
+ if (url.endsWith(".css")) {
946
+ links += `<link rel="stylesheet" href="${url}">`;
947
+ } else {
948
+ links += `<link rel="modulepreload" href="${url}">`;
949
+ }
950
+ }
951
+ const index = html.indexOf("</head>");
952
+ if (index === -1) return html;
953
+ return html.slice(0, index) + links + html.slice(index);
954
+ }
955
+ function serializeFragmentAssets(key, boundaryModules, context) {
956
+ const map = boundaryModules.get(key);
957
+ if (!map || !Object.keys(map).length) return;
958
+ context.serialize(key + "_assets", map);
959
+ }
960
+ function propagateBoundaryStyles(childKey, parentKey, tracking) {
961
+ const childStyles = tracking.getBoundaryStyles(childKey);
962
+ if (!childStyles) return;
963
+ let parentStyles = tracking.boundaryStyles.get(parentKey);
964
+ if (!parentStyles) {
965
+ parentStyles = new Set();
966
+ tracking.boundaryStyles.set(parentKey, parentStyles);
967
+ }
968
+ for (const url of childStyles) {
969
+ parentStyles.add(url);
970
+ }
971
+ }
972
+ function collectStreamStyles(key, tracking, headStyles) {
973
+ const styles = tracking.getBoundaryStyles(key);
974
+ const links = [];
975
+ const inline = [];
976
+ if (!styles) return {
977
+ links,
978
+ inline
979
+ };
980
+ for (const entry of styles) {
981
+ if (typeof entry === "string") {
982
+ if (!headStyles || !headStyles.has(entry)) links.push(entry);
983
+ } else if (!entry.emitted) {
984
+ entry.emitted = true;
985
+ inline.push(entry);
986
+ }
987
+ }
988
+ return {
989
+ links,
990
+ inline
991
+ };
992
+ }
993
+ function escapeStyleContent(content) {
994
+ return content.replace(/<\/(style)/gi, "<\\/$1");
995
+ }
996
+ function renderInlineStyle(entry, nonce) {
997
+ let attrs = "";
998
+ if (entry.attrs) {
999
+ for (const name in entry.attrs) {
1000
+ attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
1001
+ }
1002
+ }
1003
+ return `<style${nonce ? ` nonce="${nonce}"` : ""} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
1004
+ }
1005
+ function injectInlineStyles(inlineStyles, html, nonce) {
1006
+ if (!inlineStyles.size) return html;
1007
+ const index = html.indexOf("</head>");
1008
+ if (index === -1) return html;
1009
+ let out = "";
1010
+ for (const entry of inlineStyles.values()) {
1011
+ if (entry.emitted) continue;
1012
+ entry.emitted = true;
1013
+ out += renderInlineStyle(entry, nonce);
1014
+ }
1015
+ return out ? html.slice(0, index) + out + html.slice(index) : html;
1016
+ }
1017
+ function injectScripts(html, scripts, nonce) {
1018
+ const tag = `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>`;
1019
+ const index = html.indexOf("<!--xs-->");
1020
+ if (index > -1) {
1021
+ return html.slice(0, index) + tag + html.slice(index);
1022
+ }
1023
+ return html + tag;
1024
+ }
1025
+ function waitForFragments(registry, key) {
1026
+ for (const k of [...registry.keys()].reverse()) {
1027
+ if (key.startsWith(k)) return k;
1028
+ }
1029
+ return false;
1030
+ }
1031
+ function replacePlaceholder(html, key, value) {
1032
+ const marker = `<template id="pl-${key}">`;
1033
+ const close = `<!--pl-${key}-->`;
1034
+ const first = html.indexOf(marker);
1035
+ if (first === -1) return html;
1036
+ const last = html.indexOf(close, first + marker.length);
1037
+ return html.slice(0, first) + value + html.slice(last + close.length);
1038
+ }
1039
+ function tryResolveString(node) {
1040
+ const t = typeof node;
1041
+ if (t === "string") return node;
1042
+ if (t === "number") return "" + node;
1043
+ if (node == null || t === "boolean") return "";
1044
+ if (t === "object") {
1045
+ if (Array.isArray(node)) {
1046
+ const joined = tryJoinPlainSSRArray(node);
1047
+ if (joined !== undefined) return joined;
1048
+ let s = "";
1049
+ let prevNonObj = false;
1050
+ for (let i = 0, len = node.length; i < len; i++) {
1051
+ const item = node[i];
1052
+ const itemNonObj = item !== null && typeof item !== "object";
1053
+ if (prevNonObj && itemNonObj) s += "<!--!$-->";
1054
+ prevNonObj = itemNonObj;
1055
+ const r = tryResolveString(item);
1056
+ if (typeof r !== "string") return {
1057
+ bail: node
1058
+ };
1059
+ s += r;
1060
+ }
1061
+ return s;
1062
+ }
1063
+ if (node.h && node.h.length > 0) return {
1064
+ merge: node
1065
+ };
1066
+ if (node.t === undefined) {
1067
+ console.warn(`Unrecognized value. Skipped inserting`, node);
1068
+ return "";
1069
+ }
1070
+ return Array.isArray(node.t) ? node.t[0] : node.t;
1071
+ }
1072
+ if (t === "function") {
1073
+ let v;
1074
+ try {
1075
+ v = node();
1076
+ } catch (err) {
1077
+ return buildAsyncWrap(err, node) || "";
1078
+ }
1079
+ return tryResolveString(v);
1080
+ }
1081
+ return "";
1082
+ }
1083
+ function resolveSSRNode(node, result = {
1084
+ t: [""],
1085
+ h: [],
1086
+ p: []
1087
+ }, top) {
1088
+ const t = typeof node;
1089
+ if (t === "string" || t === "number") {
1090
+ result.t[result.t.length - 1] += node;
1091
+ } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
1092
+ let prevNonObj = false;
1093
+ for (let i = 0, len = node.length; i < len; i++) {
1094
+ const item = node[i];
1095
+ const itemNonObj = item !== null && typeof item !== "object";
1096
+ if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
1097
+ prevNonObj = itemNonObj;
1098
+ resolveSSRNode(item, result);
1099
+ }
1100
+ } else if (t === "object") {
1101
+ if (node.h) {
1102
+ result.t[result.t.length - 1] += node.t[0];
1103
+ if (node.t.length > 1) {
1104
+ result.t.push(...node.t.slice(1));
1105
+ result.h.push(...node.h);
1106
+ result.p.push(...node.p);
1107
+ }
1108
+ } else if (node.t !== undefined) {
1109
+ result.t[result.t.length - 1] += node.t;
1110
+ } else console.warn(`Unrecognized value. Skipped inserting`, node);
1111
+ } else if (t === "function") {
1112
+ try {
1113
+ resolveSSRNode(node(), result);
1114
+ } catch (err) {
1115
+ const wrap = buildAsyncWrap(err, node);
1116
+ if (wrap) {
1117
+ result.h.push(wrap.fn);
1118
+ result.p.push(wrap.p);
1119
+ result.t.push("");
1120
+ }
1121
+ }
1122
+ }
1123
+ return result;
1124
+ }
1125
+ function resolveSSRSync(node) {
1126
+ const res = resolveSSRNode(node);
1127
+ if (!res.h.length) return res.t[0];
1128
+ throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
1129
+ }
1130
+
1131
+ function createChunk(data) {
1132
+ const encodeData = new TextEncoder().encode(data);
1133
+ const bytes = encodeData.length;
1134
+ const baseHex = bytes.toString(16);
1135
+ const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex;
1136
+ const head = new TextEncoder().encode(`;0x${totalHex};`);
1137
+ const chunk = new Uint8Array(12 + bytes);
1138
+ chunk.set(head);
1139
+ chunk.set(encodeData, 12);
1140
+ return chunk;
1141
+ }
1142
+
1143
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
1144
+ function isResponseEnvelope(value) {
1145
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
1146
+ }
1147
+
1148
+ const FRAME_STREAM_HEADER = "X-Frame-Stream";
1149
+ function isFrameStreamResponse(response) {
1150
+ return response.headers.has(FRAME_STREAM_HEADER);
1151
+ }
1152
+
1153
+ function serverOwned(render) {
1154
+ return NoHydration ? NoHydration({
1155
+ get children() {
1156
+ return render();
1157
+ }
1158
+ }) : render();
1159
+ }
1160
+ function createFrameSink(emit, frame) {
1161
+ const {
1162
+ id,
1163
+ version
1164
+ } = frame;
1165
+ const styledKeys = new Set();
1166
+ return {
1167
+ shell(html, meta = {}) {
1168
+ if (meta.preloads && meta.preloads.size) {
1169
+ const styles = [];
1170
+ const modules = [];
1171
+ for (const url of meta.preloads) {
1172
+ (url.endsWith(".css") ? styles : modules).push(url);
1173
+ }
1174
+ const chunk = {
1175
+ type: "assets",
1176
+ id,
1177
+ version,
1178
+ key: ""
1179
+ };
1180
+ if (styles.length) chunk.styles = styles;
1181
+ if (modules.length) chunk.modules = modules;
1182
+ emit(chunk);
1183
+ }
1184
+ emit({
1185
+ type: "html",
1186
+ id,
1187
+ version,
1188
+ html
1189
+ });
1190
+ },
1191
+ data(record) {
1192
+ if (record && typeof record.key === "string" && (record.key.endsWith("_fr") || /^\d+$/.test(record.key))) {
1193
+ return;
1194
+ }
1195
+ if (typeof record === "string") {
1196
+ emit({
1197
+ type: "data",
1198
+ id,
1199
+ version,
1200
+ payload: record
1201
+ });
1202
+ } else {
1203
+ emit({
1204
+ type: "data",
1205
+ id,
1206
+ version,
1207
+ key: record.key,
1208
+ node: record.node,
1209
+ initial: record.initial
1210
+ });
1211
+ }
1212
+ },
1213
+ fragment(key, value, meta = {}) {
1214
+ const links = meta.styles && meta.styles.links || [];
1215
+ const inline = meta.styles && meta.styles.inline || [];
1216
+ if (links.length || inline.length) {
1217
+ if (links.length) styledKeys.add(key);
1218
+ const chunk = {
1219
+ type: "assets",
1220
+ id,
1221
+ version,
1222
+ key
1223
+ };
1224
+ if (links.length) chunk.styles = links;
1225
+ if (inline.length) {
1226
+ chunk.inlineStyles = inline.map(e => ({
1227
+ id: e.id,
1228
+ content: e.content,
1229
+ attrs: e.attrs
1230
+ }));
1231
+ }
1232
+ emit(chunk);
1233
+ }
1234
+ emit({
1235
+ type: "fragment",
1236
+ id,
1237
+ version,
1238
+ key,
1239
+ html: value
1240
+ });
1241
+ if (meta.error) {
1242
+ emit({
1243
+ type: "error",
1244
+ id,
1245
+ version,
1246
+ key,
1247
+ error: {
1248
+ message: String(meta.error && meta.error.message || meta.error)
1249
+ }
1250
+ });
1251
+ }
1252
+ if (!meta.revealGroup) {
1253
+ emit({
1254
+ type: "reveal",
1255
+ id,
1256
+ version,
1257
+ keys: [key],
1258
+ waitForStyles: !!links.length
1259
+ });
1260
+ }
1261
+ },
1262
+ reveal(keys, meta = {}) {
1263
+ let waitForStyles = false;
1264
+ for (const key of keys) if (styledKeys.has(key)) waitForStyles = true;
1265
+ const chunk = {
1266
+ type: "reveal",
1267
+ id,
1268
+ version,
1269
+ keys,
1270
+ waitForStyles
1271
+ };
1272
+ if (meta.fallback) chunk.fallback = true;
1273
+ emit(chunk);
1274
+ },
1275
+ asset(type, url) {
1276
+ if (type !== "module") return;
1277
+ emit({
1278
+ type: "assets",
1279
+ id,
1280
+ version,
1281
+ key: "",
1282
+ modules: [url]
1283
+ });
1284
+ },
1285
+ end() {
1286
+ emit({
1287
+ type: "complete",
1288
+ id,
1289
+ version
1290
+ });
1291
+ },
1292
+ error(errorId, error) {
1293
+ emit({
1294
+ type: "error",
1295
+ id,
1296
+ version,
1297
+ key: errorId,
1298
+ error
1299
+ });
1300
+ },
1301
+ slot(key, args) {
1302
+ emit({
1303
+ type: "slot",
1304
+ id,
1305
+ version,
1306
+ key,
1307
+ args
1308
+ });
1309
+ },
1310
+ region(childId, html) {
1311
+ emit({
1312
+ type: "html",
1313
+ id: childId,
1314
+ version,
1315
+ html
1316
+ });
1317
+ }
1318
+ };
1319
+ }
1320
+ function renderToFrameStream(code, options = {}) {
1321
+ return frameStream(() => code, options);
1322
+ }
1323
+ function renderServerComponent(component, options = {}) {
1324
+ return frameStream((sink, frame) => {
1325
+ const props = createSlotProps(sink, frame);
1326
+ return () => component(props);
1327
+ }, options);
1328
+ }
1329
+ function frameStream(makeCode, options) {
1330
+ const {
1331
+ id = "",
1332
+ version = 1
1333
+ } = options.frame || {};
1334
+ const frame = {
1335
+ id,
1336
+ version
1337
+ };
1338
+ function stream(w) {
1339
+ const emit = chunk => w.write(chunk);
1340
+ const sink = createFrameSink(emit, frame);
1341
+ emit({
1342
+ type: "start",
1343
+ id,
1344
+ version
1345
+ });
1346
+ const code = makeCode(sink, frame);
1347
+ try {
1348
+ renderToStream(() => serverOwned(code), {
1349
+ serializer: createJSONSerializer,
1350
+ ...options,
1351
+ sink
1352
+ }).pipe({
1353
+ write() {},
1354
+ end() {
1355
+ sink.end();
1356
+ w.end && w.end();
1357
+ }
1358
+ });
1359
+ } catch (err) {
1360
+ sink.error("", err instanceof Error ? err.message : String(err));
1361
+ sink.end();
1362
+ w.end && w.end();
1363
+ }
1364
+ }
1365
+ return {
1366
+ pipe: stream,
1367
+ then(onFulfilled, onRejected) {
1368
+ return new Promise((resolve, reject) => {
1369
+ const chunks = [];
1370
+ try {
1371
+ stream({
1372
+ write: chunk => chunks.push(chunk),
1373
+ end: () => resolve(chunks)
1374
+ });
1375
+ } catch (err) {
1376
+ reject(err);
1377
+ }
1378
+ }).then(onFulfilled, onRejected);
1379
+ }
1380
+ };
1381
+ }
1382
+ function slotRange(occurrence) {
1383
+ return {
1384
+ t: `<!--slot:${occurrence}:start--><!--slot:${occurrence}:end-->`
1385
+ };
1386
+ }
1387
+ function createDocumentSlotProps(clientProps, frameId) {
1388
+ const counts = Object.create(null);
1389
+ const getters = new Map();
1390
+ const range = (occurrence, content) => [{
1391
+ t: `<!--slot:${occurrence}:start-->`
1392
+ }, content, {
1393
+ t: `<!--slot:${occurrence}:end-->`
1394
+ }];
1395
+ const zoneOwner = getOwner ? getOwner() : null;
1396
+ const scoped = (occurrence, render) => {
1397
+ const id = `sc-${frameId}-${occurrence}-`;
1398
+ const run = () => Hydration ? Hydration({
1399
+ id,
1400
+ get children() {
1401
+ return render();
1402
+ }
1403
+ }) : runWithHydrationScope(id, render);
1404
+ return zoneOwner ? runWithOwner(zoneOwner, run) : run();
1405
+ };
1406
+ return new Proxy(Object.create(null), {
1407
+ has() {
1408
+ return true;
1409
+ },
1410
+ get(_, prop) {
1411
+ if (typeof prop !== "string") return undefined;
1412
+ if (prop === "then") return undefined;
1413
+ let fn = getters.get(prop);
1414
+ if (!fn) {
1415
+ fn = (...callArgs) => {
1416
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
1417
+ return scoped(prop, () => {
1418
+ const value = clientProps[prop];
1419
+ return range(prop, typeof value === "function" ? value() : value);
1420
+ });
1421
+ }
1422
+ const raw = callArgs[0];
1423
+ let occurrence;
1424
+ const k = raw.$key;
1425
+ if (typeof k === "string" || typeof k === "number") {
1426
+ occurrence = `${prop}#${k}`;
1427
+ } else {
1428
+ const n = counts[prop] || 0;
1429
+ counts[prop] = n + 1;
1430
+ occurrence = `${prop}#${n}`;
1431
+ }
1432
+ const slot = clientProps[prop];
1433
+ if (typeof slot !== "function") return range(occurrence, undefined);
1434
+ const resolved = {};
1435
+ const regions = [];
1436
+ for (const key of Object.keys(raw)) {
1437
+ const value = raw[key];
1438
+ if (key !== "$key" && isServerContent(value)) {
1439
+ const childId = `${frameId}.${occurrence}.${key}`;
1440
+ const region = {
1441
+ key,
1442
+ childId,
1443
+ value,
1444
+ used: false
1445
+ };
1446
+ regions.push(region);
1447
+ resolved[key] = () => {
1448
+ region.used = true;
1449
+ return [{
1450
+ t: `<!--frame:${childId}:start-->`
1451
+ }, value, {
1452
+ t: `<!--frame:${childId}:end-->`
1453
+ }];
1454
+ };
1455
+ } else {
1456
+ resolved[key] = value;
1457
+ }
1458
+ }
1459
+ const out = scoped(occurrence, () => range(occurrence, slot(resolved)));
1460
+ const unused = regions.filter(r => !r.used);
1461
+ if (sharedConfig.context) {
1462
+ const rendered = renderedHtmlOf(out);
1463
+ const args = {};
1464
+ let any = false;
1465
+ for (const key of Object.keys(raw)) {
1466
+ const value = raw[key];
1467
+ if (key === "$key") continue;
1468
+ const region = regions.find(r => r.key === key);
1469
+ if (region) {
1470
+ if (!region.used) {
1471
+ args[key] = {
1472
+ $frame: region.childId
1473
+ };
1474
+ any = true;
1475
+ }
1476
+ continue;
1477
+ }
1478
+ if (isServerContent(value)) continue;
1479
+ const t = typeof value;
1480
+ if ((t === "string" || t === "number") && rendered !== null) {
1481
+ const needle = t === "string" ? sharedConfig.context.escape(String(value)) : String(value);
1482
+ if (needle !== "" && rendered.includes(needle)) continue;
1483
+ }
1484
+ args[key] = value;
1485
+ any = true;
1486
+ }
1487
+ if (any) sharedConfig.context.serialize(`sc:slot:${frameId}:${occurrence}`, args);
1488
+ for (const region of unused) {
1489
+ sharedConfig.context.serialize(`sc:region:${region.childId}`, resolveRegionHtml(sharedConfig.context, region.value));
1490
+ }
1491
+ }
1492
+ return out;
1493
+ };
1494
+ getters.set(prop, fn);
1495
+ }
1496
+ return fn;
1497
+ }
1498
+ });
1499
+ }
1500
+ function frameTransformDirectResult(value, {
1501
+ id
1502
+ }) {
1503
+ if (typeof value !== "function") return value;
1504
+ const component = value;
1505
+ const wrapped = props => [{
1506
+ t: `<!--frame:${id}:start-->`
1507
+ }, serverOwned(() => component(createDocumentSlotProps(props, id))), {
1508
+ t: `<!--frame:${id}:end-->`
1509
+ }];
1510
+ wrapped[SERVER_COMPONENT] = id;
1511
+ return wrapped;
1512
+ }
1513
+ function renderedHtmlOf(out) {
1514
+ try {
1515
+ const res = sharedConfig.context.resolve(out);
1516
+ if (res && res.t && (!res.h || !res.h.length)) {
1517
+ return res.t[0].replace(/<!--[^>]*-->/g, "");
1518
+ }
1519
+ } catch (e) {}
1520
+ return null;
1521
+ }
1522
+ function resolveRegionHtml(ctx, node) {
1523
+ const res = ctx.resolve(node);
1524
+ if (!res || !res.t) return String(res ?? "");
1525
+ if (!res.h || !res.h.length) return res.t[0];
1526
+ return Promise.all(res.p).then(() => {
1527
+ let out = Promise.resolve(res.t[0]);
1528
+ for (let i = 0; i < res.h.length; i++) {
1529
+ const hole = res.h[i];
1530
+ const tail = res.t[i + 1];
1531
+ out = out.then(acc => Promise.resolve(resolveRegionHtml(ctx, hole)).then(part => acc + part + tail));
1532
+ }
1533
+ return out;
1534
+ });
1535
+ }
1536
+ const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("dom-expressions.server-component");
1537
+ const ServerComponentPlugin = /*#__PURE__*/createPlugin({
1538
+ tag: "dom-expressions/server-component",
1539
+ test(value) {
1540
+ return typeof value === "function" && SERVER_COMPONENT in value;
1541
+ },
1542
+ parse: {
1543
+ sync(value, ctx) {
1544
+ return {
1545
+ id: ctx.parse(value[SERVER_COMPONENT])
1546
+ };
1547
+ },
1548
+ async async(value, ctx) {
1549
+ return {
1550
+ id: await ctx.parse(value[SERVER_COMPONENT])
1551
+ };
1552
+ },
1553
+ stream(value, ctx) {
1554
+ return {
1555
+ id: ctx.parse(value[SERVER_COMPONENT])
1556
+ };
1557
+ }
1558
+ },
1559
+ serialize(node, ctx) {
1560
+ return "self._$SC.r(" + ctx.serialize(node.id) + ")";
1561
+ },
1562
+ deserialize(node, ctx) {
1563
+ return globalThis._$SC.r(ctx.deserialize(node.id));
1564
+ }
1565
+ });
1566
+ const SERVER_COMPONENT_BOOTSTRAP = "self._$SC={c:{},r(i){return this.c[i]||(this.c[i]=(p)=>self._$SC.impl(i,p))}};";
1567
+ function isServerContent(value) {
1568
+ if (value && typeof value === "object") {
1569
+ if ("t" in value) return true;
1570
+ if (Array.isArray(value) && value.length > 0) {
1571
+ for (const item of value) {
1572
+ if (!(item && typeof item === "object" && "t" in item)) return false;
1573
+ }
1574
+ return true;
1575
+ }
1576
+ }
1577
+ return false;
1578
+ }
1579
+ function createSlotProps(sink, frame) {
1580
+ const counts = Object.create(null);
1581
+ const getters = new Map();
1582
+ return new Proxy(Object.create(null), {
1583
+ has() {
1584
+ return true;
1585
+ },
1586
+ get(_, prop) {
1587
+ if (typeof prop !== "string") return undefined;
1588
+ if (prop === "then") return undefined;
1589
+ let fn = getters.get(prop);
1590
+ if (!fn) {
1591
+ fn = (...callArgs) => {
1592
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
1593
+ return slotRange(prop);
1594
+ }
1595
+ const raw = callArgs[0];
1596
+ let occurrence;
1597
+ const k = raw.$key;
1598
+ if (typeof k === "string" || typeof k === "number") {
1599
+ occurrence = `${prop}#${k}`;
1600
+ } else {
1601
+ const n = counts[prop] || 0;
1602
+ counts[prop] = n + 1;
1603
+ occurrence = `${prop}#${n}`;
1604
+ }
1605
+ const args = {};
1606
+ for (const key of Object.keys(raw)) {
1607
+ const value = raw[key];
1608
+ const t = typeof value;
1609
+ if (value == null || t === "string" || t === "number" || t === "boolean") {
1610
+ args[key] = value;
1611
+ } else if (isServerContent(value)) {
1612
+ const resolved = sharedConfig.context.resolve(value);
1613
+ if (resolved.h.length) {
1614
+ throw new Error("Async server content in slot args is not supported yet (arg '" + key + "' of " + occurrence + "). Move the async read above the slot or into a fragment.");
1615
+ }
1616
+ const childId = `${frame.id}.${occurrence}.${key}`;
1617
+ sink.region(childId, resolved.t[0]);
1618
+ args[key] = {
1619
+ $frame: childId
1620
+ };
1621
+ } else {
1622
+ const ref = `arg:${occurrence}:${key}`;
1623
+ sharedConfig.context.serialize(ref, value);
1624
+ args[key] = {
1625
+ $ref: ref
1626
+ };
1627
+ }
1628
+ }
1629
+ sink.slot(occurrence, args);
1630
+ return slotRange(occurrence);
1631
+ };
1632
+ getters.set(prop, fn);
1633
+ }
1634
+ return fn;
1635
+ }
1636
+ });
1637
+ }
1638
+ function serverComponentResponse(component, options = {}, init = {}) {
1639
+ const {
1640
+ id = "",
1641
+ version = 1
1642
+ } = options.frame || {};
1643
+ const headers = new Headers(init.headers);
1644
+ headers.set("Content-Type", "application/x-frame-stream");
1645
+ headers.set(FRAME_STREAM_HEADER, id);
1646
+ headers.set("X-Content-Raw", "1");
1647
+ const stream = renderServerComponent(component, {
1648
+ ...options,
1649
+ frame: {
1650
+ id,
1651
+ version
1652
+ }
1653
+ });
1654
+ const body = new ReadableStream({
1655
+ start(controller) {
1656
+ stream.pipe({
1657
+ write(chunk) {
1658
+ controller.enqueue(createChunk(JSON.stringify(chunk)));
1659
+ },
1660
+ end() {
1661
+ controller.close();
1662
+ }
1663
+ });
1664
+ }
1665
+ });
1666
+ return new Response(body, {
1667
+ status: init.status || 200,
1668
+ headers
1669
+ });
1670
+ }
1671
+ function frameTransformResult(event, result) {
1672
+ let init;
1673
+ if (isResponseEnvelope(result)) {
1674
+ const {
1675
+ response,
1676
+ value
1677
+ } = result;
1678
+ if (typeof value !== "function") return result;
1679
+ init = response ? {
1680
+ headers: response.headers,
1681
+ status: response.status
1682
+ } : undefined;
1683
+ result = value;
1684
+ }
1685
+ if (typeof result !== "function") return result;
1686
+ const meta = event && event.locals && event.locals.serverFunctionMeta;
1687
+ return serverComponentResponse(result, {
1688
+ frame: {
1689
+ id: meta && meta.id || ""
1690
+ }
1691
+ }, init);
1692
+ }
1693
+
1694
+ export { FRAME_STREAM_HEADER, SERVER_COMPONENT_BOOTSTRAP, ServerComponentPlugin, createFrameSink, frameTransformDirectResult, frameTransformResult, isFrameStreamResponse, renderServerComponent, renderToFrameStream, serverComponentResponse };