@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.21

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +5165 -0
  3. package/dist/server.js +1876 -374
  4. package/dist/{server.cjs → server.observe.js} +2070 -577
  5. package/dist/{dev.cjs → web.dev.js} +955 -567
  6. package/dist/web.js +646 -350
  7. package/dist/{dev.js → web.observe.js} +699 -421
  8. package/frames/dist/assets.js +92 -0
  9. package/frames/dist/client.dev.js +1296 -1198
  10. package/frames/dist/client.js +1128 -1191
  11. package/frames/dist/client.observe.js +2041 -0
  12. package/frames/dist/regions.js +171 -0
  13. package/frames/dist/server.dev.js +2545 -0
  14. package/frames/dist/server.js +1683 -3004
  15. package/frames/dist/server.observe.js +2544 -0
  16. package/frames/dist/trace.js +45 -0
  17. package/frames/dist/wire.js +594 -0
  18. package/frames/package.json +2 -25
  19. package/package.json +244 -256
  20. package/performance-tracks/dist/performance-tracks.dev.js +679 -0
  21. package/performance-tracks/dist/performance-tracks.js +6 -0
  22. package/performance-tracks/dist/performance-tracks.observe.js +667 -0
  23. package/performance-tracks/package.json +7 -0
  24. package/performance-tracks/types/index.d.ts +69 -0
  25. package/serialization/decode/package.json +2 -15
  26. package/serialization/dist/decode.js +121 -25
  27. package/serialization/dist/serialization.js +282 -88
  28. package/serialization/package.json +2 -15
  29. package/serialization/types/index.d.ts +115 -153
  30. package/serialization/types/serializer-decode.d.ts +173 -114
  31. package/serialization/types/serializer.d.ts +144 -0
  32. package/server-functions/dist/client.dev.js +1462 -0
  33. package/server-functions/dist/client.js +667 -165
  34. package/server-functions/dist/client.observe.js +1441 -0
  35. package/server-functions/dist/rich-args.js +102 -1
  36. package/server-functions/dist/server.dev.js +2802 -299
  37. package/server-functions/dist/server.js +2724 -314
  38. package/server-functions/dist/server.observe.js +3680 -0
  39. package/server-functions/package.json +2 -35
  40. package/server-functions/rich-args/package.json +2 -15
  41. package/skills/server-components/SKILL.md +117 -0
  42. package/storage/package.json +2 -15
  43. package/types/client.d.ts +342 -288
  44. package/types/constants.d.ts +22 -0
  45. package/types/cookies.d.ts +32 -84
  46. package/types/diagnostics.d.ts +80 -0
  47. package/types/frames/assets-tier.d.ts +78 -0
  48. package/types/frames/client.d.ts +40 -1
  49. package/types/frames/frame-client.d.ts +443 -280
  50. package/types/frames/frame-container-plugin.d.ts +64 -0
  51. package/types/frames/frame-morph.d.ts +29 -0
  52. package/types/frames/frame-sink.d.ts +141 -161
  53. package/types/frames/frame-transport.d.ts +263 -184
  54. package/types/frames/regions-tier.d.ts +60 -0
  55. package/types/frames/serializer-decode.d.ts +241 -0
  56. package/types/frames/serializer.d.ts +115 -153
  57. package/types/frames/server.d.ts +2 -2
  58. package/types/frames/trace-tier.d.ts +2 -0
  59. package/types/frames/tree-rewrite.d.ts +39 -0
  60. package/types/frames/wire-tier.d.ts +169 -0
  61. package/types/head.d.ts +20 -0
  62. package/types/index.d.ts +98 -81
  63. package/types/index.server.d.ts +159 -0
  64. package/types/jsx.d.ts +49 -44
  65. package/types/observe.d.ts +535 -0
  66. package/types/reconcile.d.ts +1 -0
  67. package/types/render.d.ts +11 -0
  68. package/types/request-error-hook.d.ts +5 -0
  69. package/types/response.d.ts +95 -147
  70. package/types/serializer-decode.d.ts +173 -114
  71. package/types/serializer.d.ts +115 -153
  72. package/types/server-functions/argument-codec.d.ts +30 -0
  73. package/types/server-functions/client.d.ts +237 -223
  74. package/types/server-functions/flash.d.ts +28 -30
  75. package/types/server-functions/registry.d.ts +105 -0
  76. package/types/server-functions/rich-args.d.ts +1 -10
  77. package/types/server-functions/server.d.ts +538 -531
  78. package/types/server-functions/shared.d.ts +398 -425
  79. package/types/server-functions/uploads.d.ts +53 -0
  80. package/types/server-mock.d.ts +154 -20
  81. package/types/server-observe.d.ts +86 -0
  82. package/types/server.d.ts +601 -422
  83. package/types/trace.d.ts +127 -0
  84. package/LICENSE +0 -21
  85. package/dist/web.cjs +0 -2033
  86. package/frames/dist/client.cjs +0 -2002
  87. package/frames/dist/client.dev.cjs +0 -2022
  88. package/frames/dist/server.cjs +0 -3877
  89. package/serialization/dist/decode.cjs +0 -139
  90. package/serialization/dist/serialization.cjs +0 -261
  91. package/serialization/types-cjs/index.d.cts +0 -182
  92. package/serialization/types-cjs/package.json +0 -3
  93. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  94. package/server-functions/dist/client.cjs +0 -834
  95. package/server-functions/dist/rich-args.cjs +0 -11
  96. package/server-functions/dist/server.cjs +0 -1242
  97. package/server-functions/dist/server.dev.cjs +0 -1242
  98. package/storage/dist/storage.cjs +0 -12
  99. package/storage/types-cjs/index.d.cts +0 -28
  100. package/storage/types-cjs/package.json +0 -3
  101. package/types/core.d.ts +0 -9
  102. package/types-cjs/client.d.cts +0 -337
  103. package/types-cjs/cookies.d.cts +0 -93
  104. package/types-cjs/core.d.cts +0 -9
  105. package/types-cjs/frames/client.d.cts +0 -36
  106. package/types-cjs/frames/frame-client.d.cts +0 -356
  107. package/types-cjs/frames/frame-sink.d.cts +0 -194
  108. package/types-cjs/frames/frame-transport.d.cts +0 -222
  109. package/types-cjs/frames/serializer.d.cts +0 -182
  110. package/types-cjs/frames/server.d.cts +0 -52
  111. package/types-cjs/index.d.cts +0 -244
  112. package/types-cjs/jsx-properties.d.cts +0 -93
  113. package/types-cjs/jsx.d.cts +0 -4159
  114. package/types-cjs/package.json +0 -3
  115. package/types-cjs/response.d.cts +0 -174
  116. package/types-cjs/serializer-decode.d.cts +0 -182
  117. package/types-cjs/serializer.d.cts +0 -182
  118. package/types-cjs/server-functions/client.d.cts +0 -262
  119. package/types-cjs/server-functions/flash.d.cts +0 -38
  120. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  121. package/types-cjs/server-functions/server.d.cts +0 -681
  122. package/types-cjs/server-functions/shared.d.cts +0 -523
  123. package/types-cjs/server-mock.d.cts +0 -286
  124. package/types-cjs/server.d.cts +0 -544
package/dist/server.js CHANGED
@@ -1,6 +1,8 @@
1
- import { createRenderEffect, createMemo, sharedConfig, createRoot, inServerComponentScope, getOwner, ssrHandleError, runWithOwner, creationStamp, createComponent, omit, getNextChildId, onCleanup, getProjectionTrace } from 'solid-js';
2
- export { Errored, For, Hydration, Loading, Match, NoHydration, Repeat, Reveal, Show, Switch, createComponent, getOwner, merge as mergeProps, ssrScope as scope, sharedConfig, untrack } from 'solid-js';
3
- import { Feature, createStream, Serializer, getCrossReferenceHeader } from 'seroval';
1
+ import { createRenderEffect, createMemo, getOwner, createRoot, $PROXY, onCleanup, runWithOwner, createComponent, omit, getNextChildId } from 'solid-js';
2
+ export { Errored, For, Hydration, Loading, Match, NoHydration, Repeat, Reveal, Show, Switch, createComponent, dynamicComponent, getOwner, merge as mergeProps, untrack } from 'solid-js';
3
+ import { sharedConfig, ssrSanitizeError, beginEdgesRender, reportServerError, viewOf, sourceOwners, ssrHandleError, inServerComponentScope, creationStamp, dynamicCore, getProjectionTrace, shareAsyncIterable } from 'solid-js/internal';
4
+ export { ssrScope as scope } from 'solid-js/internal';
5
+ import { createStream, Feature, crossSerializeStream, isStream, getCrossReferenceHeader } from 'seroval';
4
6
  import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
5
7
 
6
8
  const DOMWithState = {
@@ -32,6 +34,7 @@ const DOMWithState = {
32
34
  }
33
35
  };
34
36
  const ChildProperties = /*#__PURE__*/new Set(["innerHTML", "textContent", "innerText", "children"]);
37
+ const LinkAttributes = /*#__PURE__*/new Set(["href", "target", "rel", "download", "link", "aria-current"]);
35
38
  const DelegatedEvents = /*#__PURE__*/new Set(["beforeinput", "click", "dblclick", "contextmenu", "focusin", "focusout", "input", "keydown", "keyup", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "pointerdown", "pointermove", "pointerout", "pointerover", "pointerup", "touchend", "touchmove", "touchstart"]);
36
39
  const SVGElements = /*#__PURE__*/new Set([
37
40
  "altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor", "animateMotion", "animateTransform", "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "ellipse", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feDropShadow", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignObject", "g", "glyph", "glyphRef", "hkern", "image", "line", "linearGradient", "marker", "mask", "metadata", "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline", "radialGradient", "rect",
@@ -48,6 +51,19 @@ const Namespaces = {
48
51
  const VoidElements = /*#__PURE__*/new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
49
52
  const RawTextElements = /*#__PURE__*/new Set(["style", "script", "noscript", "template", "textarea", "title"]);
50
53
  const DOMElements = /*#__PURE__*/new Set(/*#__PURE__*/"a,abbr,acronym,address,applet,area,article,aside,audio,b,base,basefont,bdi,bdo,bgsound,big,blink,blockquote,body,br,button,canvas,caption,center,cite,code,col,colgroup,content,data,datalist,dd,del,details,dfn,dialog,dir,div,dl,dt,em,embed,fieldset,figcaption,figure,font,footer,form,frame,frameset,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,image,img,input,ins,isindex,kbd,keygen,label,legend,li,link,listing,main,map,mark,marquee,math,menu,menuitem,meta,meter,multicol,nav,nextid,nobr,noembed,noframes,noindex,noscript,object,ol,optgroup,option,output,p,param,picture,plaintext,portal,pre,progress,q,rb,rp,rt,rtc,ruby,s,samp,script,search,section,select,shadow,slot,small,source,spacer,span,strike,strong,style,sub,summary,sup,svg,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,tt,u,ul,var,video,wbr,webview,xmp".split(","));
54
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
55
+ function isHttpNavigationTarget(target) {
56
+ try {
57
+ const protocol = new URL(target, "http://base.invalid").protocol;
58
+ return protocol === "http:" || protocol === "https:";
59
+ } catch {
60
+ return false;
61
+ }
62
+ }
63
+ function isEventName(name) {
64
+ let c;
65
+ return name.startsWith("on") && (c = name.charCodeAt(2)) > 64 && c < 91;
66
+ }
51
67
 
52
68
  const transparentOptions = {
53
69
  transparent: true,
@@ -56,14 +72,281 @@ const transparentOptions = {
56
72
  const syncOptions = {
57
73
  sync: true
58
74
  };
59
- const effect = (fn, effectFn, options) => createRenderEffect(fn, effectFn, options ? {
60
- sync: true,
61
- ...options,
62
- transparent: !options.scope
63
- } : transparentOptions);
64
- const memo = fn => createMemo(() => fn(), syncOptions);
75
+ function effect(fn, effectFn, options) {
76
+ const nodeOptions = options ? {
77
+ sync: true,
78
+ ...options,
79
+ transparent: !options.scope
80
+ } : transparentOptions;
81
+ createRenderEffect(fn, effectFn, nodeOptions);
82
+ }
83
+ function memo(fn) {
84
+ return createMemo(() => fn(), syncOptions);
85
+ }
86
+
87
+ const REQUEST_ERROR_HOOK = Symbol.for("solid-js/server/request-error-hook");
88
+ function hooks() {
89
+ const g = globalThis;
90
+ return g[REQUEST_ERROR_HOOK] || (g[REQUEST_ERROR_HOOK] = new WeakMap());
91
+ }
92
+ function setRequestErrorHook(event, hook) {
93
+ if (hook !== undefined) hooks().set(event, hook);
94
+ }
95
+
96
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
97
+ const ZERO_TRACE = "00000000000000000000000000000000";
98
+ const ZERO_SPAN = "0000000000000000";
99
+ function parseTraceparent(value) {
100
+ if (!value) return undefined;
101
+ const m = TRACEPARENT.exec(value.trim());
102
+ if (!m) return undefined;
103
+ const [, version, traceId, parentId, flags, rest] = m;
104
+ if (version === "ff") return undefined;
105
+ if (version === "00" && rest !== undefined) return undefined;
106
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
107
+ return {
108
+ traceId,
109
+ parentId,
110
+ sampled: (parseInt(flags, 16) & 1) === 1
111
+ };
112
+ }
113
+ function randomHex(bytes) {
114
+ let out = "";
115
+ for (let i = 0; i < bytes; i += 4) out += (Math.random() * 0x100000000 >>> 0).toString(16).padStart(8, "0");
116
+ return out.length === bytes * 2 ? out : out.slice(0, bytes * 2);
117
+ }
118
+ function randomTraceId() {
119
+ let id = randomHex(16);
120
+ while (id === ZERO_TRACE) id = randomHex(16);
121
+ return id;
122
+ }
123
+ function randomSpanId() {
124
+ let id = randomHex(8);
125
+ while (id === ZERO_SPAN) id = randomHex(8);
126
+ return id;
127
+ }
128
+ function formatTraceparent(context) {
129
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
130
+ }
131
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
132
+ function records() {
133
+ const g = globalThis;
134
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
135
+ }
136
+ function traceFor(key, request) {
137
+ const store = records();
138
+ let record = store.get(key);
139
+ if (record) return record;
140
+ const headers = request ? request.headers : undefined;
141
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
142
+ const context = {
143
+ traceId: incoming ? incoming.traceId : randomTraceId(),
144
+ spanId: randomSpanId(),
145
+ entries: {}
146
+ };
147
+ if (incoming) {
148
+ context.parentId = incoming.parentId;
149
+ context.sampled = incoming.sampled;
150
+ }
151
+ if (headers) {
152
+ const state = headers.get("tracestate");
153
+ if (state) context.state = state;
154
+ const baggage = headers.get("baggage");
155
+ if (baggage) context.baggage = baggage;
156
+ }
157
+ let answered = false;
158
+ context.entries.traceparent = formatTraceparent(context);
159
+ record = {
160
+ context,
161
+ emit: incoming !== undefined && incoming.sampled || answered,
162
+ timing: []
163
+ };
164
+ store.set(key, record);
165
+ return record;
166
+ }
167
+ function traceForEvent(event) {
168
+ return traceFor(event.request || event, event.request);
169
+ }
170
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
171
+ function splitServerTiming(value) {
172
+ const entries = [];
173
+ let start = 0;
174
+ let quoted = false;
175
+ for (let i = 0; i < value.length; i++) {
176
+ const c = value[i];
177
+ if (quoted) {
178
+ if (c === "\\") i++;else if (c === '"') quoted = false;
179
+ } else if (c === '"') quoted = true;else if (c === ",") {
180
+ entries.push(value.slice(start, i));
181
+ start = i + 1;
182
+ }
183
+ }
184
+ entries.push(value.slice(start));
185
+ return entries;
186
+ }
187
+ function metricName(entry) {
188
+ return entry.split(";")[0].trim().toLowerCase();
189
+ }
190
+ function namesOnServerTiming(headers) {
191
+ const names = new Set();
192
+ const existing = headers.get("server-timing");
193
+ if (existing) {
194
+ for (const entry of splitServerTiming(existing)) {
195
+ const name = metricName(entry);
196
+ if (name) names.add(name);
197
+ }
198
+ }
199
+ return names;
200
+ }
201
+ function quoteDesc(value) {
202
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
203
+ }
204
+ function shellMs(record) {
205
+ return record.render !== undefined ? record.render.shellMs : undefined;
206
+ }
207
+ function hasServerTiming(record) {
208
+ return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
209
+ }
210
+ function appendTraceServerTiming(headers, record) {
211
+ if (record.emit) {
212
+ const entries = record.context.entries;
213
+ let present;
214
+ for (const name in entries) {
215
+ if (!TOKEN.test(name)) continue;
216
+ if (!present) present = namesOnServerTiming(headers);
217
+ if (present.has(name.toLowerCase())) continue;
218
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
219
+ present.add(name.toLowerCase());
220
+ }
221
+ }
222
+ const shell = shellMs(record);
223
+ if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
224
+ for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
225
+ }
226
+ function metricOf(work) {
227
+ if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
228
+ const boundary = work.event;
229
+ return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
230
+ }
231
+ function formatMetric(name, dur, desc) {
232
+ let out = `${name};dur=${Math.round(dur * 10) / 10}`;
233
+ if (desc) out += `;desc="${quoteDesc(desc)}"`;
234
+ return out;
235
+ }
236
+ function mergeServerTiming(target, value) {
237
+ const present = namesOnServerTiming(target);
238
+ for (const entry of splitServerTiming(value)) {
239
+ const trimmed = entry.trim();
240
+ const name = metricName(trimmed);
241
+ if (!name || present.has(name)) continue;
242
+ target.append("Server-Timing", trimmed);
243
+ }
244
+ }
245
+ function escapeAttr(value) {
246
+ return value.replace(/[&"<>]/g, c => c === "&" ? "&amp;" : c === '"' ? "&quot;" : c === "<" ? "&lt;" : "&gt;");
247
+ }
248
+ function traceMetaMarkup(record) {
249
+ if (!record.emit) return "";
250
+ let markup = "";
251
+ const entries = record.context.entries;
252
+ for (const name in entries) {
253
+ if (!TOKEN.test(name)) continue;
254
+ markup += `<meta name="${name}" content="${escapeAttr(entries[name])}">`;
255
+ }
256
+ return markup;
257
+ }
65
258
 
66
- const STATE = Symbol.for("dom-expressions.container-trace-state");
259
+ const DESCEND = Symbol("descend");
260
+ const CYCLE = {};
261
+ const TRACK = 16;
262
+ function rewriteTree(value, visit, withPath) {
263
+ if (value === null || typeof value !== "object") return value;
264
+ const path = undefined;
265
+ const state = {
266
+ memo: undefined,
267
+ ancestors: undefined
268
+ };
269
+ try {
270
+ return cow(value, visit, path, 0, state);
271
+ } catch (err) {
272
+ if (err !== CYCLE) throw err;
273
+ }
274
+ return clone(value, visit, path, state.memo || (state.memo = new Map()));
275
+ }
276
+ function shape(value) {
277
+ return Array.isArray(value) ? 1 : Object.getPrototypeOf(value) === Object.prototype ? 2 : 0;
278
+ }
279
+ function cow(value, visit, path, depth, state) {
280
+ const memo = state.memo;
281
+ if (memo !== undefined && memo.has(value)) return memo.get(value);
282
+ const r = visit(value, path);
283
+ if (r !== DESCEND) {
284
+ if (r !== value) (memo || (state.memo = new Map())).set(value, r);
285
+ return r;
286
+ }
287
+ const s = shape(value);
288
+ if (s === 0) return value;
289
+ let ancestors;
290
+ if (depth >= TRACK) {
291
+ ancestors = state.ancestors || (state.ancestors = new Set());
292
+ if (ancestors.has(value)) throw CYCLE;
293
+ ancestors.add(value);
294
+ }
295
+ let out = value;
296
+ if (s === 1) {
297
+ for (let i = 0; i < value.length; i++) {
298
+ const c = value[i];
299
+ if (c === null || typeof c !== "object") continue;
300
+ const next = cow(c, visit, undefined , depth + 1, state);
301
+ if (next !== c) {
302
+ if (out === value) out = value.slice();
303
+ out[i] = next;
304
+ }
305
+ }
306
+ } else {
307
+ for (const k of Object.keys(value)) {
308
+ const c = value[k];
309
+ if (c === null || typeof c !== "object") continue;
310
+ const next = cow(c, visit, undefined , depth + 1, state);
311
+ if (next !== c) {
312
+ if (out === value) out = {
313
+ ...value
314
+ };
315
+ out[k] = next;
316
+ }
317
+ }
318
+ }
319
+ if (ancestors !== undefined) ancestors.delete(value);
320
+ return out;
321
+ }
322
+ function clone(value, visit, path, memo) {
323
+ if (memo.has(value)) return memo.get(value);
324
+ const r = visit(value, path);
325
+ if (r !== DESCEND) {
326
+ memo.set(value, r);
327
+ return r;
328
+ }
329
+ const s = shape(value);
330
+ if (s === 0) return value;
331
+ const out = s === 1 ? value.slice() : {
332
+ ...value
333
+ };
334
+ memo.set(value, out);
335
+ if (s === 1) {
336
+ for (let i = 0; i < value.length; i++) {
337
+ const c = value[i];
338
+ if (c !== null && typeof c === "object") out[i] = clone(c, visit, undefined , memo);
339
+ }
340
+ } else {
341
+ for (const k of Object.keys(value)) {
342
+ const c = value[k];
343
+ if (c !== null && typeof c === "object") out[k] = clone(c, visit, undefined , memo);
344
+ }
345
+ }
346
+ return out;
347
+ }
348
+
349
+ const STATE = Symbol.for("solid.container-trace-state");
67
350
  const state = globalThis[STATE] || (globalThis[STATE] = {
68
351
  materialized: new WeakMap(),
69
352
  materializedValues: new WeakSet()
@@ -71,14 +354,33 @@ const state = globalThis[STATE] || (globalThis[STATE] = {
71
354
  function setContainerTraceResolver(fn) {
72
355
  state.resolveTrace = fn;
73
356
  }
357
+ function setAsyncIterableSharer(fn) {
358
+ state.shareIterable = fn;
359
+ }
74
360
  function setContainerTraceStreamMint(fn) {
75
361
  state.streamOf = fn;
76
362
  }
77
- const TRACE = Symbol.for("dom-expressions.container-trace");
78
- function materialize(marker) {
363
+ const TRACE = Symbol.for("solid.container-trace");
364
+ function toBorderForm(value, envelopeContainers) {
365
+ if (value == null || typeof value !== "object") return value;
366
+ const share = state.shareIterable;
367
+ if (!share) return value;
368
+ return rewriteTree(value, v => {
369
+ if (share && isShareableIterable(v)) return share(v);
370
+ return DESCEND;
371
+ });
372
+ }
373
+ function isShareableIterable(value) {
374
+ try {
375
+ return typeof value[Symbol.asyncIterator] === "function" && !(typeof ReadableStream !== "undefined" && value instanceof ReadableStream);
376
+ } catch {
377
+ return false;
378
+ }
379
+ }
380
+ function materialize(marker, claiming) {
79
381
  let value = state.materialized.get(marker.$tr);
80
382
  if (value === undefined) {
81
- value = state.materializeTrace(marker);
383
+ value = state.materializeTrace(marker, claiming);
82
384
  state.materialized.set(marker.$tr, value);
83
385
  if (value !== null && typeof value === "object") state.materializedValues.add(value);
84
386
  }
@@ -93,7 +395,7 @@ function parseTrace(value, ctx) {
93
395
  };
94
396
  }
95
397
  const ContainerTracePlugin = {
96
- tag: "dom-expressions/container-trace",
398
+ tag: "solid/container-trace",
97
399
  test(value) {
98
400
  return value != null && typeof value === "object" && TRACE in value;
99
401
  },
@@ -136,57 +438,186 @@ setContainerTraceStreamMint(iterable => {
136
438
  })();
137
439
  return stream;
138
440
  });
139
- const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
441
+ const DEFAULT_WEB_PLUGINS = /* @__PURE__ */Object.freeze([AbortSignalPlugin,
140
442
  CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
141
443
  FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin,
142
444
  ContainerTracePlugin]);
143
445
  function resolveSerializerPlugins(customPlugins) {
144
446
  return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
145
447
  }
146
- Feature.RegExp;
147
448
 
148
- const DEFAULT_DISABLED_FEATURES = Feature.AggregateError | Feature.BigIntTypedArray;
149
- const serializeOnlyDisabledFeatures = () => process.env.NODE_ENV === "development" ? 0 : Feature.ErrorPrototypeStack;
449
+ const defaultDisabledFeatures = () => Feature.AggregateError | Feature.BigIntTypedArray;
450
+ const serializeOnlyDisabledFeatures = serializeErrorStacks => (process.env.NODE_ENV === "development" ) ? 0 : Feature.ErrorPrototypeStack;
150
451
  const HYDRATION_GLOBAL = "_$HY.r";
151
- function createSerializer(options) {
152
- return new Serializer({
153
- ...options,
154
- plugins: resolveSerializerPlugins(options.plugins),
155
- disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures()
156
- });
452
+ function createKeyedSerializer(serialize, onError, onDone) {
453
+ const cancels = new Set();
454
+ let pendingWrites = 0;
455
+ let flushed = false;
456
+ let done = false;
457
+ let closed = false;
458
+ const maybeDone = () => {
459
+ if (flushed && pendingWrites === 0 && !done) {
460
+ done = true;
461
+ onDone && onDone();
462
+ }
463
+ };
464
+ return {
465
+ write(key, value) {
466
+ if (flushed) return;
467
+ pendingWrites++;
468
+ let settled = false;
469
+ let failed = false;
470
+ let cancel = null;
471
+ const settle = () => {
472
+ if (settled) return;
473
+ settled = true;
474
+ if (cancel) cancels.delete(cancel);
475
+ pendingWrites--;
476
+ maybeDone();
477
+ };
478
+ let stream;
479
+ try {
480
+ stream = serialize(key, value, {
481
+ onError: onError && (err => {
482
+ failed = true;
483
+ onError(err);
484
+ if (cancel) {
485
+ cancel();
486
+ settle();
487
+ }
488
+ }),
489
+ onDone: settle
490
+ }, () => !closed);
491
+ } catch (err) {
492
+ settle();
493
+ throw err;
494
+ }
495
+ if (settled) return;
496
+ if (closed || failed) {
497
+ stream();
498
+ settle();
499
+ return;
500
+ }
501
+ cancel = stream;
502
+ cancels.add(cancel);
503
+ },
504
+ flush() {
505
+ flushed = true;
506
+ maybeDone();
507
+ },
508
+ close() {
509
+ closed = flushed = true;
510
+ for (const cancel of cancels) cancel();
511
+ cancels.clear();
512
+ if (!done) {
513
+ done = true;
514
+ onDone && onDone();
515
+ }
516
+ }
517
+ };
157
518
  }
519
+ const KEY_ESCAPES = {
520
+ '"': '\\"',
521
+ "\\": "\\\\",
522
+ "\n": "\\n",
523
+ "\r": "\\r",
524
+ "\b": "\\b",
525
+ "\t": "\\t",
526
+ "\f": "\\f",
527
+ "<": "\\x3C",
528
+ "\u2028": "\\u2028",
529
+ "\u2029": "\\u2029"
530
+ };
531
+ const serializeKey = key => ("" + key).replace(/["\\\n\r\b\t\f<\u2028\u2029]/g, c => KEY_ESCAPES[c]);
158
532
  function createHydrationSerializer({
159
533
  onData,
160
534
  onDone,
161
535
  scopeId,
162
536
  onError,
163
- plugins
537
+ plugins,
538
+ late
164
539
  }) {
165
- return createSerializer({
540
+ const resolvedPlugins = resolveSerializerPlugins(plugins);
541
+ const disabledFeatures = defaultDisabledFeatures() | serializeOnlyDisabledFeatures();
542
+ const refs = new Map();
543
+ const serialize = (key, value, callbacks, live) => crossSerializeStream(value, {
166
544
  scopeId,
167
- plugins,
168
- globalIdentifier: HYDRATION_GLOBAL,
169
- onData,
170
- onDone,
171
- onError
545
+ refs,
546
+ plugins: resolvedPlugins,
547
+ disabledFeatures,
548
+ onSerialize(data, initial) {
549
+ if (!live()) return;
550
+ onData(initial ? HYDRATION_GLOBAL + '["' + serializeKey(key) + '"]=' + data : data);
551
+ },
552
+ ...callbacks
172
553
  });
554
+ return createKeyedSerializer(late ? late(serialize, refs, onData, scopeId) : serialize, onError, onDone);
555
+ }
556
+ function rejectUnserializedKey(serialize, refs, onData, scopeId) {
557
+ let taken = 0;
558
+ let fresh = [];
559
+ const set = refs.set;
560
+ refs.set = (value, id) => {
561
+ taken++;
562
+ fresh.push(value);
563
+ return set.call(refs, value, id);
564
+ };
565
+ Object.defineProperty(refs, "size", {
566
+ get: () => taken
567
+ });
568
+ return (key, value, callbacks, live) => {
569
+ const sent = [];
570
+ const failed = () => {
571
+ for (const ref of fresh) refs.delete(ref);
572
+ fresh = [];
573
+ const ids = new Set();
574
+ for (const ref of sent) {
575
+ const id = refs.get(ref);
576
+ if (ref instanceof Promise) ids.add(id + 1);else if (isStream(ref) || Object.getPrototypeOf(ref) === Object.prototype && !Object.keys(ref).length) ids.add(id);
577
+ }
578
+ if (!ids.size) return;
579
+ const body = "for(const i of[" + [...ids] + "]){const v=$R[i];v&&(v.f?v.f(e):v.throw&&v.throw(e))}";
580
+ const message = JSON.stringify("Serialization failed: the hydration value for key " + JSON.stringify(key) + " could not be serialized on the server").replace(/[<\u2028\u2029]/g, c => KEY_ESCAPES[c]);
581
+ onData("($R=>{const e=new Error(" + message + ");" + body + "})(" + (scopeId == null ? "$R" : '$R["' + serializeKey(scopeId) + '"]') + ")");
582
+ };
583
+ return serialize(key, value, {
584
+ ...callbacks,
585
+ onError: callbacks.onError && (err => {
586
+ if (live()) failed();
587
+ callbacks.onError(err);
588
+ })
589
+ },
590
+ () => {
591
+ if (!live()) return false;
592
+ sent.push(...fresh);
593
+ fresh = [];
594
+ return true;
595
+ });
596
+ };
173
597
  }
174
598
  function getLocalHeaderScript(id) {
175
599
  return getCrossReferenceHeader(id) + ";";
176
600
  }
177
601
 
178
602
  const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
179
- // PURE-annotated factory (same convention as solid's MockPromise): the brand
180
- const ResponseEnvelope = /* @__PURE__ */(() => {
181
- class ResponseEnvelope {
182
- constructor(response, value) {
183
- this.response = response;
184
- this.value = value;
185
- }
603
+ let EnvelopeClass;
604
+ const ResponseEnvelope = function ResponseEnvelope(response, value) {
605
+ if (!EnvelopeClass) {
606
+ EnvelopeClass = class extends Response {
607
+ constructor(response, value) {
608
+ super(response ? response.body : null, response && {
609
+ status: response.status,
610
+ statusText: response.statusText,
611
+ headers: copyHeaders(response.headers)
612
+ });
613
+ this.response = response ? this : undefined;
614
+ this.value = value;
615
+ }
616
+ };
617
+ EnvelopeClass.prototype[ENVELOPE] = true;
186
618
  }
187
- ResponseEnvelope.prototype[ENVELOPE] = true;
188
- return ResponseEnvelope;
189
- })();
619
+ return new EnvelopeClass(response, value);
620
+ };
190
621
  function isResponseEnvelope(value) {
191
622
  return !!(value && typeof value === "object" && value[ENVELOPE]);
192
623
  }
@@ -209,24 +640,38 @@ function isSafeError(value) {
209
640
  return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
210
641
  }
211
642
  const REVALIDATE_HEADER = "X-Revalidate";
212
- function initWithRevalidate(init) {
643
+ const REVALIDATE_ALL = "*";
644
+ const RESPONSE_HEADER_VALUE_LIMIT = 4096;
645
+ function copyHeaders(init) {
646
+ const source = init;
647
+ if (!source || !source.getSetCookie) return new Headers(init);
648
+ const headers = new Headers();
649
+ source.forEach((value, key) => {
650
+ if (key !== "set-cookie") headers.append(key, value);
651
+ });
652
+ for (const cookie of source.getSetCookie()) headers.append("Set-Cookie", cookie);
653
+ return headers;
654
+ }
655
+ function initWithRevalidate(init = {}) {
656
+ const resolved = typeof init === "number" ? {
657
+ status: init
658
+ } : init;
213
659
  const {
214
660
  revalidate,
215
661
  ...responseInit
216
- } = init;
217
- let headers;
218
- if (responseInit.headers && responseInit.headers.getSetCookie) {
219
- headers = new Headers();
220
- responseInit.headers.forEach((value, key) => {
221
- if (key !== "set-cookie") headers.append(key, value);
222
- });
223
- for (const cookie of responseInit.headers.getSetCookie()) {
224
- headers.append("Set-Cookie", cookie);
662
+ } = resolved;
663
+ const headers = copyHeaders(responseInit.headers);
664
+ if (revalidate !== undefined) {
665
+ const list = Array.isArray(revalidate) ? revalidate : [revalidate];
666
+ if (list.length > 1 && list.includes(REVALIDATE_ALL)) {
667
+ throw new TypeError(`revalidate names "${REVALIDATE_ALL}" alongside other keys; "${REVALIDATE_ALL}" already ` + `means every entry and stands alone — pass revalidate: "${REVALIDATE_ALL}" or the named keys.`);
225
668
  }
226
- } else {
227
- headers = new Headers(responseInit.headers);
669
+ const keys = list.join(",");
670
+ if (keys.length > RESPONSE_HEADER_VALUE_LIMIT) {
671
+ throw new TypeError(`revalidate names ${keys.length} characters of cache keys; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} the ${REVALIDATE_HEADER} header would overflow ` + `receivers (an 8 KiB proxy buffer holds the whole header block) and the response ` + `dies at the socket after the mutation committed. Split the invalidation across ` + `calls or use coarser keys — a dropped key would be a silently stale cache, so ` + `the runtime refuses rather than trims.`);
672
+ }
673
+ headers.set(REVALIDATE_HEADER, keys);
228
674
  }
229
- revalidate !== undefined && headers.set(REVALIDATE_HEADER, revalidate.toString());
230
675
  return {
231
676
  responseInit,
232
677
  headers
@@ -239,13 +684,17 @@ function redirect(url, init = 302) {
239
684
  const {
240
685
  responseInit,
241
686
  headers
242
- } = initWithRevalidate(typeof init === "number" ? {
243
- status: init
244
- } : init);
687
+ } = initWithRevalidate(init);
245
688
  if (responseInit.status === undefined) {
246
689
  responseInit.status = 302;
247
690
  }
248
- headers.set("Location", String(url));
691
+ const target = typeof url === "string" ? url : url[HREF];
692
+ const location = typeof target === "string" ? target : String(url);
693
+ const encoded = location.replace(/[^\x00-\x7f]/gu, encodeURIComponent);
694
+ if (encoded.length > RESPONSE_HEADER_VALUE_LIMIT) {
695
+ throw new TypeError(`redirect() target is ${encoded.length} characters; past ` + `${RESPONSE_HEADER_VALUE_LIMIT} the Location header (and the scripted transport's ` + `redirect header) would overflow receivers and the response dies at the socket. ` + `A target this size is usually unbounded input echoed into the url — carry the ` + `state server-side instead. Refused rather than trimmed: a cut target is a ` + `different address.`);
696
+ }
697
+ headers.set("Location", encoded);
249
698
  return new Response(null, {
250
699
  ...responseInit,
251
700
  headers
@@ -261,13 +710,26 @@ function reload(init = {}) {
261
710
  headers
262
711
  });
263
712
  }
713
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
264
714
  function respond(value, init = {}) {
265
715
  const {
266
716
  responseInit,
267
717
  headers
268
718
  } = initWithRevalidate(init);
719
+ for (const header of COMPOSED_BODY_FRAMING) headers.delete(header);
720
+ if (NULL_BODY_STATUSES.has(responseInit.status)) {
721
+ return new ResponseEnvelope(new Response(null, {
722
+ ...responseInit,
723
+ headers
724
+ }), value);
725
+ }
269
726
  headers.set("Content-Type", "application/json");
270
- return new ResponseEnvelope(new Response(JSON.stringify(value), {
727
+ return new ResponseEnvelope(new Response(new ReadableStream({
728
+ pull(controller) {
729
+ controller.enqueue(new TextEncoder().encode(JSON.stringify(value)));
730
+ controller.close();
731
+ }
732
+ }), {
271
733
  ...responseInit,
272
734
  headers
273
735
  }), value);
@@ -316,6 +778,7 @@ function serializeCookie(name, value, options = {}) {
316
778
  if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
317
779
  if (options.httpOnly) cookie += "; HttpOnly";
318
780
  if (options.secure) cookie += "; Secure";
781
+ if (options.partitioned) cookie += "; Partitioned";
319
782
  if (options.sameSite) {
320
783
  const sameSite = options.sameSite.toLowerCase();
321
784
  cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
@@ -323,7 +786,7 @@ function serializeCookie(name, value, options = {}) {
323
786
  return cookie;
324
787
  }
325
788
  const FLASH_COOKIE = "flash";
326
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
789
+ const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
327
790
  function hasFlashCookie(cookieHeader) {
328
791
  return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
329
792
  }
@@ -333,6 +796,7 @@ function clearFlashCookie() {
333
796
 
334
797
  const ERROR_HEADER = "X-Server-Function-Error";
335
798
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
799
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
336
800
  const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
337
801
 
338
802
  const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
@@ -367,11 +831,28 @@ function classifyHeadTag(desc) {
367
831
  resource: false
368
832
  };
369
833
  }
834
+ function qualifierValue(name, value) {
835
+ if (value == null || value === false) return null;
836
+ if (name === "imagesrcset" || name === "imagesizes") return typeof value === "string" && value !== "" ? value : null;
837
+ const v = value === true ? "" : String(value);
838
+ if (name === "as") return asciiLowerCase(v);
839
+ if (name !== "crossorigin") return v;
840
+ return v.length === 15 && v.toLowerCase() === "use-credentials" ? v.toLowerCase() : "anonymous";
841
+ }
842
+ function asciiLowerCase(value) {
843
+ return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
844
+ }
845
+ const JSON_SCRIPT_TYPE = /^(?:importmap|speculationrules)$|^[\t\n\r ]*(?:application\/json|text\/json|[\w!#$%&'*+.^`|~-]+\/[\w!#$%&'*+.^`|~-]*\+json)[\t\n\r ]*(?:;|$)/i;
846
+ function headBodyText(tag, props, text) {
847
+ return tag === "script" && JSON_SCRIPT_TYPE.test(String(props.type)) ? text.replace(/</g, "\\u003C") : text;
848
+ }
370
849
  function resourceIdentity(tag, props) {
371
- let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
850
+ const url = String(props.href || props.src || "");
851
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + url.length + ":" + url;
372
852
  for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
373
853
  const q = RESOURCE_QUALIFIERS[i];
374
- if (props[q] != null) id += ":" + q + "=" + props[q];
854
+ const value = qualifierValue(q, props[q]);
855
+ if (value !== null) id += ":" + q + "=" + value.length + ":" + value;
375
856
  }
376
857
  return id;
377
858
  }
@@ -420,6 +901,7 @@ function resolveHead(groups) {
420
901
  return winners;
421
902
  }
422
903
 
904
+ const renderConfig = sharedConfig;
423
905
  function joinAssetPath(base, file) {
424
906
  if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
425
907
  if (typeof base !== "string" || !base) base = "/";
@@ -430,41 +912,65 @@ function resolveAssets(moduleUrl, manifest) {
430
912
  if (!manifest) return null;
431
913
  const base = manifest._base;
432
914
  const entry = manifest[moduleUrl];
433
- if (!entry) return null;
915
+ if (!entry || typeof entry !== "object") return null;
434
916
  const css = [];
435
917
  const js = [];
918
+ let preloads;
436
919
  const visited = new Set();
437
920
  const walk = key => {
438
921
  if (visited.has(key)) return;
439
922
  visited.add(key);
440
923
  const e = manifest[key];
441
- if (!e) return;
924
+ if (!e || typeof e !== "object") return;
442
925
  js.push(joinAssetPath(base, e.file));
443
926
  if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
927
+ if (e.preloads) {
928
+ for (let i = 0; i < e.preloads.length; i++) {
929
+ const link = e.preloads[i];
930
+ const href = link && typeof link.href === "string" && link.href;
931
+ const srcset = link && typeof link.imagesrcset === "string" && link.imagesrcset;
932
+ if (!href && !srcset) continue;
933
+ if (!preloads) preloads = [];
934
+ if (href) preloads.push({
935
+ ...link,
936
+ href: joinAssetPath(base, href)
937
+ });else {
938
+ const {
939
+ href: bad,
940
+ ...rest
941
+ } = link;
942
+ preloads.push(rest);
943
+ }
944
+ }
945
+ }
444
946
  if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
445
947
  };
446
948
  walk(moduleUrl);
447
- return {
949
+ const assets = {
448
950
  js,
449
951
  css
450
952
  };
953
+ if (preloads) assets.preloads = preloads;
954
+ return assets;
451
955
  }
452
956
  function registerEntryAssets(manifest) {
453
957
  if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
454
958
  const ctx = sharedConfig.context;
455
959
  if (!ctx?.registerAsset) return;
456
960
  for (const key in manifest) {
457
- if (manifest[key].isEntry) {
961
+ const entry = manifest[key];
962
+ if (entry && entry.isEntry) {
458
963
  const assets = resolveAssets(key, manifest);
459
964
  if (assets) {
965
+ if (assets.preloads) for (let i = 0; i < assets.preloads.length; i++) ctx.registerAsset("preload", assets.preloads[i]);
460
966
  for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
461
- for (let i = 1; i < assets.js.length; i++) ctx.registerAsset("module", assets.js[i]);
967
+ for (let i = 1; i < assets.js.length; i++) ctx.registerAsset("module", assets.js[i], true);
462
968
  }
463
969
  return;
464
970
  }
465
971
  }
466
972
  }
467
- function createAssetTracking() {
973
+ function createAssetTracking(lowPriorityPreloads) {
468
974
  const boundaryModules = new Map();
469
975
  const boundaryStyles = new Map();
470
976
  const emittedAssets = new Set();
@@ -475,6 +981,8 @@ function createAssetTracking() {
475
981
  boundaryStyles,
476
982
  emittedAssets,
477
983
  inlineStyles,
984
+ preloadLinks: null,
985
+ lowModules: lowPriorityPreloads !== false ? new Set() : null,
478
986
  registerInlineStyle(desc) {
479
987
  let entry = inlineStyles.get(desc.id);
480
988
  if (!entry) {
@@ -549,6 +1057,7 @@ function applyAssetTracking(context, tracking, manifest, noScripts) {
549
1057
  });
550
1058
  context.registerModule = tracking.registerModule;
551
1059
  context.getBoundaryModules = tracking.getBoundaryModules;
1060
+ context._lazyAssets = new Map();
552
1061
  if (typeof manifest === "function") {
553
1062
  context.resolveAssets = guard(manifest);
554
1063
  } else if (manifest && typeof manifest.resolve === "function") {
@@ -566,6 +1075,82 @@ function isCssUrl(url) {
566
1075
  const q = url.search(/[?#]/);
567
1076
  return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
568
1077
  }
1078
+ const RESPONSIVE_ATTRIBUTES = ["imagesrcset", "imagesizes"];
1079
+ function isSetAttr(value) {
1080
+ return value != null && value !== false && value !== "";
1081
+ }
1082
+ const PRELOAD_LINK_ATTRIBUTES = ["type", "crossorigin", "integrity", "referrerpolicy", "fetchpriority", "media", "imagesrcset", "imagesizes"];
1083
+ function registerPreloadLink(tracking, headRegistry, link, nonce) {
1084
+ if (!link || typeof link !== "object") {
1085
+ return null;
1086
+ }
1087
+ if (typeof link.as !== "string") {
1088
+ return null;
1089
+ }
1090
+ const as = asciiLowerCase(link.as);
1091
+ let destination = null;
1092
+ switch (as) {
1093
+ case "script":
1094
+ case "style":
1095
+ destination = as;
1096
+ break;
1097
+ case "fetch":
1098
+ case "font":
1099
+ case "image":
1100
+ case "track":
1101
+ break;
1102
+ default:
1103
+ return null;
1104
+ }
1105
+ const responsive = as === "image";
1106
+ let srcset = null;
1107
+ let sizes = null;
1108
+ if (responsive) {
1109
+ for (const name of RESPONSIVE_ATTRIBUTES) {
1110
+ const value = link[name];
1111
+ if (!isSetAttr(value)) continue;
1112
+ if (typeof value !== "string") {
1113
+ continue;
1114
+ }
1115
+ if (name === "imagesrcset") srcset = value;else sizes = value;
1116
+ }
1117
+ }
1118
+ const href = typeof link.href === "string" && link.href ? link.href : null;
1119
+ if (!href && !srcset) {
1120
+ return null;
1121
+ }
1122
+ const props = {
1123
+ rel: "preload"
1124
+ };
1125
+ if (href) props.href = href;
1126
+ props.as = as;
1127
+ for (let i = 0; i < PRELOAD_LINK_ATTRIBUTES.length; i++) {
1128
+ const name = PRELOAD_LINK_ATTRIBUTES[i];
1129
+ if (RESPONSIVE_ATTRIBUTES.indexOf(name) !== -1) {
1130
+ const value = name === "imagesrcset" ? srcset : sizes;
1131
+ if (value !== null) props[name] = value;
1132
+ continue;
1133
+ }
1134
+ const value = link[name];
1135
+ if (value == null || value === false) continue;
1136
+ props[name] = value === true ? "" : String(value);
1137
+ }
1138
+ const identity = resourceIdentity("link", props);
1139
+ if (headRegistry.resources.has(identity)) return null;
1140
+ const attrs = headAttrRecord(props);
1141
+ const nonceValue = destination && nonce && nonce[destination];
1142
+ if (typeof nonceValue === "string" && nonceValue) attrs.nonce = nonceValue;
1143
+ const entry = {
1144
+ href: props.href,
1145
+ attrs,
1146
+ attrHtml: renderHeadAttrHtml(props) + nonceAttr(nonce, destination)
1147
+ };
1148
+ headRegistry.resources.add(identity);
1149
+ let links = tracking.preloadLinks;
1150
+ if (!links) tracking.preloadLinks = links = [];
1151
+ links.push(entry);
1152
+ return entry;
1153
+ }
569
1154
  function createHeadRegistry() {
570
1155
  return {
571
1156
  pending: [],
@@ -702,7 +1287,7 @@ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc
702
1287
  if (plain && props.href != null) {
703
1288
  const isCss = isCssUrl(props.href);
704
1289
  if (rel === "stylesheet" ? isCss : !isCss) {
705
- context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href);
1290
+ context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href, true);
706
1291
  return;
707
1292
  }
708
1293
  }
@@ -816,7 +1401,7 @@ function headGroupSignature(winner) {
816
1401
  }
817
1402
  return sig;
818
1403
  }
819
- function renderShellHead(registry, nonce, isPendingFragment, noScripts) {
1404
+ function renderShellHead(registry, nonce, isPendingFragment, noScripts, traceMetas = "") {
820
1405
  commitHeadBoundary(registry, "", isPendingFragment);
821
1406
  registry.shellFlushed = true;
822
1407
  const winners = resolveHead(registry.committed);
@@ -842,11 +1427,12 @@ function renderShellHead(registry, nonce, isPendingFragment, noScripts) {
842
1427
  }
843
1428
  return {
844
1429
  prelude,
845
- html: registry.eagerHtml + links + metas + others + scripts,
1430
+ html: registry.eagerHtml + links + metas + traceMetas + others + scripts,
846
1431
  title,
847
1432
  noScripts
848
1433
  };
849
1434
  }
1435
+ let headBodyHook;
850
1436
  function flushHeadFragment(registry, boundary, nonce) {
851
1437
  const groups = commitHeadBoundary(registry, boundary);
852
1438
  if (!groups.length) return null;
@@ -870,7 +1456,7 @@ function flushHeadFragment(registry, boundary, nonce) {
870
1456
  const t = winner.tags[i];
871
1457
  const attrs = {};
872
1458
  for (const name in t.props) {
873
- if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1459
+ if (name === "children" || name === "ref" || isEventName(name)) continue;
874
1460
  if (!HEAD_ATTR_NAME.test(name)) {
875
1461
  continue;
876
1462
  }
@@ -884,7 +1470,7 @@ function flushHeadFragment(registry, boundary, nonce) {
884
1470
  if (value) attrs.nonce = String(value);
885
1471
  }
886
1472
  const children = t.props.children;
887
- ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
1473
+ ops.push(["a", identity, t.tag, attrs, children == null ? null : headBodyHook ? headBodyHook(t.tag, t.props, String(children)) : String(children)]);
888
1474
  }
889
1475
  }
890
1476
  return ops.length ? ops : null;
@@ -912,19 +1498,9 @@ function normalizeNonce(nonce) {
912
1498
  }
913
1499
  function destinationNonce(nonce, destination) {
914
1500
  if (nonce == null) return undefined;
915
- if (typeof nonce === "string") return nonce || undefined;
916
- const value = nonce[destination];
1501
+ const value = typeof nonce === "string" ? nonce : nonce[destination];
917
1502
  return typeof value === "string" && value ? value : undefined;
918
1503
  }
919
- function scriptNonce(nonce) {
920
- return destinationNonce(nonce, "script");
921
- }
922
- function styleNonce(nonce) {
923
- return destinationNonce(nonce, "style");
924
- }
925
- function asciiLowerCase(value) {
926
- return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
927
- }
928
1504
  function hasNonceProp(props) {
929
1505
  for (const name in props) if (name.length === 5 && asciiLowerCase(name) === "nonce" && props[name] != null) return true;
930
1506
  return false;
@@ -955,6 +1531,10 @@ function nonceDestination(tag, props) {
955
1531
  return "script";
956
1532
  }
957
1533
  }
1534
+ function modulePreloadLink(url, scriptAttr, lowModules) {
1535
+ const priority = lowModules && !lowModules.has(url) ? ' fetchpriority="low"' : "";
1536
+ return `<link rel="modulepreload" href="${url}"${priority}${scriptAttr}>`;
1537
+ }
958
1538
  function nonceAttr(nonce, destination) {
959
1539
  if (!nonce || !destination) return "";
960
1540
  return destination === "script" ? nonce.scriptAttr : nonce.styleAttr;
@@ -962,7 +1542,7 @@ function nonceAttr(nonce, destination) {
962
1542
  function renderHeadAttrHtml(props) {
963
1543
  let attrs = "";
964
1544
  for (const name in props) {
965
- if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1545
+ if (name === "children" || name === "ref" || isEventName(name)) continue;
966
1546
  if (!HEAD_ATTR_NAME.test(name)) {
967
1547
  continue;
968
1548
  }
@@ -975,7 +1555,7 @@ function renderHeadAttrHtml(props) {
975
1555
  function headAttrRecord(props, skipRelHref) {
976
1556
  let attrs = null;
977
1557
  for (const name in props) {
978
- if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
1558
+ if (name === "children" || name === "ref" || isEventName(name)) continue;
979
1559
  if ((name === "rel" || name === "href")) continue;
980
1560
  if (!HEAD_ATTR_NAME.test(name)) continue;
981
1561
  const v = props[name];
@@ -990,6 +1570,7 @@ function renderHeadTagMarkup(tag, props, identity, nonce) {
990
1570
  if (nonce && !hasNonceProp(props)) attrs += nonceAttr(nonce, nonceDestination(tag, props));
991
1571
  if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
992
1572
  let body = props.children == null ? "" : String(props.children);
1573
+ if (headBodyHook) body = headBodyHook(tag, props, body);
993
1574
  if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
994
1575
  return `<${tag}${attrs}>${body}</${tag}>`;
995
1576
  }
@@ -998,10 +1579,51 @@ function useHead(tags) {
998
1579
  if (!ctx || !ctx.registerHeadTags) {
999
1580
  return;
1000
1581
  }
1582
+ headBodyHook = headBodyText;
1001
1583
  ctx.registerHeadTags(tags);
1002
1584
  }
1003
1585
  const VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
1004
- 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])}`;
1586
+ const NOT_NAME = /[\0-\x20\x7F-\x9F"'<>/=]/;
1587
+ const TAG_START = /^[a-zA-Z]/;
1588
+ const tagInfos = /*#__PURE__*/new Map();
1589
+ function tagInfo(tag) {
1590
+ let info = tagInfos.get(tag);
1591
+ if (info === undefined) {
1592
+ if (!TAG_START.test(tag) || NOT_NAME.test(tag)) throw new Error(`"${tag}" is not a valid tag name`);
1593
+ let formDefaults, formAttributes;
1594
+ if (tag === "input" || tag === "option") {
1595
+ formDefaults = Object.create(null);
1596
+ formAttributes = Object.create(null);
1597
+ const state = DOMWithState[tag.toUpperCase()];
1598
+ for (const prop in state) {
1599
+ if (state[prop] === 2) {
1600
+ const attr = prop.slice(7).toLowerCase();
1601
+ formDefaults[attr] = prop;
1602
+ formAttributes[prop] = attr;
1603
+ }
1604
+ }
1605
+ }
1606
+ info = {
1607
+ open: "<" + tag,
1608
+ close: "</" + tag + ">",
1609
+ isVoid: VOID_ELEMENTS.test(tag),
1610
+ textarea: tag === "textarea",
1611
+ raw: tag === "script" || tag === "style",
1612
+ formDefaults,
1613
+ formAttributes
1614
+ };
1615
+ if (tagInfos.size < 512) tagInfos.set(tag, info);
1616
+ }
1617
+ return info;
1618
+ }
1619
+ const safeAttrNames = /*#__PURE__*/new Set();
1620
+ function isAttrName(prop) {
1621
+ if (safeAttrNames.has(prop)) return true;
1622
+ if (prop === "" || NOT_NAME.test(prop)) return false;
1623
+ if (safeAttrNames.size < 512) safeAttrNames.add(prop);
1624
+ return true;
1625
+ }
1626
+ 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,(_$HY.v=_$HY.v||{})[e]=n.hasAttribute("e")?[...n.content.childNodes]:1,o.replaceWith(n.content),n.remove(),_$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])}function $dfe(e,t,k){(t=e.target)&&t.getAttribute&&!t._$dc&&(k=t.getAttribute("data-dfc"))&&(t._$dc=1,$dfc(k))}document.addEventListener("load",$dfe,!0);document.addEventListener("error",$dfe,!0)`;
1005
1627
  const HEAD_SCRIPT = `function $dha(o,i,e,n){for(i=0;i<o.length;i++)e=o[i],"t"==e[0]?((n=document.querySelector("title"))?n.hasAttribute("data-dh")||n.setAttribute("data-dhf",n.textContent):(n=document.createElement("title"),document.head.appendChild(n)),n.textContent=e[1],n.setAttribute("data-dh","title")):"r"==e[0]?$dhr(e[1]):(n=document.createElement(e[2]),Object.keys(e[3]).forEach(function(a){n.setAttribute(a,e[3][a])}),null!=e[4]&&(n.textContent=e[4]),n.setAttribute("data-dh",e[1]),document.head.appendChild(n))}function $dhr(v,l,i){for(l=document.head.querySelectorAll("[data-dh]"),i=0;i<l.length;i++)l[i].getAttribute("data-dh")==v&&l[i].remove()}function $dh(o){_$HY.h?_$HY.h(o):$dha(o)}`;
1006
1628
  function renderToString(code, options = {}) {
1007
1629
  const {
@@ -1011,6 +1633,8 @@ function renderToString(code, options = {}) {
1011
1633
  onHead
1012
1634
  } = options;
1013
1635
  const nonce = normalizeNonce(options.nonce);
1636
+ const requestEvent = peekRequestEvent();
1637
+ const errorScope = requestEvent || {};
1014
1638
  let scripts = "";
1015
1639
  const serializer = createHydrationSerializer({
1016
1640
  scopeId: renderId,
@@ -1022,26 +1646,33 @@ function renderToString(code, options = {}) {
1022
1646
  }
1023
1647
  scripts += script + ";";
1024
1648
  },
1025
- onError: options.onError
1649
+ onError: serializerErrorHook(options.onError)
1026
1650
  });
1027
- const tracking = createAssetTracking();
1651
+ const tracking = createAssetTracking(options.lowPriorityPreloads);
1028
1652
  const headRegistry = createHeadRegistry();
1653
+ let closed = false;
1029
1654
  sharedConfig.context = {
1030
1655
  nonce: options.nonce,
1031
1656
  escape: escape,
1032
1657
  resolve: resolveSSRNode,
1033
1658
  ssr: ssr,
1659
+ errorPolicy: options.onError,
1660
+ _errorScope: errorScope,
1034
1661
  registerHeadTags(tags) {
1035
1662
  registerHeadTags(headRegistry, sharedConfig.context, tracking, null, nonce, tags);
1036
1663
  },
1037
1664
  serialize(id, p) {
1038
- if (sharedConfig.context.noHydrate) return;
1665
+ if (closed) return;
1039
1666
  if (p != null && typeof p === "object" && (typeof p.then === "function" || typeof p[Symbol.asyncIterator] === "function")) {
1040
1667
  throw new Error("Cannot serialize async value in renderToString (id: " + id + "). " + "Use renderToStream for async data.");
1041
1668
  }
1042
1669
  serializer.write(id, p);
1043
1670
  },
1044
- registerAsset(type, value) {
1671
+ registerAsset(type, value, defaultPriority) {
1672
+ if (type === "preload") {
1673
+ registerPreloadLink(tracking, headRegistry, value, nonce);
1674
+ return;
1675
+ }
1045
1676
  if (type === "inline-style") {
1046
1677
  tracking.registerInlineStyle(value);
1047
1678
  return;
@@ -1054,23 +1685,56 @@ function renderToString(code, options = {}) {
1054
1685
  }
1055
1686
  styles.add(value);
1056
1687
  }
1688
+ if (defaultPriority && tracking.lowModules) tracking.lowModules.add(value);
1057
1689
  tracking.emittedAssets.add(value);
1058
1690
  }
1059
1691
  };
1060
1692
  applyAssetTracking(sharedConfig.context, tracking, manifest, noScripts);
1061
1693
  registerEntryAssets(manifest);
1062
- let html = createRoot(d => {
1063
- setTimeout(d);
1064
- return resolveSSRSync(escape(code()));
1065
- }, {
1066
- id: renderId
1067
- });
1068
- serializeFragmentAssets("", tracking.boundaryModules, sharedConfig.context, renderId);
1069
- sharedConfig.context.noHydrate = true;
1070
- serializer.close();
1071
- const head = renderShellHead(headRegistry, nonce, null, noScripts);
1072
- return assembleDocument(resolveSSRSelectValues(html), tracking.emittedAssets, tracking.inlineStyles, scripts.length ? scripts : "", nonce, head, onHead);
1694
+ const context = sharedConfig.context;
1695
+ context.writer = createHydrationWriter(context, () => !closed);
1696
+ if (requestEvent) setRequestErrorHook(requestEvent, options.onError);
1697
+ context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
1698
+ const render = timeDocument(context, context.trace);
1699
+ let dispose;
1700
+ let rootOwner;
1701
+ let rendered = false;
1702
+ try {
1703
+ const html = createRoot(d => {
1704
+ dispose = d;
1705
+ rootOwner = claimRenderRoot(context);
1706
+ if (requestEvent) claimEventRender(requestEvent, context);
1707
+ return resolveSSRSync(escape(code()));
1708
+ }, {
1709
+ id: renderId
1710
+ });
1711
+ serializeFragmentAssets("", tracking.boundaryModules, sharedConfig.context, renderId);
1712
+ closed = true;
1713
+ serializer.close();
1714
+ const head = renderShellHead(headRegistry, nonce, null, noScripts, traceMetaMarkup(context.trace));
1715
+ const document = withShellEnd(assembleDocument(resolveSSRSelectValues(html), tracking.emittedAssets, tracking.preloadLinks, tracking.inlineStyles, scripts.length ? scripts : "", nonce, head, onHead, tracking.lowModules), context, renderId, nonce, noScripts);
1716
+ if (render) render.shell();
1717
+ if (requestEvent && requestEvent.response) {
1718
+ commitResponseStub(requestEvent.response, {
1719
+ event: requestEvent
1720
+ });
1721
+ }
1722
+ rendered = true;
1723
+ return document;
1724
+ } catch (err) {
1725
+ reportServerError(err, {
1726
+ kind: "render",
1727
+ handling: "failed"
1728
+ }, null, options.onError, errorScope);
1729
+ throw err;
1730
+ } finally {
1731
+ if (render) settleRender(render, rootOwner, rendered ? "complete" : "error");
1732
+ context.trace = undefined;
1733
+ if (dispose) dispose();
1734
+ }
1073
1735
  }
1736
+ const SHELL_ABANDONED = Symbol();
1737
+ const ABANDON_RENDER = Symbol();
1074
1738
  function renderToStream(code, options = {}) {
1075
1739
  let {
1076
1740
  onCompleteShell,
@@ -1081,12 +1745,48 @@ function renderToStream(code, options = {}) {
1081
1745
  onHead
1082
1746
  } = options;
1083
1747
  const nonce = normalizeNonce(options.nonce);
1748
+ const requestEvent = peekRequestEvent();
1749
+ if (requestEvent) setRequestErrorHook(requestEvent, options.onError);
1750
+ const errorScope = requestEvent || {};
1751
+ const reportFailure = (err, handling) => {
1752
+ reportServerError(err, {
1753
+ kind: "render",
1754
+ handling
1755
+ }, null, options.onError, errorScope);
1756
+ if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
1757
+ };
1084
1758
  let dispose;
1085
1759
  let dead = false;
1086
- const abandon = () => {
1760
+ let render;
1761
+ let rootOwner;
1762
+ let serializer;
1763
+ let disconnected = false;
1764
+ let onFailed;
1765
+ const defuse = p => {
1766
+ if (p && typeof p.then === "function") p.then(undefined, () => {});
1767
+ };
1768
+ const abandonedSerializer = {
1769
+ write(_, value) {
1770
+ defuse(value);
1771
+ },
1772
+ flush() {},
1773
+ close() {}
1774
+ };
1775
+ const onFailure = complete => {
1776
+ if (dead) return complete(undefined, disconnected || undefined);
1777
+ const prev = onFailed;
1778
+ onFailed = prev ? (sink, gone) => {
1779
+ prev(sink, gone);
1780
+ complete(sink, gone);
1781
+ } : complete;
1782
+ };
1783
+ const abandon = (disconnect, quiet) => {
1087
1784
  if (dead) return;
1088
1785
  dead = true;
1089
1786
  completed = true;
1787
+ if (disconnect) disconnected = disconnect;
1788
+ if (render) settleRender(render, rootOwner, disconnect ? "abandoned" : "error");
1789
+ const sink = writable;
1090
1790
  buffer = {
1091
1791
  write() {}
1092
1792
  };
@@ -1098,13 +1798,30 @@ function renderToStream(code, options = {}) {
1098
1798
  dispose = () => {};
1099
1799
  d();
1100
1800
  }
1801
+ if (serializer && typeof serializer.close === "function") {
1802
+ try {
1803
+ serializer.close();
1804
+ } catch (err) {
1805
+ reportServerError(err, {
1806
+ kind: "render",
1807
+ handling: "serialize"
1808
+ }, null, options.onError, errorScope);
1809
+ }
1810
+ }
1811
+ serializer = abandonedSerializer;
1812
+ if (stubBatch) {
1813
+ for (const p of stubBatch.values()) defuse(p);
1814
+ stubBatch = null;
1815
+ }
1816
+ onFailed && onFailed(sink, disconnect);
1101
1817
  };
1102
1818
  const failRender = err => {
1103
- try {
1104
- options.onError ? options.onError(err) : console.error(err);
1105
- } catch (_) {}
1819
+ reportFailure(err, "failed");
1106
1820
  abandon();
1107
1821
  };
1822
+ const failRootRender = err => {
1823
+ failRender(err);
1824
+ };
1108
1825
  const coalesceWrites = (writeRaw, endRaw) => {
1109
1826
  let buf = "";
1110
1827
  let scheduled = false;
@@ -1133,39 +1850,53 @@ function renderToStream(code, options = {}) {
1133
1850
  };
1134
1851
  const guardSink = w => ({
1135
1852
  write(payload) {
1136
- if (dead) return;
1853
+ if (disconnected) return;
1137
1854
  try {
1138
1855
  w.write(payload);
1139
1856
  } catch (_) {
1140
- abandon();
1857
+ abandon("sink");
1141
1858
  }
1142
1859
  },
1143
1860
  end() {
1144
- if (dead) return;
1861
+ if (disconnected) return;
1145
1862
  try {
1146
1863
  w.end();
1147
1864
  } catch (_) {
1148
- abandon();
1865
+ abandon("sink");
1149
1866
  }
1150
1867
  }
1151
1868
  });
1152
1869
  const blockingPromises = new Set();
1153
1870
  const canBatchStubs = !options.serializer && !options.sink;
1154
1871
  let stubBatch = null;
1155
- const STUB_BATCH_KEY = "$B";
1872
+ let stableOrder = false;
1873
+ let parkedWrites = null;
1874
+ const byKey = (a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
1875
+ let writing = 0;
1876
+ let stranded = false;
1877
+ const handOver = (id, value) => {
1878
+ writing++;
1879
+ try {
1880
+ serializer.write(id, value);
1881
+ } finally {
1882
+ writing--;
1883
+ }
1884
+ };
1885
+ const write = (id, value) => {
1886
+ if (stableOrder && !dead) (parkedWrites ||= []).push([id, value]);else handOver(id, value);
1887
+ };
1888
+ const flushParkedWrites = () => {
1889
+ if (!parkedWrites) return;
1890
+ const writes = parkedWrites.sort(byKey);
1891
+ parkedWrites = null;
1892
+ for (let i = 0; i < writes.length; i++) handOver(writes[i][0], writes[i][1]);
1893
+ };
1156
1894
  const flushStubBatch = () => {
1157
1895
  if (!stubBatch) return;
1158
- const batch = stubBatch;
1896
+ const entries = [...stubBatch];
1159
1897
  stubBatch = null;
1160
- if (batch.size === 1) {
1161
- const [id, p] = batch.entries().next().value;
1162
- serializer.write(id, p);
1163
- return;
1164
- }
1165
- const obj = {};
1166
- for (const [id, p] of batch) obj[id] = p;
1167
- serializer.write(STUB_BATCH_KEY, obj);
1168
- pushTask(`(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r["${STUB_BATCH_KEY}"]})(_$HY.r["${STUB_BATCH_KEY}"])`);
1898
+ if (stableOrder) entries.sort(byKey);
1899
+ for (let i = 0; i < entries.length; i++) handOver(entries[i][0], entries[i][1]);
1169
1900
  };
1170
1901
  let headerEmitted = false;
1171
1902
  const pushTask = task => {
@@ -1181,7 +1912,10 @@ function renderToStream(code, options = {}) {
1181
1912
  }
1182
1913
  };
1183
1914
  const onDone = () => {
1915
+ if (dead) return;
1184
1916
  writeTasks();
1917
+ if (stranded) return abandon();
1918
+ lastBlockingSize = blockingPromises.size;
1185
1919
  doShell();
1186
1920
  onCompleteAll && onCompleteAll({
1187
1921
  write(v) {
@@ -1190,6 +1924,7 @@ function renderToStream(code, options = {}) {
1190
1924
  });
1191
1925
  writable && writable.end();
1192
1926
  completed = true;
1927
+ if (render) settleRender(render, rootOwner, "complete");
1193
1928
  if (firstFlushed) dispose();
1194
1929
  };
1195
1930
  const sink = {
@@ -1199,6 +1934,7 @@ function renderToStream(code, options = {}) {
1199
1934
  fragment(key, value, meta) {
1200
1935
  const deferActivation = !!meta.revealGroup;
1201
1936
  const styles = meta.styles;
1937
+ const tpl = `<template id="${key}"${meta.error ? " e" : ""}>${value}</template>`;
1202
1938
  for (let i = 0; i < styles.inline.length; i++) {
1203
1939
  buffer.write(renderInlineStyle(styles.inline[i], nonce));
1204
1940
  }
@@ -1206,12 +1942,12 @@ function renderToStream(code, options = {}) {
1206
1942
  const styleAttr = nonceAttr(nonce, "style");
1207
1943
  emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
1208
1944
  writeTasks();
1945
+ buffer.write(tpl);
1209
1946
  for (const entry of styles.links) {
1210
- buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}"${styleAttr} onload="$dfc('${key}')" onerror="$dfc('${key}')">` : `<link${entry.attrHtml}${styleAttr} onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
1947
+ buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}"${styleAttr} data-dfc="${key}">` : `<link${entry.attrHtml}${styleAttr} data-dfc="${key}">`);
1211
1948
  }
1212
- buffer.write(`<template id="${key}">${value}</template>`);
1213
1949
  } else {
1214
- buffer.write(`<template id="${key}">${value}</template>`);
1950
+ buffer.write(tpl);
1215
1951
  if (!deferActivation) {
1216
1952
  emitTask(`$df("${key}")`);
1217
1953
  }
@@ -1222,7 +1958,9 @@ function renderToStream(code, options = {}) {
1222
1958
  },
1223
1959
  asset(type, value) {
1224
1960
  if (type === "module") {
1225
- buffer.write(`<link rel="modulepreload" href="${value}"${nonceAttr(nonce, "script")}>`);
1961
+ buffer.write(modulePreloadLink(value, nonceAttr(nonce, "script"), tracking.lowModules));
1962
+ } else if (type === "preload") {
1963
+ buffer.write(`<link${value.attrHtml}>`);
1226
1964
  } else if (type === "inline-style") {
1227
1965
  buffer.write(renderInlineStyle(value, nonce));
1228
1966
  } else if (type === "head-tag") {
@@ -1230,16 +1968,20 @@ function renderToStream(code, options = {}) {
1230
1968
  }
1231
1969
  },
1232
1970
  shell(shellHtml, meta) {
1233
- buffer.write(assembleDocument(shellHtml, meta.preloads, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
1971
+ buffer.write(withShellEnd(assembleDocument(shellHtml, meta.preloads, meta.preloadLinks, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead, tracking.lowModules), context, renderId, nonce, noScripts));
1234
1972
  },
1235
1973
  ...options.sink
1236
1974
  };
1237
- const serializer = (options.serializer || createHydrationSerializer)({
1975
+ serializer = (options.serializer || createHydrationSerializer)({
1238
1976
  scopeId: options.renderId,
1239
1977
  plugins: options.plugins,
1240
1978
  onData: payload => sink.data(payload),
1241
1979
  onDone,
1242
- onError: options.onError
1980
+ onError: err => {
1981
+ reportFailure(err, "serialize");
1982
+ if (!writing && !options.serializer && !firstFlushed) stranded = true;
1983
+ },
1984
+ late: rejectUnserializedKey
1243
1985
  });
1244
1986
  let rootAssetsSerialized = false;
1245
1987
  const serializeRootAssets = () => {
@@ -1249,7 +1991,7 @@ function renderToStream(code, options = {}) {
1249
1991
  };
1250
1992
  let holds = 0;
1251
1993
  const flushEnd = () => {
1252
- if (!registry.size && !holds) {
1994
+ if (!registry.size && !holds && !rootHoles) {
1253
1995
  serializeRootAssets();
1254
1996
  queue(() => queue(() => {
1255
1997
  if (context.live.end) {
@@ -1258,11 +2000,87 @@ function renderToStream(code, options = {}) {
1258
2000
  end();
1259
2001
  }
1260
2002
  flushStubBatch();
2003
+ flushParkedWrites();
1261
2004
  serializer.flush();
1262
2005
  }));
1263
2006
  }
1264
2007
  };
1265
2008
  const registry = new Map();
2009
+ const pendingSerialized = new Map();
2010
+ const guardedChannels = new WeakMap();
2011
+ const verdictNow = error => {
2012
+ throw ssrSanitizeError(error, null, undefined, undefined, errorScope);
2013
+ };
2014
+ const borderForm = value => toBorderForm(value);
2015
+ const guardIterable = iterable => ({
2016
+ [Symbol.asyncIterator]() {
2017
+ const iterator = iterable[Symbol.asyncIterator]();
2018
+ return {
2019
+ next: value => iterator.next(value).then(undefined, verdictNow),
2020
+ return: value => iterator.return ? iterator.return(value) : Promise.resolve({
2021
+ done: true,
2022
+ value
2023
+ }),
2024
+ throw: error => iterator.throw ? iterator.throw(error) : Promise.reject(error)
2025
+ };
2026
+ }
2027
+ });
2028
+ const guardStream = source => {
2029
+ const reader = source.getReader();
2030
+ return new ReadableStream({
2031
+ pull: c => reader.read().then(r => r.done ? c.close() : c.enqueue(r.value), e => {
2032
+ try {
2033
+ verdictNow(e);
2034
+ } catch (sanitized) {
2035
+ c.error(sanitized);
2036
+ }
2037
+ }),
2038
+ cancel: reason => reader.cancel(reason)
2039
+ });
2040
+ };
2041
+ const guardChannel = p => {
2042
+ if (!p || typeof p !== "object" || "__SEROVAL_STREAM__" in p) return p;
2043
+ let guarded = guardedChannels.get(p);
2044
+ if (guarded !== undefined) return guarded;
2045
+ if (typeof p.then === "function") {
2046
+ guarded = p.then(borderForm, verdictNow);
2047
+ } else if (typeof ReadableStream === "function" && p instanceof ReadableStream) {
2048
+ guarded = guardStream(p);
2049
+ } else {
2050
+ const border = borderForm(p);
2051
+ guarded = typeof border[Symbol.asyncIterator] === "function" ? guardIterable(border) : border;
2052
+ if (guarded === p) return p;
2053
+ }
2054
+ guardedChannels.set(p, guarded);
2055
+ return guarded;
2056
+ };
2057
+ const trackSerialized = (id, p) => {
2058
+ let settle;
2059
+ const raced = Promise.race([p, new Promise(r => settle = r)]);
2060
+ raced.catch(() => {});
2061
+ pendingSerialized.set(id, settle);
2062
+ const drop = () => pendingSerialized.delete(id);
2063
+ p.then(drop, drop);
2064
+ return raced;
2065
+ };
2066
+ const abandonSubtree = (key, error) => {
2067
+ if (key == null) return;
2068
+ for (const [k, entry] of registry) {
2069
+ if (k != null && k.length > key.length && k.startsWith(key)) {
2070
+ registry.delete(k);
2071
+ entry.resolve();
2072
+ }
2073
+ }
2074
+ const unregister = [];
2075
+ for (const [id, settle] of pendingSerialized) {
2076
+ if (id.startsWith(key)) {
2077
+ pendingSerialized.delete(id);
2078
+ settle();
2079
+ if (!stubBatch?.delete(id)) unregister.push(`delete _$HY.r[${JSON.stringify(id)}]`);
2080
+ }
2081
+ }
2082
+ if (unregister.length && !options.sink) pushTask(unregister.join(";"));
2083
+ };
1266
2084
  const writeTasks = () => {
1267
2085
  if (tasks.length && !completed && firstFlushed) {
1268
2086
  buffer.write(`<script${nonceAttr(nonce, "script")}>${tasks}</script>`);
@@ -1304,12 +2122,18 @@ function renderToStream(code, options = {}) {
1304
2122
  }
1305
2123
  let rootHoles = null;
1306
2124
  let nextHoleId = 0;
2125
+ let parkedInlines = null;
2126
+ function inlineFragment(key, value) {
2127
+ if (rootHoles && !html.includes(`<template id="pl-${key}">`)) {
2128
+ (parkedInlines ||= new Map()).set(key, value);
2129
+ } else html = replacePlaceholder(html, key, value);
2130
+ }
1307
2131
  let buffer = {
1308
2132
  write(payload) {
1309
2133
  tmp += payload;
1310
2134
  }
1311
2135
  };
1312
- const tracking = createAssetTracking();
2136
+ const tracking = createAssetTracking(options.lowPriorityPreloads);
1313
2137
  const headRegistry = createHeadRegistry();
1314
2138
  let headScriptFlushed = false;
1315
2139
  const emitHeadOps = (key, ops) => {
@@ -1320,6 +2144,8 @@ function renderToStream(code, options = {}) {
1320
2144
  sharedConfig.context = context = {
1321
2145
  async: true,
1322
2146
  nonce: options.nonce,
2147
+ document: !options.sink,
2148
+ edges: !!options.plugins && options.plugins.some(p => p.tag === "solid/server-component"),
1323
2149
  live: {},
1324
2150
  registerHeadTags(tags) {
1325
2151
  registerHeadTags(headRegistry, context, tracking,
@@ -1332,7 +2158,12 @@ function renderToStream(code, options = {}) {
1332
2158
  }
1333
2159
  }, nonce, tags);
1334
2160
  },
1335
- registerAsset(type, value) {
2161
+ registerAsset(type, value, defaultPriority) {
2162
+ if (type === "preload") {
2163
+ const entry = registerPreloadLink(tracking, headRegistry, value, nonce);
2164
+ if (entry && firstFlushed) sink.asset("preload", entry);
2165
+ return;
2166
+ }
1336
2167
  if (type === "inline-style") {
1337
2168
  const entry = tracking.registerInlineStyle(value);
1338
2169
  if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
@@ -1349,6 +2180,7 @@ function renderToStream(code, options = {}) {
1349
2180
  }
1350
2181
  styles.add(value);
1351
2182
  }
2183
+ if (defaultPriority && tracking.lowModules) tracking.lowModules.add(value);
1352
2184
  if (!tracking.emittedAssets.has(value)) {
1353
2185
  tracking.emittedAssets.add(value);
1354
2186
  if (firstFlushed) sink.asset(type, value);
@@ -1376,19 +2208,20 @@ function renderToStream(code, options = {}) {
1376
2208
  html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
1377
2209
  },
1378
2210
  serialize(id, p, deferStream) {
1379
- if (sharedConfig.context.noHydrate) return;
1380
- if (!firstFlushed && p && typeof p === "object" && "then" in p) {
1381
- if (deferStream) {
2211
+ p = guardChannel(p);
2212
+ if (p && typeof p === "object" && typeof p.then === "function") {
2213
+ if (!firstFlushed && deferStream) {
1382
2214
  blockingPromises.add(p);
1383
- p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
2215
+ p.then(d => write(id, d)).catch(e => write(id, e));
1384
2216
  return;
1385
2217
  }
1386
- if (canBatchStubs && !shellCompleted) {
2218
+ p = trackSerialized(id, p);
2219
+ if (!firstFlushed && canBatchStubs && !shellCompleted && !dead) {
1387
2220
  (stubBatch ||= new Map()).set(id, p);
1388
2221
  return;
1389
2222
  }
1390
2223
  }
1391
- serializer.write(id, p);
2224
+ write(id, p);
1392
2225
  },
1393
2226
  escape: escape,
1394
2227
  resolve: resolveSSRNode,
@@ -1416,19 +2249,26 @@ function renderToStream(code, options = {}) {
1416
2249
  if (!registry.has(key)) {
1417
2250
  let resolve, reject;
1418
2251
  const p = new Promise((r, rej) => (resolve = r, reject = rej));
2252
+ defuse(p);
1419
2253
  registry.set(key, {
1420
2254
  resolve: err => queue(() => queue(() => {
1421
- err ? reject(err) : resolve(true);
2255
+ err ? reject(ssrSanitizeError(err, null, undefined, undefined, errorScope)) : resolve(true);
1422
2256
  queue(flushEnd);
1423
2257
  }))
1424
2258
  });
1425
- if (canBatchStubs && !shellCompleted) (stubBatch ||= new Map()).set(key + "_fr", p);else serializer.write(key + "_fr", p);
2259
+ if (canBatchStubs && !shellCompleted && !dead) (stubBatch ||= new Map()).set(key + "_fr", p);else write(key + "_fr", p);
1426
2260
  }
1427
- return (value, error) => {
2261
+ return (value, error, escaped) => {
1428
2262
  if (registry.has(key)) {
1429
2263
  const item = registry.get(key);
1430
2264
  registry.delete(key);
1431
- if (item.children) {
2265
+ if (error) abandonSubtree(key);
2266
+ if (error && escaped) {
2267
+ const wire = ssrSanitizeError(error, null, undefined, undefined, errorScope);
2268
+ const message = wire instanceof Error ? wire.message : String(wire);
2269
+ if (sink.error) sink.error("", message);else if (context.live && context.live.error) context.live.error(escaped.frame, message);
2270
+ }
2271
+ if (item.children && !error) {
1432
2272
  for (const k in item.children) {
1433
2273
  value = replacePlaceholder(value, k, item.children[k]);
1434
2274
  }
@@ -1447,7 +2287,7 @@ function renderToStream(code, options = {}) {
1447
2287
  if (!completed) {
1448
2288
  if (error) dropHeadBoundary(headRegistry, key);
1449
2289
  if (!firstFlushed) {
1450
- queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
2290
+ queue(() => inlineFragment(key, value !== undefined ? value : ""));
1451
2291
  serializeFragmentAssets(key, tracking.boundaryModules, context);
1452
2292
  item.resolve(error);
1453
2293
  } else {
@@ -1455,10 +2295,10 @@ function renderToStream(code, options = {}) {
1455
2295
  const styles = collectStreamStyles(key, tracking, headStyles);
1456
2296
  const headOps = error ? null : flushHeadFragment(headRegistry, key, nonce);
1457
2297
  if (headOps) emitHeadOps(key, headOps);
1458
- sink.fragment(key, resolveSSRSelectValues(value !== undefined ? value : " "), {
2298
+ sink.fragment(key, resolveSSRSelectValues(value !== undefined ? value : error ? "" : " "), {
1459
2299
  styles,
1460
2300
  revealGroup,
1461
- error
2301
+ error: error ? ssrSanitizeError(error, null, undefined, undefined, errorScope) : error
1462
2302
  });
1463
2303
  item.resolve(error);
1464
2304
  }
@@ -1484,26 +2324,71 @@ function renderToStream(code, options = {}) {
1484
2324
  };
1485
2325
  applyAssetTracking(context, tracking, manifest, noScripts);
1486
2326
  context.failRender = failRender;
2327
+ context.errorPolicy = options.onError;
2328
+ context._errorScope = errorScope;
2329
+ context.flushed = () => firstFlushed;
2330
+ context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
2331
+ render = timeDocument(context, context.trace);
1487
2332
  registerEntryAssets(manifest);
1488
- let html = createRoot(d => {
1489
- dispose = d;
1490
- const res = resolveSSRNode(escape(code()));
1491
- if (!res.h.length) return res.t[0];
1492
- rootHoles = [];
1493
- let out = res.t[0];
1494
- for (let i = 0; i < res.h.length; i++) {
1495
- const id = nextHoleId++;
1496
- rootHoles.push({
1497
- id,
1498
- fn: res.h[i]
1499
- });
1500
- out += `<!--rh${id}-->` + res.t[i + 1];
1501
- }
1502
- for (const p of res.p) blockingPromises.add(p);
1503
- return out;
1504
- }, {
1505
- id: renderId
1506
- });
2333
+ context.writer = createHydrationWriter(context, () => !completed);
2334
+ const signal = options.signal;
2335
+ let cancelled = false;
2336
+ const onAbort = signal ? () => {
2337
+ if (dead) return;
2338
+ cancelled = true;
2339
+ abandon("signal", !!(signal.reason && signal.reason.quiet === true));
2340
+ } : undefined;
2341
+ const endEdges = context.edges ? beginEdgesRender() : undefined;
2342
+ let html;
2343
+ try {
2344
+ html = createRoot(d => {
2345
+ dispose = () => {
2346
+ context.trace = undefined;
2347
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2348
+ if (endEdges) endEdges();
2349
+ try {
2350
+ d();
2351
+ } catch (err) {
2352
+ reportFailure(err, "failed");
2353
+ }
2354
+ };
2355
+ rootOwner = claimRenderRoot(context);
2356
+ if (requestEvent) claimEventRender(requestEvent, context);
2357
+ let res;
2358
+ try {
2359
+ res = resolveSSRNode(escape(code()));
2360
+ } catch (err) {
2361
+ reportServerError(err, {
2362
+ kind: "render",
2363
+ handling: "failed"
2364
+ }, null, options.onError, errorScope);
2365
+ throw err;
2366
+ }
2367
+ if (!res.h.length) return res.t[0];
2368
+ rootHoles = [];
2369
+ let out = res.t[0];
2370
+ for (let i = 0; i < res.h.length; i++) {
2371
+ const id = nextHoleId++;
2372
+ rootHoles.push({
2373
+ id,
2374
+ fn: res.h[i]
2375
+ });
2376
+ out += `<!--rh${id}-->` + res.t[i + 1];
2377
+ }
2378
+ for (const p of res.p) blockingPromises.add(p);
2379
+ return out;
2380
+ }, {
2381
+ id: renderId
2382
+ });
2383
+ } catch (err) {
2384
+ if (endEdges) endEdges();
2385
+ throw err;
2386
+ }
2387
+ if (onAbort) {
2388
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
2389
+ once: true
2390
+ });
2391
+ }
1507
2392
  function resolveRootHoles() {
1508
2393
  if (!rootHoles) return true;
1509
2394
  const pending = [];
@@ -1529,6 +2414,13 @@ function renderToStream(code, options = {}) {
1529
2414
  for (const p of res.p) blockingPromises.add(p);
1530
2415
  }
1531
2416
  }
2417
+ if (parkedInlines) {
2418
+ for (const [key, value] of parkedInlines) {
2419
+ if (!html.includes(`<template id="pl-${key}">`)) continue;
2420
+ html = replacePlaceholder(html, key, value);
2421
+ parkedInlines.delete(key);
2422
+ }
2423
+ }
1532
2424
  if (pending.length) {
1533
2425
  rootHoles = pending;
1534
2426
  return false;
@@ -1539,9 +2431,9 @@ function renderToStream(code, options = {}) {
1539
2431
  function doShell() {
1540
2432
  if (shellCompleted) return;
1541
2433
  sharedConfig.context = context;
1542
- const blockersBefore = blockingPromises.size;
2434
+ if (blockingPromises.size !== lastBlockingSize) return;
1543
2435
  if (!resolveRootHoles()) return;
1544
- if (blockingPromises.size !== blockersBefore) return;
2436
+ if (blockingPromises.size !== lastBlockingSize) return;
1545
2437
  if (!headShellReady(headRegistry, p => blockingPromises.add(p))) return;
1546
2438
  headStyles = new Set();
1547
2439
  for (const url of tracking.emittedAssets) {
@@ -1549,9 +2441,11 @@ function renderToStream(code, options = {}) {
1549
2441
  }
1550
2442
  serializeRootAssets();
1551
2443
  flushStubBatch();
1552
- const head = renderShellHead(headRegistry, nonce, k => registry.has(k), noScripts);
2444
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k), noScripts, traceMetaMarkup(context.trace));
2445
+ if (render) render.shell();
1553
2446
  sink.shell(resolveSSRSelectValues(html), {
1554
2447
  preloads: tracking.emittedAssets,
2448
+ preloadLinks: tracking.preloadLinks,
1555
2449
  inlineStyles: tracking.inlineStyles,
1556
2450
  tasks,
1557
2451
  head
@@ -1568,21 +2462,30 @@ function renderToStream(code, options = {}) {
1568
2462
  let lastBlockingSize = -1;
1569
2463
  let lastRegistrySize = -1;
1570
2464
  let drainTurn = 0;
1571
- const scheduleFlush = fn => {
2465
+ let graced = false;
2466
+ const scheduleFlush = (fn, awaited) => {
1572
2467
  const attempt = () => {
1573
- flushStubBatch();
2468
+ if (!stableOrder) flushStubBatch();
1574
2469
  if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1575
2470
  if (registry.size !== lastRegistrySize) drainTurn = 0;
1576
2471
  lastRegistrySize = registry.size;
1577
2472
  queue(attempt);
1578
2473
  return;
1579
2474
  }
2475
+ if (!graced && registry.size) {
2476
+ graced = true;
2477
+ lastRegistrySize = -1;
2478
+ drainTurn = 0;
2479
+ deferFlush(attempt);
2480
+ return;
2481
+ }
1580
2482
  fn();
1581
2483
  };
1582
- const progressed = blockingPromises.size !== lastBlockingSize;
1583
- lastBlockingSize = blockingPromises.size;
2484
+ const progressed = awaited !== lastBlockingSize;
2485
+ lastBlockingSize = awaited;
1584
2486
  lastRegistrySize = -1;
1585
2487
  drainTurn = 0;
2488
+ graced = false;
1586
2489
  progressed ? queue(attempt) : setTimeout(attempt);
1587
2490
  };
1588
2491
  let cachedReadable;
@@ -1596,28 +2499,42 @@ function renderToStream(code, options = {}) {
1596
2499
  const pipeToImpl = w => {
1597
2500
  let resolve;
1598
2501
  const p = new Promise(r => resolve = r);
2502
+ let closeOnAbort = () => w.close().catch(() => {});
2503
+ onFailure((sink, gone) => {
2504
+ try {
2505
+ if (!gone) {
2506
+ if (sink) sink.end();else w.close().catch(() => {});
2507
+ } else if (gone === "signal") closeOnAbort();
2508
+ } catch (_) {}
2509
+ resolve();
2510
+ });
1599
2511
  function flush() {
1600
- allSettled(blockingPromises).then(() => {
2512
+ allSettled(blockingPromises).then(awaited => {
1601
2513
  scheduleFlush(() => {
1602
2514
  if (dead) return resolve();
1603
2515
  try {
1604
2516
  doShell();
1605
2517
  } catch (err) {
1606
- failRender(err);
1607
- return resolve();
2518
+ failRootRender(err);
2519
+ return;
1608
2520
  }
1609
2521
  if (!shellCompleted) return flush();
2522
+ if (stranded) return abandon();
1610
2523
  const encoder = new TextEncoder();
1611
2524
  const writer = w.getWriter();
1612
2525
  let pendingWrites = Promise.resolve();
1613
2526
  let ended = false;
1614
2527
  const failed = () => {
1615
2528
  if (!ended) {
1616
- abandon();
2529
+ abandon("consumer");
1617
2530
  resolve();
1618
2531
  }
1619
2532
  };
1620
2533
  writer.closed && writer.closed.catch(failed);
2534
+ closeOnAbort = () => {
2535
+ ended = true;
2536
+ pendingWrites.then(() => writer.close()).catch(() => {});
2537
+ };
1621
2538
  buffer = writable = coalesceWrites(payload => {
1622
2539
  pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
1623
2540
  }, () => {
@@ -1635,7 +2552,7 @@ function renderToStream(code, options = {}) {
1635
2552
  dispose();
1636
2553
  writable.end();
1637
2554
  } else flushEnd();
1638
- });
2555
+ }, awaited);
1639
2556
  });
1640
2557
  }
1641
2558
  flush();
@@ -1643,8 +2560,15 @@ function renderToStream(code, options = {}) {
1643
2560
  };
1644
2561
  return {
1645
2562
  then(onFulfilled, onRejected) {
1646
- const p = new Promise(resolve => {
2563
+ if (canBatchStubs) stableOrder = true;
2564
+ const freezeHead = () => {
2565
+ if (requestEvent && requestEvent.response) commitResponseStub(requestEvent.response, {
2566
+ event: requestEvent
2567
+ });
2568
+ };
2569
+ const p = new Promise((resolve, reject) => {
1647
2570
  function complete() {
2571
+ freezeHead();
1648
2572
  dispose();
1649
2573
  resolve(tmp);
1650
2574
  }
@@ -1655,18 +2579,20 @@ function renderToStream(code, options = {}) {
1655
2579
  complete();
1656
2580
  };
1657
2581
  } else onCompleteAll = complete;
2582
+ onFailure(() => cancelled ? reject(signal.reason) : resolve(tmp));
1658
2583
  function flush() {
1659
- allSettled(blockingPromises).then(() => {
2584
+ allSettled(blockingPromises).then(awaited => {
1660
2585
  scheduleFlush(() => {
2586
+ if (dead) return;
2587
+ sharedConfig.context = context;
1661
2588
  try {
1662
- const blockersBefore = blockingPromises.size;
1663
- if (!resolveRootHoles() || blockingPromises.size !== blockersBefore || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
2589
+ if (blockingPromises.size !== lastBlockingSize || !resolveRootHoles() || blockingPromises.size !== lastBlockingSize || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
1664
2590
  } catch (err) {
1665
- failRender(err);
1666
- return resolve(tmp);
2591
+ failRootRender(err);
2592
+ return;
1667
2593
  }
1668
2594
  queue(flushEnd);
1669
- });
2595
+ }, awaited);
1670
2596
  });
1671
2597
  }
1672
2598
  flush();
@@ -1675,20 +2601,25 @@ function renderToStream(code, options = {}) {
1675
2601
  },
1676
2602
  pipe(w) {
1677
2603
  claimConsumer("pipe");
2604
+ const abandoned = w[SHELL_ABANDONED];
2605
+ onFailure((sink, gone) => {
2606
+ try {
2607
+ if (!gone) sink ? sink.end() : abandoned ? abandoned() : w.end();else if (!sink && abandoned) abandoned();else if (gone === "signal") w.end();
2608
+ } catch (_) {}
2609
+ });
2610
+ if (abandoned) w[ABANDON_RENDER] = abandon;
1678
2611
  function flush() {
1679
- allSettled(blockingPromises).then(() => {
2612
+ allSettled(blockingPromises).then(awaited => {
1680
2613
  scheduleFlush(() => {
1681
2614
  if (dead) return;
1682
2615
  try {
1683
2616
  doShell();
1684
2617
  } catch (err) {
1685
- failRender(err);
1686
- try {
1687
- w.end();
1688
- } catch (_) {}
2618
+ failRootRender(err);
1689
2619
  return;
1690
2620
  }
1691
2621
  if (!shellCompleted) return flush();
2622
+ if (stranded) return abandon();
1692
2623
  const sink = guardSink(w);
1693
2624
  buffer = writable = coalesceWrites(sink.write, sink.end);
1694
2625
  buffer.write(tmp);
@@ -1698,7 +2629,7 @@ function renderToStream(code, options = {}) {
1698
2629
  dispose();
1699
2630
  writable.end();
1700
2631
  } else flushEnd();
1701
- });
2632
+ }, awaited);
1702
2633
  });
1703
2634
  }
1704
2635
  flush();
@@ -1719,11 +2650,15 @@ function renderToStream(code, options = {}) {
1719
2650
  };
1720
2651
  }
1721
2652
  function HydrationScript(props) {
1722
- const nonce = scriptNonce(sharedConfig.context && sharedConfig.context.nonce);
1723
- return ssr(generateHydrationScript({
1724
- nonce,
2653
+ if (sharedConfig.context) sharedConfig.context.bootstrap = true;
2654
+ const {
2655
+ eventNames,
2656
+ nonce
2657
+ } = {
2658
+ nonce: sharedConfig.context && sharedConfig.context.nonce,
1725
2659
  ...props
1726
- }));
2660
+ };
2661
+ return ssr(hydrationBootstrap(eventNames, destinationNonce(nonce, "script"), true));
1727
2662
  }
1728
2663
  function ssrGroup(fn, n) {
1729
2664
  fn.$g = n;
@@ -1812,6 +2747,10 @@ function ssrGroupSlot(fn, idx) {
1812
2747
  }
1813
2748
  };
1814
2749
  }
2750
+ function wireErrorMessage(err, scope) {
2751
+ const wire = ssrSanitizeError(err, null, undefined, undefined, scope);
2752
+ return String(wire && wire.message || wire);
2753
+ }
1815
2754
  const holePositionCache = new WeakMap();
1816
2755
  function holeContentPositions(t) {
1817
2756
  let cached = holePositionCache.get(t);
@@ -1871,19 +2810,86 @@ function holeContentPositions(t) {
1871
2810
  holePositionCache.set(t, cached);
1872
2811
  return cached;
1873
2812
  }
1874
- function createLiveHoles(sink, scoped) {
2813
+ function createLiveHoles(sink, scoped, settled, errorScope) {
1875
2814
  let nextId = 0;
1876
2815
  const stamp = typeof creationStamp === "function" ? creationStamp : () => 0;
1877
2816
  const inScope = scoped && typeof inServerComponentScope === "function" ? inServerComponentScope : null;
1878
- const stripMarkers = html => html.replace(/<!--lh:\/?\d+-->/g, "");
2817
+ const stripMarkers = html => html.replace(/<!--lh:\/?\d+-->| data-lha="\d+"/g, "");
2818
+ const swept = (owner, ctx, fn) => {
2819
+ const prev = sharedConfig.context;
2820
+ sharedConfig.context = ctx;
2821
+ let dispose;
2822
+ let before;
2823
+ const run = () => createRoot(d => {
2824
+ dispose = d;
2825
+ before = stamp();
2826
+ return fn();
2827
+ }, {
2828
+ transparent: true
2829
+ });
2830
+ try {
2831
+ return owner ? runWithOwner(owner, run) : run();
2832
+ } finally {
2833
+ sharedConfig.context = prev;
2834
+ engine.sweptOwners = before !== undefined && stamp() !== before;
2835
+ if (dispose) dispose();
2836
+ }
2837
+ };
2838
+ const stripRow = html => html.replace(/<!--lh:\/?\d+-->| data-lha="\d+"|<!--lr-->/g, "");
2839
+ const rowsOf = v => Array.isArray(v) && v.$rows ? v : null;
2840
+ function holeValue(hole) {
2841
+ const b = hole.$lhBinding;
2842
+ if (b) {
2843
+ const v = hole();
2844
+ return b.fn && rowsOf(b.fn()) || v;
2845
+ }
2846
+ if (!hole.$fn) return hole();
2847
+ const v = hole.$fn();
2848
+ return rowsOf(v) || escape(v);
2849
+ }
2850
+ function resolveValue(value, res) {
2851
+ if (!Array.isArray(value) || !value.$rows) {
2852
+ resolveSSRNode(value, res);
2853
+ return null;
2854
+ }
2855
+ let rows = [];
2856
+ for (const row of value) {
2857
+ const r = resolveSSRNode(escape(row));
2858
+ res.t[res.t.length - 1] += "<!--lr-->" + r.t[0];
2859
+ if (r.h.length) {
2860
+ res.t.push(...r.t.slice(1));
2861
+ res.h.push(...r.h);
2862
+ res.p.push(...r.p);
2863
+ rows = null;
2864
+ } else if (rows) rows.push(engine.sweeping ? r.t[0] : stripRow(r.t[0]));
2865
+ }
2866
+ return rows;
2867
+ }
2868
+ function rowOps(last, rows) {
2869
+ const ops = [];
2870
+ const html = [];
2871
+ for (let i = 0; i < rows.length; i++) if (i >= last.length || rows[i] !== last[i]) {
2872
+ const patch = i < last.length ? rowPatch(last[i], rows[i]) : null;
2873
+ ops.push(patch ? [i, patch.p] : [i, rows[i]]);
2874
+ html.push(rows[i]);
2875
+ }
2876
+ if (ops.length >= rows.length) return null;
2877
+ return Object.defineProperty({
2878
+ n: rows.length,
2879
+ r: ops
2880
+ }, ROW_HTML, {
2881
+ value: html
2882
+ });
2883
+ }
1879
2884
  function resolveHoleValue(hole) {
1880
2885
  const result = {
1881
2886
  t: [""],
1882
2887
  h: [],
1883
- p: []
2888
+ p: [],
2889
+ rows: null
1884
2890
  };
1885
2891
  try {
1886
- resolveSSRNode(hole(), result);
2892
+ result.rows = resolveValue(holeValue(hole), result);
1887
2893
  } catch (err) {
1888
2894
  const wrap = buildAsyncWrap(err, hole);
1889
2895
  if (!wrap) throw err;
@@ -1901,12 +2907,88 @@ function createLiveHoles(sink, scoped) {
1901
2907
  }
1902
2908
  b.children.length = 0;
1903
2909
  }
2910
+ let tops = 0;
2911
+ const ids = new Map();
2912
+ const scopeFor = hole => {
2913
+ const p = engine.scope;
2914
+ return {
2915
+ id: undefined,
2916
+ p,
2917
+ i: p ? p.c++ : tops++,
2918
+ n: null,
2919
+ c: 0,
2920
+ h: hole
2921
+ };
2922
+ };
2923
+ const scopeId = s => s.id !== undefined ? s.id : s.id = s.p ? scopeId(s.p) + "." + s.i : String(s.i);
2924
+ const collect = (v, id, forget) => (v.occ || (v.occ = new Map())).set(id, forget);
2925
+ function rescope(b, hole, fn) {
2926
+ const prevScope = engine.scope;
2927
+ const prevVisit = engine.visit;
2928
+ engine.scope = {
2929
+ id: scopeId(b.scope),
2930
+ p: null,
2931
+ i: 0,
2932
+ n: null,
2933
+ c: 0,
2934
+ h: hole
2935
+ };
2936
+ const visit = engine.visit = {
2937
+ occ: null
2938
+ };
2939
+ try {
2940
+ return fn();
2941
+ } finally {
2942
+ engine.scope = prevScope;
2943
+ engine.visit = prevVisit;
2944
+ b.next = visit.occ;
2945
+ }
2946
+ }
2947
+ function settleOccurrences(b) {
2948
+ const occ = b.next;
2949
+ b.next = null;
2950
+ if (b.occ) for (const [id, forget] of b.occ) if (!occ || !occ.has(id)) forget();
2951
+ b.occ = occ;
2952
+ if (occ) for (let a = b.up; a; a = a.up) for (const [id, forget] of occ) collect(a, id, forget);
2953
+ }
2954
+ function leave(b, parent, scope, visit) {
2955
+ engine.parent = parent;
2956
+ engine.scope = scope;
2957
+ engine.visit = visit;
2958
+ if (visit && b.occ) for (const [id, forget] of b.occ) collect(visit, id, forget);
2959
+ }
1904
2960
  const engine = {
1905
2961
  suppressed: 0,
1906
2962
  sweeping: false,
1907
2963
  parent: null,
1908
- recordStamp: 0,
1909
2964
  gateHit: false,
2965
+ sweptOwners: false,
2966
+ scope: null,
2967
+ visit: null,
2968
+ dry: false,
2969
+ slotId(prop, given) {
2970
+ const s = engine.scope;
2971
+ if (!s) return given;
2972
+ const n = s.n || (s.n = Object.create(null));
2973
+ const i = n[prop] || 0;
2974
+ n[prop] = i + 1;
2975
+ const sid = scopeId(s);
2976
+ const at = sid + "." + i + "\0" + prop;
2977
+ if (given !== undefined) {
2978
+ ids.set(at, given);
2979
+ return given;
2980
+ }
2981
+ return ids.get(at) || `${prop}#~${sid}.${i}`;
2982
+ },
2983
+ seen(id, forget) {
2984
+ if (engine.visit) collect(engine.visit, id, forget);
2985
+ },
2986
+ nest(hole) {
2987
+ const s = engine.scope;
2988
+ if (!s || s.h === hole || hole.$lhSkip || inScope && !inScope()) return undefined;
2989
+ engine.scope = scopeFor(hole);
2990
+ return s;
2991
+ },
1910
2992
  content(hole) {
1911
2993
  if (hole.$lhSuppress) {
1912
2994
  const r = {
@@ -1914,10 +2996,12 @@ function createLiveHoles(sink, scoped) {
1914
2996
  h: [],
1915
2997
  p: []
1916
2998
  };
1917
- engine.suppressed++;
1918
- try {
2999
+ let rows = null;
3000
+ const b = hole.$lhBinding;
3001
+ const run = () => {
3002
+ engine.suppressed++;
1919
3003
  try {
1920
- resolveSSRNode(hole(), r);
3004
+ rows = resolveValue(holeValue(hole), r);
1921
3005
  } catch (err) {
1922
3006
  const wrap = buildAsyncWrap(err, hole);
1923
3007
  if (wrap) {
@@ -1925,45 +3009,53 @@ function createLiveHoles(sink, scoped) {
1925
3009
  r.p.push(wrap.p);
1926
3010
  r.t.push("");
1927
3011
  }
3012
+ } finally {
3013
+ engine.suppressed--;
1928
3014
  }
1929
- } finally {
1930
- engine.suppressed--;
1931
- }
1932
- const b = hole.$lhBinding;
3015
+ };
3016
+ b && !engine.sweeping ? rescope(b, hole, run) : run();
1933
3017
  if (b && !b.closed && !r.h.length && !engine.sweeping) {
1934
3018
  b.last = stripMarkers(r.t[0]);
3019
+ b.rows = rows;
3020
+ settleOccurrences(b);
1935
3021
  }
1936
3022
  return r.h.length ? r : r.t[0];
1937
3023
  }
1938
3024
  if (engine.suppressed || engine.sweeping) return null;
1939
3025
  if (hole.$lhSkip) return null;
1940
3026
  if (inScope && !inScope()) return null;
1941
- const recordsBefore = engine.recordStamp;
1942
3027
  const ownersBefore = stamp();
1943
3028
  const owner = getOwner();
3029
+ const holeCtx = sharedConfig.context;
1944
3030
  const b = {
1945
3031
  key: null,
1946
3032
  children: [],
1947
3033
  last: null,
3034
+ rows: null,
3035
+ fn: hole.$fn,
1948
3036
  closed: false,
3037
+ scope: undefined,
3038
+ occ: null,
3039
+ next: null,
3040
+ up: engine.parent,
1949
3041
  sweep() {
1950
3042
  if (b.closed) return;
1951
3043
  const prevSweeping = engine.sweeping;
1952
3044
  engine.sweeping = true;
1953
- engine.gateHit = false;
1954
- const sweepOwnersBefore = stamp();
3045
+ engine.dry = b.last === null;
1955
3046
  let res;
1956
3047
  try {
1957
- res = owner ? runWithOwner(owner, () => resolveHoleValue(hole)) : resolveHoleValue(hole);
3048
+ res = rescope(b, hole, () => swept(owner, holeCtx, () => resolveHoleValue(hole)));
1958
3049
  } catch (err) {
1959
3050
  b.closed = true;
1960
3051
  sink.closeBinding(b.key);
1961
- sink.error(b.key, String(err && err.message || err));
3052
+ sink.error(b.key, wireErrorMessage(err, errorScope));
1962
3053
  return;
1963
3054
  } finally {
1964
3055
  engine.sweeping = prevSweeping;
3056
+ engine.dry = false;
1965
3057
  }
1966
- if (engine.gateHit || stamp() !== sweepOwnersBefore) {
3058
+ if (engine.sweptOwners && res.h.length) {
1967
3059
  b.closed = true;
1968
3060
  sink.closeBinding(b.key);
1969
3061
  return;
@@ -1971,29 +3063,38 @@ function createLiveHoles(sink, scoped) {
1971
3063
  if (res.h.length) return;
1972
3064
  const html = res.t[0];
1973
3065
  if (b.last === null || html === b.last) return;
3066
+ const ops = b.rows && res.rows && rowOps(b.rows, res.rows);
1974
3067
  b.last = html;
3068
+ if (ops && !ops.r.length && ops.n === b.rows.length) return;
3069
+ b.rows = res.rows;
1975
3070
  closeChildren(b);
1976
- sink.hole(b.key, html);
3071
+ settleOccurrences(b);
3072
+ sink.hole(b.key, html, ops && !html.includes("<!--slot:") ? ops : null);
1977
3073
  }
1978
3074
  };
1979
3075
  if (engine.parent) engine.parent.children.push(b);
1980
3076
  const prevParent = engine.parent;
3077
+ const prevScope = engine.scope;
3078
+ const prevVisit = engine.visit;
3079
+ const scope = b.scope = scopeFor(hole);
1981
3080
  engine.parent = b;
3081
+ engine.scope = scope;
3082
+ engine.visit = b;
1982
3083
  let value;
1983
3084
  let escalated = null;
1984
3085
  try {
1985
- value = hole();
3086
+ value = holeValue(hole);
1986
3087
  } catch (err) {
1987
3088
  const wrap = buildAsyncWrap(err, hole);
1988
3089
  if (!wrap) {
1989
- engine.parent = prevParent;
3090
+ leave(b, prevParent, prevScope, prevVisit);
1990
3091
  closeChildren(b);
1991
3092
  return "";
1992
3093
  }
1993
3094
  escalated = wrap;
1994
3095
  }
1995
3096
  if (!escalated && (typeof value === "function" && value.$lhSkip || value !== null && typeof value === "object" && value.$slot)) {
1996
- engine.parent = prevParent;
3097
+ leave(b, prevParent, prevScope, prevVisit);
1997
3098
  const r = {
1998
3099
  t: [""],
1999
3100
  h: [],
@@ -2008,6 +3109,7 @@ function createLiveHoles(sink, scoped) {
2008
3109
  return r.h.length ? r : r.t[0];
2009
3110
  }
2010
3111
  let res;
3112
+ let rows = null;
2011
3113
  if (escalated) {
2012
3114
  closeChildren(b);
2013
3115
  escalated.fn.$lhSuppress = true;
@@ -2024,23 +3126,25 @@ function createLiveHoles(sink, scoped) {
2024
3126
  p: []
2025
3127
  };
2026
3128
  try {
2027
- resolveSSRNode(value, res);
3129
+ rows = resolveValue(value, res);
2028
3130
  } catch (_) {
2029
- engine.parent = prevParent;
3131
+ leave(b, prevParent, prevScope, prevVisit);
2030
3132
  closeChildren(b);
2031
3133
  return "";
2032
3134
  }
2033
3135
  }
2034
- engine.parent = prevParent;
2035
- if (engine.recordStamp !== recordsBefore || stamp() !== ownersBefore) {
3136
+ leave(b, prevParent, prevScope, prevVisit);
3137
+ if (stamp() !== ownersBefore) {
2036
3138
  return res.h.length ? res : res.t[0];
2037
3139
  }
3140
+ if (!res.h.length && settled && settled()) return res.t[0];
2038
3141
  const id = nextId++;
2039
3142
  const key = b.key = "lh:" + id;
2040
3143
  const open = `<!--lh:${id}-->`;
2041
3144
  const close = `<!--lh:/${id}-->`;
2042
3145
  if (!res.h.length) {
2043
3146
  b.last = stripMarkers(res.t[0]);
3147
+ b.rows = rows;
2044
3148
  sink.openBinding(key, b);
2045
3149
  return open + res.t[0] + close;
2046
3150
  }
@@ -2058,10 +3162,11 @@ function createLiveHoles(sink, scoped) {
2058
3162
  return nextId++;
2059
3163
  },
2060
3164
  active() {
2061
- return !inScope || inScope();
3165
+ return (!inScope || inScope()) && !(settled && settled());
2062
3166
  },
2063
3167
  attr(cap) {
2064
3168
  const owner = getOwner();
3169
+ const holeCtx = sharedConfig.context;
2065
3170
  const b = {
2066
3171
  key: "lha:" + cap.id,
2067
3172
  children: [],
@@ -2070,9 +3175,10 @@ function createLiveHoles(sink, scoped) {
2070
3175
  sweep() {
2071
3176
  if (b.closed) return;
2072
3177
  const prevSweeping = engine.sweeping;
3178
+ const prevScope = engine.scope;
2073
3179
  engine.sweeping = true;
3180
+ engine.scope = null;
2074
3181
  engine.gateHit = false;
2075
- const sweepOwnersBefore = stamp();
2076
3182
  let html = "";
2077
3183
  try {
2078
3184
  let group = null;
@@ -2097,17 +3203,23 @@ function createLiveHoles(sink, scoped) {
2097
3203
  if (vt === "string" || vt === "number") html += v;
2098
3204
  }
2099
3205
  };
2100
- owner ? runWithOwner(owner, run) : run();
3206
+ swept(owner, holeCtx, run);
2101
3207
  } catch (err) {
2102
- if (ssrHandleError(err, true)) return;
3208
+ if (ssrHandleError(err, true)) {
3209
+ if (!engine.sweptOwners) return;
3210
+ b.closed = true;
3211
+ sink.closeBinding(b.key);
3212
+ return;
3213
+ }
2103
3214
  b.closed = true;
2104
3215
  sink.closeBinding(b.key);
2105
- sink.error("lha:" + cap.id, String(err && err.message || err));
3216
+ sink.error("lha:" + cap.id, wireErrorMessage(err, errorScope));
2106
3217
  return;
2107
3218
  } finally {
2108
3219
  engine.sweeping = prevSweeping;
3220
+ engine.scope = prevScope;
2109
3221
  }
2110
- if (engine.gateHit || stamp() !== sweepOwnersBefore) {
3222
+ if (engine.gateHit) {
2111
3223
  b.closed = true;
2112
3224
  sink.closeBinding(b.key);
2113
3225
  return;
@@ -2120,6 +3232,7 @@ function createLiveHoles(sink, scoped) {
2120
3232
  sink.attr(String(cap.id), html, removed);
2121
3233
  }
2122
3234
  };
3235
+ if (sink.attrBaseline) sink.attrBaseline(b.key, cap.base);
2123
3236
  sink.openBinding(b.key, b);
2124
3237
  }
2125
3238
  };
@@ -2132,6 +3245,71 @@ function attrNames(text) {
2132
3245
  while (m = re.exec(text)) names.push(m[1]);
2133
3246
  return names;
2134
3247
  }
3248
+ const ROW_HTML = Symbol.for("solid.rowHtml");
3249
+ const ROW_TOKEN = /<(\/?)([a-zA-Z][^\s/>]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|<!--([\s\S]*?)-->/g;
3250
+ const ROW_VOID = /^(?:area|base|br|col|embed|hr|img|input|link|meta|source|track|wbr)$/i;
3251
+ const ROW_FOREIGN = /^(?:svg|math)$/i;
3252
+ const ROW_RAW = /^(?:script|style|textarea|title|template)$/i;
3253
+ const ROW_KEY = /\s_key(?:="[^"]*")?(?![^\s/])/;
3254
+ const rowKey = attrs => (ROW_KEY.exec(attrs) || [""])[0];
3255
+ const ROW_ENTITY = /&(?:amp|lt|gt|quot|#39);/g;
3256
+ const ROW_ENTITIES = {
3257
+ "&amp;": "&",
3258
+ "&lt;": "<",
3259
+ "&gt;": ">",
3260
+ "&quot;": '"',
3261
+ "&#39;": "'"
3262
+ };
3263
+ function rowText(text) {
3264
+ if (!text.includes("&")) return text;
3265
+ if (text.replace(ROW_ENTITY, "").includes("&")) return null;
3266
+ return text.replace(ROW_ENTITY, e => ROW_ENTITIES[e]);
3267
+ }
3268
+ const ROW_HASH_SEED = 0x811c9dc5;
3269
+ function rowPatch(a, b) {
3270
+ const ra = new RegExp(ROW_TOKEN);
3271
+ const rb = new RegExp(ROW_TOKEN);
3272
+ const p = [];
3273
+ const stack = [[-1, 0, false]];
3274
+ let el = -1;
3275
+ let h = ROW_HASH_SEED;
3276
+ let ia = 0;
3277
+ let ib = 0;
3278
+ for (;;) {
3279
+ const ma = ra.exec(a);
3280
+ const mb = rb.exec(b);
3281
+ const ta = a.slice(ia, ma ? ma.index : a.length);
3282
+ const tb = b.slice(ib, mb ? mb.index : b.length);
3283
+ const top = stack[stack.length - 1];
3284
+ if (ta !== tb) {
3285
+ const text = rowText(tb);
3286
+ if (text === null) return null;
3287
+ p.push([top[0], top[1], text]);
3288
+ }
3289
+ if (!ma || !mb) return !ma && !mb ? {
3290
+ p,
3291
+ h: h >>> 0
3292
+ } : null;
3293
+ ia = ra.lastIndex;
3294
+ ib = rb.lastIndex;
3295
+ if (ma[4] !== undefined || mb[4] !== undefined) {
3296
+ if (ma[4] !== mb[4]) return null;
3297
+ top[1]++;
3298
+ } else if (ma[1] !== mb[1] || ma[2] !== mb[2]) return null;else if (ROW_RAW.test(ma[2])) return null;else if (ma[1]) {
3299
+ if (stack.length === 1) return null;
3300
+ stack.pop();
3301
+ } else {
3302
+ el++;
3303
+ top[1]++;
3304
+ const foreign = top[2] || ROW_FOREIGN.test(ma[2]);
3305
+ if (ma[3] !== mb[3]) {
3306
+ if (foreign || rowKey(ma[3]) !== rowKey(mb[3])) return null;
3307
+ p.push([el, mb[3].replace(/\/$/, "")]);
3308
+ }
3309
+ if (!ROW_VOID.test(ma[2]) && !ma[3].endsWith("/")) stack.push([el, 0, foreign]);
3310
+ }
3311
+ }
3312
+ }
2135
3313
  function ssr(t) {
2136
3314
  const len = arguments.length;
2137
3315
  if (len === 1) return {
@@ -2171,7 +3349,9 @@ function ssr(t) {
2171
3349
  cap = {
2172
3350
  id,
2173
3351
  parts: [prefix],
2174
- base: prefix
3352
+ base: prefix,
3353
+ at: lastOpen.seg,
3354
+ inject
2175
3355
  };
2176
3356
  return true;
2177
3357
  };
@@ -2220,7 +3400,10 @@ function ssr(t) {
2220
3400
  });
2221
3401
  }
2222
3402
  } else {
2223
- cap = null;
3403
+ if (cap) {
3404
+ result.t[cap.at] = result.t[cap.at].replace(cap.inject, "");
3405
+ cap = null;
3406
+ }
2224
3407
  result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
2225
3408
  result.p.push(lastGroupVal.p);
2226
3409
  result.t.push("");
@@ -2282,12 +3465,15 @@ function ssr(t) {
2282
3465
  f: hole
2283
3466
  });
2284
3467
  } else {
3468
+ result.t[cap.at] = result.t[cap.at].replace(cap.inject, "");
2285
3469
  cap = null;
2286
3470
  }
2287
3471
  }
2288
3472
  } else {
2289
3473
  const capturing = live && !hp.pos[i - 1] && captureStart();
3474
+ const scope = live && hp.pos[i - 1] && live.nest(hole);
2290
3475
  const r = tryResolveFunctionHole(hole);
3476
+ if (scope) live.scope = scope;
2291
3477
  if (typeof r === "string") {
2292
3478
  s += r;
2293
3479
  if (capturing) {
@@ -2297,7 +3483,10 @@ function ssr(t) {
2297
3483
  });
2298
3484
  }
2299
3485
  } else {
2300
- if (capturing) cap = null;
3486
+ if (capturing) {
3487
+ s = s.replace(cap.inject, "");
3488
+ cap = null;
3489
+ }
2301
3490
  result = {
2302
3491
  t: [s],
2303
3492
  h: [],
@@ -2358,16 +3547,17 @@ function ssr(t) {
2358
3547
  return result;
2359
3548
  }
2360
3549
  function ssrClassName(value) {
3550
+ if (typeof value === "number") return "" + value;
2361
3551
  if (!value) return "";
2362
3552
  if (typeof value === "string") return escape(value, true);
2363
3553
  value = classListToObject(value);
2364
3554
  let classKeys = Object.keys(value),
2365
3555
  result = "";
2366
3556
  for (let i = 0, len = classKeys.length; i < len; i++) {
2367
- const key = classKeys[i],
2368
- classValue = !!value[key];
3557
+ const key = classKeys[i];
3558
+ const classValue = value[key];
2369
3559
  if (!key || key === "undefined" || !classValue) continue;
2370
- i && (result += " ");
3560
+ result && (result += " ");
2371
3561
  result += escape(key, true);
2372
3562
  }
2373
3563
  return result;
@@ -2381,9 +3571,9 @@ function ssrStyle(value) {
2381
3571
  const s = escape(k[i], true);
2382
3572
  const v = value[k[i]];
2383
3573
  if (v != undefined) {
2384
- if (i) result += ";";
2385
3574
  const r = escape(v, true);
2386
3575
  if (r != undefined && r !== "undefined") {
3576
+ if (result) result += ";";
2387
3577
  result += `${s}:${r}`;
2388
3578
  }
2389
3579
  }
@@ -2393,76 +3583,185 @@ function ssrStyle(value) {
2393
3583
  function ssrStyleProperty(name, value) {
2394
3584
  return value != null ? name + value : "";
2395
3585
  }
2396
- function ssrElement(tag, props, children, needsId) {
3586
+ function ssrStyleProperties(...entries) {
3587
+ let result = "";
3588
+ for (let i = 0; i < entries.length; i += 2) {
3589
+ const entry = ssrStyleProperty(entries[i], entries[i + 1]);
3590
+ if (entry) result = result ? result + ";" + entry : entry;
3591
+ }
3592
+ return result;
3593
+ }
3594
+ function ssrElement(tag, props, children, needsId, skip, attrs) {
2397
3595
  const hk = needsId ? ssrHydrationKey() : "";
2398
- if (props == null) props = {};else if (typeof props === "function") props = props();
2399
- const skipChildren = VOID_ELEMENTS.test(tag);
2400
- const keys = Object.keys(props);
2401
- let result = `<${tag}${hk} `;
2402
- for (let i = 0; i < keys.length; i++) {
2403
- const prop = keys[i];
2404
- if (ChildProperties.has(prop)) {
2405
- if (children === undefined && !skipChildren) children = tag === "script" || tag === "style" || prop === "innerHTML" ? props[prop] : escape(props[prop]);
2406
- continue;
3596
+ if (typeof props === "function") props = props();
3597
+ let sources = null;
3598
+ let proxy = false;
3599
+ let viewKeys = null;
3600
+ let owners = null;
3601
+ const ctx = renderConfig.context;
3602
+ const link = tag === "a" && ctx !== undefined && ctx.linkClaim !== undefined ? {} : null;
3603
+ if (Array.isArray(props)) {
3604
+ let i = 0;
3605
+ for (; i < props.length; i++) {
3606
+ const s = props[i];
3607
+ if (s == null || typeof s === "function" || $PROXY in s) break;
2407
3608
  }
2408
- const value = props[prop];
2409
- if (prop === "style") {
2410
- result += `style="${ssrStyle(value)}"`;
2411
- } else if (prop === "class") {
2412
- result += `class="${ssrClassName(value)}"`;
2413
- } else if (value == undefined || prop === "ref" || prop.slice(0, 2) === "on" || prop.slice(0, 5) === "prop:") {
2414
- continue;
2415
- } else if (typeof value === "boolean") {
2416
- if (!value) continue;
2417
- result += escape(prop);
2418
- } else {
2419
- result += value === "" ? escape(prop) : `${escape(prop)}="${escape(value, true)}"`;
3609
+ if (i === props.length) sources = props;else {
3610
+ viewKeys = [];
3611
+ owners = [];
3612
+ collectSpreadSources(props, viewKeys, owners);
3613
+ }
3614
+ } else if (props == null) {
3615
+ props = {};
3616
+ } else if ($PROXY in props) {
3617
+ if (viewOf(props) !== undefined) {
3618
+ viewKeys = [];
3619
+ owners = [];
3620
+ sourceOwners(props, viewKeys, owners);
3621
+ } else proxy = true;
3622
+ }
3623
+ const info = tagInfo(tag);
3624
+ const skipChildren = info.isVoid;
3625
+ let result = info.open + hk;
3626
+ let childOwner = null;
3627
+ const last = sources === null ? 0 : sources.length - 1;
3628
+ let keysOf = null;
3629
+ if (sources !== null) {
3630
+ keysOf = new Array(last + 1);
3631
+ for (let s = 0; s <= last; s++) keysOf[s] = Object.keys(sources[s]);
3632
+ }
3633
+ for (let s = 0; s <= last; s++) {
3634
+ const keys = owners !== null ? viewKeys : keysOf !== null ? keysOf[s] : proxy ? Reflect.ownKeys(props) : Object.keys(props);
3635
+ if (sources !== null) props = sources[s];
3636
+ nextKey: for (let i = 0; i < keys.length; i++) {
3637
+ let prop = keys[i];
3638
+ if (typeof prop !== "string" || skip !== undefined && skip(prop)) continue;
3639
+ if (owners !== null) props = owners[i];
3640
+ for (let j = s + 1; j <= last; j++) {
3641
+ if (keysOf[j].includes(prop)) continue nextKey;
3642
+ }
3643
+ if (info.textarea && (prop === "value" || prop === "defaultValue")) {
3644
+ const value = props[prop];
3645
+ if (value !== null) children = escape(value);
3646
+ continue;
3647
+ }
3648
+ if (ChildProperties.has(prop)) {
3649
+ if (children === undefined && childOwner === null && !skipChildren) {
3650
+ if (prop === "children") childOwner = props;else children = info.raw || prop === "innerHTML" ? props[prop] : escape(props[prop]);
3651
+ }
3652
+ continue;
3653
+ }
3654
+ const key = prop;
3655
+ if (info.formAttributes !== undefined) {
3656
+ prop = spreadFormAttribute(prop, info, keys, keysOf, skip);
3657
+ if (prop === undefined) continue;
3658
+ }
3659
+ const value = props[key];
3660
+ if (value == undefined || prop.startsWith("prop:") || prop === "ref" || isEventName(prop)) continue;
3661
+ if (link !== null && LinkAttributes.has(prop)) link[prop] = value;
3662
+ if (prop === "style") {
3663
+ result += ` style="${ssrStyle(value)}"`;
3664
+ } else if (prop === "class") {
3665
+ result += ` class="${ssrClassName(value)}"`;
3666
+ } else if (typeof value === "boolean") {
3667
+ if (value && isAttrName(prop)) result += ` ${prop}`;
3668
+ } else if (isAttrName(prop)) {
3669
+ result += value === "" ? ` ${prop}` : ` ${prop}="${escape(value, true)}"`;
3670
+ }
2420
3671
  }
2421
- if (i !== keys.length - 1) result += " ";
2422
3672
  }
3673
+ if (attrs !== undefined) result += typeof attrs === "function" ? attrs() : attrs;
3674
+ if (link !== null && link.href !== undefined) result += ssrLinkClaim(link);
2423
3675
  if (skipChildren) return {
2424
- t: result + "/>"
3676
+ t: result + " />"
2425
3677
  };
3678
+ if (childOwner !== null) children = info.raw ? childOwner.children : escape(childOwner.children);
2426
3679
  if (typeof children === "function") children = children();
2427
- return ssr([result + ">", `</${tag}>`], resolveSSRNode(children, undefined, true));
3680
+ let thunk = null;
3681
+ if (typeof children === "function" && (ctx === undefined || !ctx.liveHoles)) {
3682
+ thunk = children;
3683
+ ssrTextTail = false;
3684
+ try {
3685
+ children = thunk();
3686
+ } catch (err) {
3687
+ const res = {
3688
+ t: [""],
3689
+ h: [],
3690
+ p: []
3691
+ };
3692
+ pushSSRAsyncHole(res, err, thunk);
3693
+ return ssr([result + ">", info.close], res);
3694
+ }
3695
+ }
3696
+ const ct = typeof children;
3697
+ if (ct === "string" || ct === "number") return {
3698
+ t: result + ">" + children + info.close
3699
+ };
3700
+ if (children == null || ct === "boolean") return {
3701
+ t: result + ">" + info.close
3702
+ };
3703
+ if (ct === "object" && !children.h && typeof children.t === "string") return {
3704
+ t: result + ">" + children.t + info.close
3705
+ };
3706
+ if (thunk === null) return ssr([result + ">", info.close], resolveSSRNode(children, undefined, true));
3707
+ const res = {
3708
+ t: [""],
3709
+ h: [],
3710
+ p: []
3711
+ };
3712
+ try {
3713
+ resolveSSRNode(children, res, false, true);
3714
+ } catch (err) {
3715
+ pushSSRAsyncHole(res, err, thunk);
3716
+ }
3717
+ return ssr([result + ">", info.close], res);
3718
+ }
3719
+ function collectSpreadSources(props, viewKeys, owners) {
3720
+ for (let i = 0; i < props.length; i++) {
3721
+ let s = props[i];
3722
+ if (typeof s === "function") s = s();
3723
+ if (s != null) sourceOwners(s, viewKeys, owners);
3724
+ }
3725
+ }
3726
+ function spreadFormAttribute(prop, info, keys, keysOf, skip) {
3727
+ const defaultProp = info.formDefaults[prop];
3728
+ if (defaultProp !== undefined && (skip === undefined || !skip(defaultProp))) {
3729
+ if (keysOf !== null) {
3730
+ for (let j = 0; j < keysOf.length; j++) {
3731
+ if (keysOf[j].includes(defaultProp)) return;
3732
+ }
3733
+ } else if (keys.includes(defaultProp)) return;
3734
+ }
3735
+ const attr = info.formAttributes[prop];
3736
+ if (attr !== undefined && skip !== undefined && skip(attr)) return;
3737
+ return attr === undefined ? prop : attr;
3738
+ }
3739
+ function ssrElementAttribute(key, value) {
3740
+ if (value == undefined) return "";
3741
+ if (key === "style" || key === "class") return ` ${key}="${key === "class" ? ssrClassName(value) : ssrStyle(value)}"`;
3742
+ if (typeof value === "boolean") return value ? ` ${key}` : "";
3743
+ return value === "" ? ` ${key}` : ` ${key}="${escape(value, true)}"`;
2428
3744
  }
2429
3745
  function ssrAttribute(key, value) {
2430
- return value == null || value === false ? "" : value === true ? ` ${key}` : ` ${key}="${value}"`;
3746
+ if (typeof value === "string") return ` ${key}="${value}"`;
3747
+ if (value == null || value === false) return "";
3748
+ if (typeof value === "object") return ` ${key}="${escape(String(value), true)}"`;
3749
+ if (typeof value === "function") return ` ${key}="${escape(String(value), true)}"`;
3750
+ return value === true ? ` ${key}` : ` ${key}="${value}"`;
2431
3751
  }
2432
3752
  function ssrHydrationKey() {
2433
3753
  const hk = getHydrationKey();
2434
3754
  return hk ? ` _hk=${hk}` : "";
2435
3755
  }
2436
- const CLAIM_PROP = /*#__PURE__*/Symbol.for("dom-expressions.claim-prop");
2437
- const CLAIMS_STREAM = 1;
2438
- const CLAIMS_DOCUMENT = 2;
2439
- const CLAIM_UNSAFE = /[^A-Za-z0-9_.!~*'()-]/g;
2440
- function encodeClaimKey(key) {
2441
- return String(key).replace(CLAIM_UNSAFE, c => encodeURIComponent(c));
2442
- }
2443
- function ssrClaim(map) {
2444
- const mode = sharedConfig.context && sharedConfig.context.claims;
2445
- if (!mode || mode === CLAIMS_DOCUMENT && !(typeof inServerComponentScope === "function" && inServerComponentScope())) {
2446
- return "";
2447
- }
2448
- let out = "";
2449
- for (const pos in map) {
2450
- const value = map[pos];
2451
- const list = Array.isArray(value) ? value : [value];
2452
- for (const fn of list) {
2453
- const prop = typeof fn === "function" && fn[CLAIM_PROP] || undefined;
2454
- if (prop === undefined) {
2455
- continue;
2456
- }
2457
- out += `${out ? "," : ""}${pos}=${encodeClaimKey(prop)}`;
2458
- }
2459
- }
2460
- return out ? ` _bnd="${out}"` : "";
3756
+ function ssrLinkClaim(attrs) {
3757
+ const ctx = renderConfig.context;
3758
+ if (ctx === undefined || ctx.linkClaim === undefined || attrs["aria-current"] != null) return "";
3759
+ return ctx.linkClaim(attrs);
2461
3760
  }
2462
3761
  function decodeSSREntities(s) {
2463
3762
  return s.indexOf("&") < 0 ? s : s.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&amp;/g, "&");
2464
3763
  }
2465
- const SELECT_VALUE_ATTR = /\svalue="([^"]*)"/;
3764
+ const SELECT_VALUE_ATTR = /\svalue(?:="([^"]*)")?(?=[\s>]|$)/;
2466
3765
  function tagEnd(html, i) {
2467
3766
  for (let j = i + 1; j < html.length; j++) {
2468
3767
  const c = html.charCodeAt(j);
@@ -2514,7 +3813,7 @@ function resolveSSRSelectValues(html) {
2514
3813
  cand = html.indexOf("<select", e0 + 1);
2515
3814
  continue;
2516
3815
  }
2517
- const bound = decodeSSREntities(m[1]);
3816
+ const bound = decodeSSREntities(m[1] ?? "");
2518
3817
  const sel = {
2519
3818
  values: /\smultiple(?=[\s>=])/.test(open) ? bound.split(",") : [bound],
2520
3819
  strip: cand + m.index,
@@ -2551,7 +3850,7 @@ function resolveSSRSelectValues(html) {
2551
3850
  const attrs = html.slice(i + 7, e);
2552
3851
  if (/\sselected(?=[\s=]|$)/.test(attrs)) sel.defaulted = true;else {
2553
3852
  const vm = SELECT_VALUE_ATTR.exec(attrs);
2554
- const value = vm ? decodeSSREntities(vm[1]) : decodeSSREntities(optionText(html, e + 1)).replace(/\s+/g, " ").trim();
3853
+ const value = vm ? decodeSSREntities(vm[1] ?? "") : decodeSSREntities(optionText(html, e + 1)).replace(/\s+/g, " ").trim();
2555
3854
  if (sel.values.includes(value)) sel.marks.push(e);
2556
3855
  }
2557
3856
  }
@@ -2570,10 +3869,13 @@ function escape(s, attr) {
2570
3869
  if (!attr && Array.isArray(s)) {
2571
3870
  const joined = tryJoinPlainSSRArray(s);
2572
3871
  if (joined !== undefined) return joined;
3872
+ const src = s;
2573
3873
  s = s.slice();
2574
3874
  for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
3875
+ if (src.$slot) s.$slot = true;
2575
3876
  return s;
2576
3877
  }
3878
+ if (!attr && t === "function") return escapeLate(s);
2577
3879
  if (attr) {
2578
3880
  if (s == null || t === "boolean" || t === "number") return s;
2579
3881
  return escape(String(s), attr);
@@ -2584,6 +3886,16 @@ function escape(s, attr) {
2584
3886
  if (i < 0) return s;
2585
3887
  return escapeSlow(s, attr, i);
2586
3888
  }
3889
+ function escapeLate(fn) {
3890
+ if (fn.$esc) return fn;
3891
+ const w = () => escape(fn());
3892
+ w.$esc = true;
3893
+ w.$fn = fn;
3894
+ if (fn.$lhSkip) w.$lhSkip = true;
3895
+ if (fn.$lhSuppress) w.$lhSuppress = true;
3896
+ if (fn.$lhBinding) w.$lhBinding = fn.$lhBinding;
3897
+ return w;
3898
+ }
2587
3899
  const ESCAPE_CONTENT = /[&<]/;
2588
3900
  const ESCAPE_ATTR = /[&"<]/;
2589
3901
  function escapeSlow(s, attr, start) {
@@ -2671,10 +3983,13 @@ function applyRef(r, element) {
2671
3983
  Array.isArray(r) ? r.flat(Infinity).forEach(f => f && f(element)) : r(element);
2672
3984
  }
2673
3985
  function generateHydrationScript({
2674
- eventNames = ["click", "input"],
3986
+ eventNames,
2675
3987
  nonce
2676
3988
  } = {}) {
2677
- return `<script${nonce ? ` nonce="${escape(String(nonce), true)}"` : ""}>window._$HY||(e=>{let t=e=>e&&e.hasAttribute&&(e.hasAttribute("_hk")?e:t(e.host&&e.host.nodeType?e.host:e.parentNode));["${eventNames.join('","')}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:{},fe(){}});</script><!--xs-->`;
3989
+ return hydrationBootstrap(eventNames, destinationNonce(nonce, "script"), false);
3990
+ }
3991
+ function hydrationBootstrap(eventNames = ["click", "input"], nonce, ledger) {
3992
+ return `<script${nonce ? ` nonce="${escape(String(nonce), true)}"` : ""}>window._$HY||(e=>{let t=e=>e&&e.hasAttribute&&(e.hasAttribute("_hk")?e:t(e.host&&e.host.nodeType?e.host:e.parentNode));["${eventNames.join('","')}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:new Proxy({},{set:(r,k,v)=>(v instanceof Promise&&v.catch(()=>{}),r[k]=v,!0)}),${ledger ? "s:{}," : ""}fe(){}});</script><!--xs-->`;
2678
3993
  }
2679
3994
  function queue(fn) {
2680
3995
  return Promise.resolve().then(fn);
@@ -2684,15 +3999,22 @@ function allSettled(promises) {
2684
3999
  let size = promises.size;
2685
4000
  return Promise.allSettled(promises).then(() => {
2686
4001
  if (promises.size !== size) return allSettled(promises);
2687
- return;
4002
+ return size;
2688
4003
  });
2689
4004
  }
2690
- function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, headTags, onHead) {
4005
+ function withShellEnd(html, context, renderId, nonce, noScripts) {
4006
+ if (noScripts || !context || !context.bootstrap) return html;
4007
+ const id = JSON.stringify(renderId).replace(/</g, "\\u003C");
4008
+ const marker = `<script${nonceAttr(nonce, "script")}>_$HY.s[${id}]=1,_$HY.sw&&_$HY.sw(${id})</script>`;
4009
+ const at = html.indexOf("</body>", html.length - 512);
4010
+ return at < 0 ? html + marker : html.slice(0, at) + marker + html.slice(at);
4011
+ }
4012
+ function assembleDocument(html, emittedAssets, preloadLinks, inlineStyles, scripts, nonce, headTags, onHead, lowModules) {
2691
4013
  const scriptTag = scripts ? `<script${nonceAttr(nonce, "script")}>${scripts}</script>` : "";
2692
4014
  const title = headTags ? headTags.title : null;
2693
4015
  let headTagsHtml = headTags ? headTags.html : "";
2694
4016
  const headPrelude = headTags ? headTags.prelude : "";
2695
- if (!onHead && title == null && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !(inlineStyles && inlineStyles.size)) {
4017
+ if (!onHead && title == null && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !preloadLinks && !(inlineStyles && inlineStyles.size)) {
2696
4018
  if (!scriptTag) return html;
2697
4019
  const xs = html.indexOf("<!--xs-->");
2698
4020
  return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
@@ -2711,7 +4033,7 @@ function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, hea
2711
4033
  if (title != null) {
2712
4034
  titleHtml = headTags.noScripts ? `<title data-dh="title">${escape(title)}</title>` : `<script${nonceAttr(nonce, "script")}>(function(x,t){(t=document.querySelector("title"))?(t.hasAttribute("data-dh")||t.setAttribute("data-dhf",t.textContent),t.textContent=x):(document.title=x,t=document.querySelector("title"));t&&t.setAttribute("data-dh","title")})(${JSON.stringify(title).replace(/</g, "\\u003C")})</script>`;
2713
4035
  }
2714
- onHead(headPrelude + headTagsHtml + titleHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce));
4036
+ onHead(headPrelude + headTagsHtml + titleHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce, lowModules));
2715
4037
  }
2716
4038
  if (!scriptTag) return html;
2717
4039
  const xs = html.indexOf("<!--xs-->");
@@ -2731,21 +4053,24 @@ function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, hea
2731
4053
  headTagsHtml = `<title data-dh="title">${winner}</title>` + headTagsHtml;
2732
4054
  }
2733
4055
  }
2734
- const head = headTagsHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce);
4056
+ const head = headTagsHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce, lowModules);
2735
4057
  if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
2736
4058
  const xsIdx = html.indexOf("<!--xs-->");
2737
4059
  if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
2738
4060
  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);
2739
4061
  }
2740
- function renderHeadAssets(emittedAssets, inlineStyles, nonce) {
4062
+ function renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce, lowModules) {
2741
4063
  let head = "";
2742
4064
  const styleAttr = nonceAttr(nonce, "style");
2743
4065
  const scriptAttr = nonceAttr(nonce, "script");
2744
4066
  if (emittedAssets && emittedAssets.size) {
2745
4067
  for (const url of emittedAssets) {
2746
- head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}"${styleAttr}>` : `<link rel="modulepreload" href="${url}"${scriptAttr}>`;
4068
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}"${styleAttr}>` : modulePreloadLink(url, scriptAttr, lowModules);
2747
4069
  }
2748
4070
  }
4071
+ if (preloadLinks) {
4072
+ for (const entry of preloadLinks) head += `<link${entry.attrHtml}>`;
4073
+ }
2749
4074
  if (inlineStyles && inlineStyles.size) {
2750
4075
  for (const entry of inlineStyles.values()) {
2751
4076
  if (entry.emitted) continue;
@@ -2840,26 +4165,30 @@ function classListToObject(classList) {
2840
4165
  function flattenClassList(list, result) {
2841
4166
  for (let i = 0, len = list.length; i < len; i++) {
2842
4167
  const item = list[i];
2843
- if (Array.isArray(item)) flattenClassList(item, result);else if (typeof item === "object" && item != null) Object.assign(result, item);else if (item || item === 0) result[item] = true;
4168
+ if (Array.isArray(item)) flattenClassList(item, result);else if (typeof item === "object" && item != null) Object.assign(result, item);
4169
+ else if (typeof item !== "boolean" && (item || item === 0)) result[item] = true;
2844
4170
  }
2845
4171
  }
2846
- function tryResolveString(node) {
4172
+ let ssrTextTail = false;
4173
+ function tryResolveString(node, nested) {
4174
+ if (!nested) ssrTextTail = false;
2847
4175
  const t = typeof node;
2848
- if (t === "string") return node;
2849
- if (t === "number") return "" + node;
4176
+ if (t === "string" || t === "number") {
4177
+ const s = ssrTextTail ? "<!--!$-->" + node : "" + node;
4178
+ ssrTextTail = true;
4179
+ return s;
4180
+ }
2850
4181
  if (node == null || t === "boolean") return "";
2851
4182
  if (t === "object") {
2852
4183
  if (Array.isArray(node)) {
2853
4184
  const joined = tryJoinPlainSSRArray(node);
2854
- if (joined !== undefined) return joined;
4185
+ if (joined !== undefined) {
4186
+ ssrTextTail = false;
4187
+ return joined;
4188
+ }
2855
4189
  let s = "";
2856
- let prevNonObj = false;
2857
4190
  for (let i = 0, len = node.length; i < len; i++) {
2858
- const item = node[i];
2859
- const itemNonObj = item !== null && typeof item !== "object";
2860
- if (prevNonObj && itemNonObj) s += "<!--!$-->";
2861
- prevNonObj = itemNonObj;
2862
- const r = tryResolveString(item);
4191
+ const r = tryResolveString(node[i], true);
2863
4192
  if (typeof r !== "string") return {
2864
4193
  bail: node
2865
4194
  };
@@ -2873,6 +4202,7 @@ function tryResolveString(node) {
2873
4202
  if (node.t === undefined) {
2874
4203
  return "";
2875
4204
  }
4205
+ ssrTextTail = false;
2876
4206
  return Array.isArray(node.t) ? node.t[0] : node.t;
2877
4207
  }
2878
4208
  if (t === "function") {
@@ -2880,9 +4210,11 @@ function tryResolveString(node) {
2880
4210
  try {
2881
4211
  v = node();
2882
4212
  } catch (err) {
2883
- return buildAsyncWrap(err, node) || "";
4213
+ const wrap = buildAsyncWrap(err, node);
4214
+ if (wrap) ssrTextTail = true;
4215
+ return wrap || "";
2884
4216
  }
2885
- return tryResolveString(v);
4217
+ return tryResolveString(v, true);
2886
4218
  }
2887
4219
  return "";
2888
4220
  }
@@ -2890,21 +4222,19 @@ function resolveSSRNode(node, result = {
2890
4222
  t: [""],
2891
4223
  h: [],
2892
4224
  p: []
2893
- }, top) {
4225
+ }, top, nested) {
4226
+ if (!nested) ssrTextTail = false;
2894
4227
  const t = typeof node;
2895
4228
  if (t === "string" || t === "number") {
2896
- result.t[result.t.length - 1] += node;
4229
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + node : node;
4230
+ ssrTextTail = true;
2897
4231
  } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
2898
4232
  const slotLive = node.$slot && sharedConfig.context && sharedConfig.context.liveHoles;
2899
4233
  if (slotLive) slotLive.suppressed++;
2900
4234
  try {
2901
- let prevNonObj = false;
2902
4235
  for (let i = 0, len = node.length; i < len; i++) {
2903
- const item = node[i];
2904
- const itemNonObj = item !== null && typeof item !== "object";
2905
- if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
2906
- prevNonObj = itemNonObj;
2907
- resolveSSRNode(item, result);
4236
+ if (top) ssrTextTail = false;
4237
+ resolveSSRNode(node[i], result, false, true);
2908
4238
  }
2909
4239
  } finally {
2910
4240
  if (slotLive) slotLive.suppressed--;
@@ -2917,37 +4247,174 @@ function resolveSSRNode(node, result = {
2917
4247
  result.h.push(...node.h);
2918
4248
  result.p.push(...node.p);
2919
4249
  }
4250
+ ssrTextTail = false;
2920
4251
  } else if (node.t !== undefined) {
2921
4252
  result.t[result.t.length - 1] += node.t;
4253
+ ssrTextTail = false;
2922
4254
  } else ;
2923
4255
  } else if (t === "function") {
2924
4256
  const live = sharedConfig.context && sharedConfig.context.liveHoles;
2925
4257
  let liveNode = null;
2926
4258
  if (live && (liveNode = live.content(node)) !== null) {
2927
- if (typeof liveNode === "string") result.t[result.t.length - 1] += liveNode;else resolveSSRNode(liveNode, result);
4259
+ if (typeof liveNode === "string") {
4260
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + liveNode : liveNode;
4261
+ ssrTextTail = true;
4262
+ } else resolveSSRNode(liveNode, result, false, true);
2928
4263
  } else {
4264
+ const scope = live && live.nest(node);
2929
4265
  try {
2930
- resolveSSRNode(node(), result);
4266
+ resolveSSRNode(node(), result, false, true);
2931
4267
  } catch (err) {
2932
- const wrap = buildAsyncWrap(err, node);
2933
- if (wrap) {
2934
- result.h.push(wrap.fn);
2935
- result.p.push(wrap.p);
2936
- result.t.push("");
2937
- }
4268
+ pushSSRAsyncHole(result, err, node);
4269
+ } finally {
4270
+ if (scope) live.scope = scope;
2938
4271
  }
2939
4272
  }
2940
4273
  }
2941
4274
  return result;
2942
4275
  }
4276
+ function pushSSRAsyncHole(result, err, node) {
4277
+ const wrap = buildAsyncWrap(err, node);
4278
+ if (wrap) {
4279
+ if (ssrTextTail) result.t[result.t.length - 1] += "<!--!$-->";
4280
+ result.h.push(wrap.fn);
4281
+ result.p.push(wrap.p);
4282
+ result.t.push("");
4283
+ ssrTextTail = true;
4284
+ }
4285
+ }
2943
4286
  function resolveSSRSync(node) {
2944
4287
  const res = resolveSSRNode(node);
2945
4288
  if (!res.h.length) return res.t[0];
2946
4289
  throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
2947
4290
  }
2948
4291
  const RequestContext = Symbol.for("solid.RequestContext");
4292
+ const ServerErrors = Symbol.for("solid-js/server/errors");
4293
+ function serializerErrorHook(hook) {
4294
+ return hook === undefined ? undefined : err => {
4295
+ reportServerError(err, {
4296
+ kind: "render",
4297
+ handling: "serialize"
4298
+ }, null, hook);
4299
+ };
4300
+ }
4301
+ function ambientServerErrorHook() {
4302
+ const slot = globalThis[ServerErrors];
4303
+ return slot === undefined ? undefined : slot.hook;
4304
+ }
4305
+ function configureServerErrors(config) {
4306
+ const g = globalThis;
4307
+ if (config && config.onError !== undefined && typeof config.onError !== "function") {
4308
+ throw new TypeError(`Invalid onError: expected a function, received ${typeof config.onError}.`);
4309
+ }
4310
+ (g[ServerErrors] ||= {}).hook = config ? config.onError : undefined;
4311
+ }
4312
+ function reportRequestFailure(error, event) {
4313
+ reportServerError(error, {
4314
+ kind: "request",
4315
+ handling: "failed",
4316
+ event
4317
+ }, null);
4318
+ if (ambientServerErrorHook() === undefined) console.error(error);
4319
+ }
2949
4320
  function getRequestEvent() {
2950
- return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
4321
+ const store = globalThis[RequestContext];
4322
+ if (!store) return undefined;
4323
+ const event = store.getStore();
4324
+ if (event) return event;
4325
+ const ctx = renderContextOf(getOwner());
4326
+ return ctx && ctx.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.");
4327
+ }
4328
+ const RENDER_ROOTS = Symbol.for("@solidjs/web/render-roots");
4329
+ function renderRoots() {
4330
+ const g = globalThis;
4331
+ return g[RENDER_ROOTS] || (g[RENDER_ROOTS] = new WeakMap());
4332
+ }
4333
+ function claimRenderRoot(context) {
4334
+ const owner = getOwner();
4335
+ const roots = renderRoots();
4336
+ roots.set(owner, context);
4337
+ onCleanup(() => roots.delete(owner));
4338
+ return owner;
4339
+ }
4340
+ function settleRender(render, root, outcome) {
4341
+ runWithOwner(root || null, () => render.settle(outcome));
4342
+ }
4343
+ const eventRenders = new WeakMap();
4344
+ function claimEventRender(event, context) {
4345
+ let renders = eventRenders.get(event);
4346
+ if (!renders) eventRenders.set(event, renders = new Set());
4347
+ renders.add(context);
4348
+ onCleanup(() => renders.delete(context));
4349
+ }
4350
+ function createHydrationWriter(context, isOpen) {
4351
+ const keys = new Set();
4352
+ return {
4353
+ async: !!context.async,
4354
+ write(key, value, options) {
4355
+ if (!isOpen() || keys.has(key)) return false;
4356
+ context.serialize(key, value, options && options.deferStream);
4357
+ keys.add(key);
4358
+ return true;
4359
+ }
4360
+ };
4361
+ }
4362
+ function getHydrationWriter() {
4363
+ const ctx = currentRenderContext();
4364
+ return ctx && ctx.writer;
4365
+ }
4366
+ function currentRenderContext() {
4367
+ let ctx = renderContextOf(getOwner());
4368
+ if (!ctx) {
4369
+ const event = peekRequestEvent();
4370
+ const renders = event && eventRenders.get(event);
4371
+ if (renders && renders.size === 1) for (const c of renders) ctx = c;
4372
+ }
4373
+ return ctx;
4374
+ }
4375
+ const LINK_STATE_RECORD = "links";
4376
+ function setLinkClaim(handler) {
4377
+ const ctx = currentRenderContext();
4378
+ if (!ctx) {
4379
+ return false;
4380
+ }
4381
+ ctx.linkClaim = handler;
4382
+ if (handler !== undefined) ctx.writer.write(LINK_STATE_RECORD, 1);
4383
+ return true;
4384
+ }
4385
+ function hasServerLinkState() {
4386
+ return false;
4387
+ }
4388
+ function takeHydrationValue(_key) {
4389
+ return undefined;
4390
+ }
4391
+ function renderContextOf(owner) {
4392
+ const roots = globalThis[RENDER_ROOTS];
4393
+ if (!roots) return undefined;
4394
+ for (; owner; owner = owner._parent) {
4395
+ const context = roots.get(owner);
4396
+ if (context) return context;
4397
+ }
4398
+ }
4399
+ function peekRequestEvent() {
4400
+ const store = globalThis[RequestContext];
4401
+ return store ? store.getStore() : undefined;
4402
+ }
4403
+ function timeDocument(context, trace, mode, requestEvent) {
4404
+ return undefined;
4405
+ }
4406
+ function getTraceContext() {
4407
+ const event = peekRequestEvent();
4408
+ if (event) return traceForEvent(event).context;
4409
+ const ctx = renderContextOf(getOwner());
4410
+ return ctx && ctx.trace ? ctx.trace.context : undefined;
4411
+ }
4412
+ function traceForStub(stub, event) {
4413
+ if (!event) {
4414
+ event = peekRequestEvent();
4415
+ if (!event || event.response !== stub) return undefined;
4416
+ }
4417
+ return traceForEvent(event);
2951
4418
  }
2952
4419
  function createResponseStub() {
2953
4420
  return {
@@ -2966,15 +4433,20 @@ function createRequestEvent(request, init) {
2966
4433
  };
2967
4434
  }
2968
4435
  function reportLostHeaderWrite(method, name) {
2969
- const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
4436
+ const message = `[LATE_HEADER_WRITE] Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
2970
4437
  console.error(message);
2971
4438
  }
2972
4439
  function commitResponseStub(stub, {
2973
- allowLateLocation = false
4440
+ allowLateLocation = false,
4441
+ event
2974
4442
  } = {}) {
2975
4443
  if (!stub || stub.committed) return stub;
2976
- stub.committed = true;
2977
4444
  const headers = stub.headers;
4445
+ if (headers && typeof headers.append === "function") {
4446
+ const trace = traceForStub(stub, event);
4447
+ if (trace) appendTraceServerTiming(headers, trace);
4448
+ }
4449
+ stub.committed = true;
2978
4450
  if (!headers || typeof headers.set !== "function") return stub;
2979
4451
  for (const method of ["set", "append", "delete"]) {
2980
4452
  const original = headers[method].bind(headers);
@@ -2995,7 +4467,7 @@ function getExpectedRedirectStatus(response) {
2995
4467
  function mergeStubHeaders(target, stub) {
2996
4468
  if (!stub) return target;
2997
4469
  stub.headers.forEach((value, key) => {
2998
- if (key !== "set-cookie") target.set(key, value);
4470
+ if (key === "server-timing") mergeServerTiming(target, value);else if (key !== "set-cookie") target.set(key, value);
2999
4471
  });
3000
4472
  const setCookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
3001
4473
  for (const cookie of setCookies) target.append("set-cookie", cookie);
@@ -3010,43 +4482,56 @@ function copyInitHeaders(init) {
3010
4482
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
3011
4483
  return headers;
3012
4484
  }
3013
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
4485
+ let stubGapFillExcluded;
4486
+ function isStubGapFillExcluded(key) {
4487
+ return (stubGapFillExcluded ||= new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
4488
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()))).has(key);
4489
+ }
3014
4490
  function fillsStubGap(key, headers, response) {
3015
- if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
4491
+ if (key === "set-cookie" || isStubGapFillExcluded(key)) return false;
3016
4492
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
3017
4493
  return !headers.has(key);
3018
4494
  }
3019
4495
  function commitEventResponse(response, event = getRequestEvent()) {
3020
4496
  const stub = event && event.response;
3021
- if (!stub || !stub.headers || stub.committed) return response;
3022
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
3023
- commitResponseStub(stub);
3024
- let hasGaps = false;
3025
- stub.headers.forEach((value, key) => {
3026
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
3027
- });
3028
- if (!cookies.length && !hasGaps) return response;
3029
- try {
3030
- for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
3031
- stub.headers.forEach((value, key) => {
3032
- if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
3033
- });
3034
- return response;
3035
- } catch {
4497
+ if (!stub || !stub.headers || stub.committed) {
4498
+ if (!event || stub) return response;
4499
+ const trace = traceForEvent(event);
4500
+ if (!hasServerTiming(trace)) return response;
3036
4501
  const headers = copyInitHeaders(response.headers);
3037
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
3038
- stub.headers.forEach((value, key) => {
3039
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
3040
- });
4502
+ appendTraceServerTiming(headers, trace);
3041
4503
  return new Response(response.body, {
3042
4504
  status: response.status,
3043
4505
  statusText: response.statusText,
3044
4506
  headers
3045
4507
  });
3046
4508
  }
4509
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
4510
+ commitResponseStub(stub, {
4511
+ event
4512
+ });
4513
+ let hasGaps = false;
4514
+ stub.headers.forEach((value, key) => {
4515
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
4516
+ });
4517
+ const timing = stub.headers.get("server-timing");
4518
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
4519
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
4520
+ const headers = copyInitHeaders(response.headers);
4521
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
4522
+ stub.headers.forEach((value, key) => {
4523
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
4524
+ });
4525
+ if (mergesTiming) mergeServerTiming(headers, timing);
4526
+ return new Response(response.body, {
4527
+ status: response.status,
4528
+ statusText: response.statusText,
4529
+ headers
4530
+ });
3047
4531
  }
3048
4532
  function deriveHead(stub, responseInit = {}) {
3049
4533
  const headers = mergeStubHeaders(copyInitHeaders(responseInit.headers), stub);
4534
+ for (const header of COMPOSED_BODY_FRAMING) headers.delete(header);
3050
4535
  const status = stub && stub.status || responseInit.status || 200;
3051
4536
  const statusText = stub && stub.statusText || responseInit.statusText || undefined;
3052
4537
  return {
@@ -3063,7 +4548,9 @@ function createSSRResponse(result, event, options = {}) {
3063
4548
  } = options;
3064
4549
  const nonce = normalizeNonce(options.nonce);
3065
4550
  if (typeof result === "string") {
3066
- if (stub) commitResponseStub(stub);
4551
+ if (stub) commitResponseStub(stub, {
4552
+ event
4553
+ });
3067
4554
  const head = deriveHead(stub, responseInit);
3068
4555
  if (stub && stub.headers.get("Location")) {
3069
4556
  return new Response(null, {
@@ -3093,12 +4580,13 @@ function createSSRResponse(result, event, options = {}) {
3093
4580
  closed = true;
3094
4581
  }
3095
4582
  };
3096
- result.pipe({
4583
+ const sink = {
3097
4584
  write(chunk) {
3098
4585
  if (!flushed) {
3099
4586
  flushed = true;
3100
4587
  if (stub) commitResponseStub(stub, {
3101
- allowLateLocation: true
4588
+ allowLateLocation: true,
4589
+ event
3102
4590
  });
3103
4591
  const head = deriveHead(stub, responseInit);
3104
4592
  if (stub && stub.headers.get("Location")) {
@@ -3107,6 +4595,7 @@ function createSSRResponse(result, event, options = {}) {
3107
4595
  status: getExpectedRedirectStatus(stub),
3108
4596
  headers: head.headers
3109
4597
  }));
4598
+ sink[ABANDON_RENDER]("redirect", true);
3110
4599
  return;
3111
4600
  }
3112
4601
  if (!head.headers.has("content-type")) {
@@ -3117,7 +4606,9 @@ function createSSRResponse(result, event, options = {}) {
3117
4606
  controller = c;
3118
4607
  },
3119
4608
  cancel() {
4609
+ if (closed) return;
3120
4610
  closed = true;
4611
+ sink[ABANDON_RENDER]("consumer");
3121
4612
  }
3122
4613
  }), {
3123
4614
  status: head.status,
@@ -3128,9 +4619,10 @@ function createSSRResponse(result, event, options = {}) {
3128
4619
  enqueue(transformChunk ? transformChunk(chunk) : chunk);
3129
4620
  },
3130
4621
  end() {
4622
+ if (!flushed) sink.write("");
3131
4623
  if (closed || !controller) return;
3132
4624
  const location = stub && stub.headers.get("Location");
3133
- if (location) {
4625
+ if (location && isHttpNavigationTarget(location)) {
3134
4626
  const attr = nonceAttr(nonce, "script");
3135
4627
  enqueue(`<script${attr}>window.location=${JSON.stringify(location).replace(/</g, "\\u003c")}</script>`);
3136
4628
  }
@@ -3138,8 +4630,23 @@ function createSSRResponse(result, event, options = {}) {
3138
4630
  try {
3139
4631
  controller.close();
3140
4632
  } catch {}
3141
- }
3142
- });
4633
+ },
4634
+ [SHELL_ABANDONED]() {
4635
+ if (flushed) return;
4636
+ flushed = closed = true;
4637
+ if (stub) commitResponseStub(stub, {
4638
+ event
4639
+ });
4640
+ const head = deriveHead(stub, responseInit);
4641
+ const status = stub && stub.headers.get("Location") ? getExpectedRedirectStatus(stub) : 500;
4642
+ resolve(new Response(null, {
4643
+ status,
4644
+ headers: head.headers
4645
+ }));
4646
+ },
4647
+ [ABANDON_RENDER]() {}
4648
+ };
4649
+ result.pipe(sink);
3143
4650
  });
3144
4651
  }
3145
4652
  function composeMiddleware(middlewares) {
@@ -3164,30 +4671,20 @@ function claimElement(node) {
3164
4671
  function claimElementTree(root) {
3165
4672
  return root;
3166
4673
  }
4674
+ function dispatchAsInteraction(_e, fn) {
4675
+ return fn();
4676
+ }
3167
4677
  function notSup() {
3168
- throw new Error("Client-only API called on the server side. Run client-only code in onMount, or conditionally run client-only component with <Show>.");
4678
+ throw new Error("Client-only API called on the server side. Run client-only code in onSettled, or conditionally run client-only component with <Show>.");
3169
4679
  }
3170
4680
 
3171
4681
  setContainerTraceResolver(getProjectionTrace);
4682
+ setAsyncIterableSharer(shareAsyncIterable);
3172
4683
  const isServer = true;
3173
4684
  const isDev = false;
3174
- function dynamic(source) {
3175
- const cached = createMemo(source, {
3176
- serialize: false
3177
- });
3178
- return props => {
3179
- return createMemo(() => {
3180
- const c = cached();
3181
- if (c) {
3182
- if (typeof c === "function") return c(props);
3183
- if (typeof c === "string") {
3184
- return ssrElement(c, props, undefined, true);
3185
- }
3186
- }
3187
- }, {
3188
- sync: true
3189
- });
3190
- };
4685
+ const ssrTag = (tag, props) => ssrElement(tag, props, undefined, true);
4686
+ function dynamic(source, options) {
4687
+ return dynamicCore(source, options, ssrTag);
3191
4688
  }
3192
4689
  function Dynamic(props) {
3193
4690
  const Comp = dynamic(() => props.component);
@@ -3209,6 +4706,11 @@ function registerClientOnlyPreload(moduleUrl) {
3209
4706
  const css = assets.css[i];
3210
4707
  if (typeof css === "string") registerAsset("style", css);else registerAsset("inline-style", css);
3211
4708
  }
4709
+ if (assets.preloads) {
4710
+ for (let i = 0; i < assets.preloads.length; i++) {
4711
+ registerAsset("preload", assets.preloads[i]);
4712
+ }
4713
+ }
3212
4714
  for (let i = 0; i < assets.js.length; i++) registerAsset("module", assets.js[i]);
3213
4715
  };
3214
4716
  const assets = resolve(moduleUrl);
@@ -3312,4 +4814,4 @@ function httpHeader(name, value, options) {
3312
4814
  }
3313
4815
  }
3314
4816
 
3315
- export { CLAIMS_DOCUMENT, CLAIMS_STREAM, CLAIM_PROP, ChildProperties, DOMElements, DOMWithState, DelegatedEvents, Dynamic, HREF, HydrationScript, MathMLElements, Namespaces, Portal, REVALIDATE_HEADER, RawTextElements, RequestContext, ResponseEnvelope, SAFE_ERROR, SVGElements, VoidElements, notSup as acquireAsset, notSup as addEvent, applyRef, notSup as assign, claimElement, claimElementTree, notSup as className, clearFlashCookie, clientOnly, commitEventResponse, commitResponseStub, composeMiddleware, createLiveHoles, createRequestEvent, createResponseStub, createSSRResponse, notSup as delegateEvents, dynamic, notSup as dynamicProperty, effect, escape, generateHydrationScript, notSup as getDelegatedRoot, getExpectedRedirectStatus, getHydrationKey, notSup as getNextElement, notSup as getNextMarker, notSup as getNextMatch, getRequestEvent, getServerFunctionMetadata, getServerFunctionRPC, hasFlashCookie, httpHeader, httpStatus, notSup as hydrate, notSup as insert, isDev, isHref, isResponseEnvelope, isSafeError, isServer, isServerFunction, markSafeError, memo, parseCookieHeader, redirect, notSup as ref, notSup as registerDelegatedContainer, notSup as registerDelegatedRoot, registerElementClaim, reload, notSup as render, renderToStream, renderToString, resolveSSRSelectValues, respond, notSup as runHydrationEvents, scriptNonce, serializeCookie, notSup as setAttribute, notSup as setAttributeNS, notSup as setProperty, notSup as setStyleProperty, notSup as spread, ssr, ssrAttribute, ssrClaim, ssrClassName, ssrElement, ssrGroup, ssrHydrationKey, ssrSelectValues, ssrStyle, ssrStyleProperty, notSup as style, styleNonce, notSup as template, notSup as unregisterDelegatedContainer, notSup as unregisterDelegatedRoot, useHead };
4817
+ export { ChildProperties, DOMElements, DOMWithState, DelegatedEvents, Dynamic, HREF, HydrationScript, MathMLElements, NULL_BODY_STATUSES, Namespaces, Portal, RESPONSE_HEADER_VALUE_LIMIT, REVALIDATE_ALL, REVALIDATE_HEADER, RawTextElements, RequestContext, ResponseEnvelope, SAFE_ERROR, SVGElements, VoidElements, notSup as acquireAsset, notSup as addEvent, applyRef, notSup as assign, claimElement, claimElementTree, notSup as className, clearFlashCookie, clientOnly, commitEventResponse, commitResponseStub, composeMiddleware, configureServerErrors, createLiveHoles, createRequestEvent, createResponseStub, createSSRResponse, notSup as delegateEvents, dispatchAsInteraction, dynamic, notSup as dynamicProperty, effect, escape, generateHydrationScript, notSup as getDelegatedRoot, getExpectedRedirectStatus, getHydrationKey, getHydrationWriter, notSup as getNextElement, notSup as getNextMarker, notSup as getNextMatch, getRequestEvent, getServerFunctionMetadata, getServerFunctionRPC, getTraceContext, hasFlashCookie, hasServerLinkState, httpHeader, httpStatus, notSup as hydrate, notSup as insert, isDev, isHref, isResponseEnvelope, isSafeError, isServer, isServerFunction, markSafeError, memo, parseCookieHeader, notSup as readShallow, redirect, notSup as ref, notSup as registerDelegatedContainer, notSup as registerDelegatedRoot, registerElementClaim, reload, notSup as render, renderToStream, renderToString, reportRequestFailure, resolveSSRNode, resolveSSRSelectValues, respond, notSup as runHydrationEvents, serializeCookie, notSup as setAttribute, notSup as setAttributeNS, setLinkClaim, notSup as setProperty, notSup as setStatefulProperty, notSup as setStyleProperty, notSup as spread, ssr, ssrAttribute, ssrClassName, ssrElement, ssrElementAttribute, ssrGroup, ssrHydrationKey, ssrLinkClaim, ssrSelectValues, ssrStyle, ssrStyleProperties, ssrStyleProperty, notSup as style, takeHydrationValue, notSup as template, notSup as unregisterDelegatedContainer, notSup as unregisterDelegatedRoot, useHead };