@solidjs/web 2.0.0-rc.1 → 2.0.0-rc.11

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 (107) hide show
  1. package/dist/server.dev.js +4472 -0
  2. package/dist/server.js +1301 -251
  3. package/dist/{server.cjs → server.observe.js} +1501 -452
  4. package/dist/{dev.cjs → web.dev.js} +699 -360
  5. package/dist/web.js +454 -139
  6. package/dist/{dev.js → web.observe.js} +505 -211
  7. package/frames/dist/client.dev.js +463 -71
  8. package/frames/dist/client.js +363 -70
  9. package/frames/dist/{client.dev.cjs → client.observe.js} +486 -133
  10. package/frames/dist/server.dev.js +1713 -0
  11. package/frames/dist/server.js +552 -2583
  12. package/frames/dist/server.observe.js +1713 -0
  13. package/frames/package.json +2 -25
  14. package/package.json +214 -255
  15. package/performance-tracks/dist/performance-tracks.dev.js +678 -0
  16. package/performance-tracks/dist/performance-tracks.js +6 -0
  17. package/performance-tracks/dist/performance-tracks.observe.js +666 -0
  18. package/performance-tracks/package.json +7 -0
  19. package/performance-tracks/types/index.d.ts +67 -0
  20. package/serialization/decode/package.json +2 -15
  21. package/serialization/dist/decode.js +92 -15
  22. package/serialization/dist/serialization.js +103 -23
  23. package/serialization/package.json +2 -15
  24. package/serialization/types/index.d.ts +76 -157
  25. package/serialization/types/serializer-decode.d.ts +149 -112
  26. package/serialization/types/serializer.d.ts +101 -0
  27. package/server-functions/dist/client.dev.js +1364 -0
  28. package/server-functions/dist/client.js +611 -97
  29. package/server-functions/dist/client.observe.js +1343 -0
  30. package/server-functions/dist/server.dev.js +2138 -202
  31. package/server-functions/dist/server.js +2042 -199
  32. package/server-functions/dist/server.observe.js +3043 -0
  33. package/server-functions/package.json +2 -35
  34. package/server-functions/rich-args/package.json +2 -15
  35. package/storage/package.json +2 -15
  36. package/types/client.d.ts +193 -288
  37. package/types/constants.d.ts +20 -0
  38. package/types/cookies.d.ts +32 -84
  39. package/types/diagnostics.d.ts +56 -0
  40. package/types/frames/client.d.ts +1 -1
  41. package/types/frames/frame-client.d.ts +323 -259
  42. package/types/frames/frame-container-plugin.d.ts +72 -0
  43. package/types/frames/frame-sink.d.ts +101 -158
  44. package/types/frames/frame-transport.d.ts +192 -190
  45. package/types/frames/serializer-decode.d.ts +219 -0
  46. package/types/frames/serializer.d.ts +76 -157
  47. package/types/frames/server.d.ts +1 -1
  48. package/types/head.d.ts +19 -0
  49. package/types/index.d.ts +52 -80
  50. package/types/index.server.d.ts +174 -0
  51. package/types/jsx.d.ts +33 -35
  52. package/types/observe.d.ts +358 -0
  53. package/types/reconcile.d.ts +1 -0
  54. package/types/render.d.ts +9 -0
  55. package/types/response.d.ts +75 -150
  56. package/types/serializer-decode.d.ts +149 -112
  57. package/types/serializer.d.ts +76 -157
  58. package/types/server-functions/client.d.ts +192 -194
  59. package/types/server-functions/flash.d.ts +28 -30
  60. package/types/server-functions/registry.d.ts +102 -0
  61. package/types/server-functions/rich-args.d.ts +1 -10
  62. package/types/server-functions/server.d.ts +511 -475
  63. package/types/server-functions/shared.d.ts +366 -425
  64. package/types/server-mock.d.ts +110 -13
  65. package/types/server-observe.d.ts +77 -0
  66. package/types/server.d.ts +425 -425
  67. package/types/trace.d.ts +127 -0
  68. package/LICENSE +0 -21
  69. package/dist/web.cjs +0 -2008
  70. package/frames/dist/client.cjs +0 -1916
  71. package/frames/dist/server.cjs +0 -3756
  72. package/serialization/dist/decode.cjs +0 -122
  73. package/serialization/dist/serialization.cjs +0 -244
  74. package/serialization/types-cjs/index.d.cts +0 -182
  75. package/serialization/types-cjs/package.json +0 -3
  76. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  77. package/server-functions/dist/client.cjs +0 -793
  78. package/server-functions/dist/rich-args.cjs +0 -11
  79. package/server-functions/dist/server.cjs +0 -1171
  80. package/server-functions/dist/server.dev.cjs +0 -1171
  81. package/storage/dist/storage.cjs +0 -12
  82. package/storage/types-cjs/index.d.cts +0 -28
  83. package/storage/types-cjs/package.json +0 -3
  84. package/types/core.d.ts +0 -6
  85. package/types-cjs/client.d.cts +0 -337
  86. package/types-cjs/cookies.d.cts +0 -93
  87. package/types-cjs/core.d.cts +0 -6
  88. package/types-cjs/frames/client.d.cts +0 -36
  89. package/types-cjs/frames/frame-client.d.cts +0 -338
  90. package/types-cjs/frames/frame-sink.d.cts +0 -194
  91. package/types-cjs/frames/frame-transport.d.cts +0 -222
  92. package/types-cjs/frames/serializer.d.cts +0 -182
  93. package/types-cjs/frames/server.d.cts +0 -52
  94. package/types-cjs/index.d.cts +0 -244
  95. package/types-cjs/jsx-properties.d.cts +0 -93
  96. package/types-cjs/jsx.d.cts +0 -4159
  97. package/types-cjs/package.json +0 -3
  98. package/types-cjs/response.d.cts +0 -174
  99. package/types-cjs/serializer-decode.d.cts +0 -182
  100. package/types-cjs/serializer.d.cts +0 -182
  101. package/types-cjs/server-functions/client.d.cts +0 -231
  102. package/types-cjs/server-functions/flash.d.cts +0 -38
  103. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  104. package/types-cjs/server-functions/server.d.cts +0 -616
  105. package/types-cjs/server-functions/shared.d.cts +0 -523
  106. package/types-cjs/server-mock.d.cts +0 -277
  107. package/types-cjs/server.d.cts +0 -523
package/dist/server.js CHANGED
@@ -1,6 +1,8 @@
1
- import { createRenderEffect, createMemo, sharedConfig, createRoot, getOwner, ssrHandleError, runWithOwner, inServerComponentScope, 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, untrack } from 'solid-js';
3
- import { Feature, Serializer, getCrossReferenceHeader } from 'seroval';
1
+ import { createRenderEffect, createMemo, sharedConfig, createRoot, $PROXY, getOwner, runWithOwner, createComponent, omit, getNextChildId, untrack, NotReadyError, onCleanup } from 'solid-js';
2
+ export { Errored, For, Hydration, Loading, Match, NoHydration, Repeat, Reveal, Show, Switch, createComponent, getOwner, merge as mergeProps, sharedConfig, untrack } from 'solid-js';
3
+ import { inServerComponentScope, sourceOwners, viewOf, reportServerError, ssrHandleError, creationStamp, ssrSanitizeError, getProjectionTrace, shareAsyncIterable } from 'solid-js/internal';
4
+ export { ssrScope as scope } from 'solid-js/internal';
5
+ import { Feature, createStream, Serializer, 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 = {
@@ -48,6 +50,15 @@ const Namespaces = {
48
50
  const VoidElements = /*#__PURE__*/new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
49
51
  const RawTextElements = /*#__PURE__*/new Set(["style", "script", "noscript", "template", "textarea", "title"]);
50
52
  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(","));
53
+ const COMPOSED_BODY_FRAMING = /*#__PURE__*/new Set(["content-length", "content-encoding", "transfer-encoding"]);
54
+ function isHttpNavigationTarget(target) {
55
+ try {
56
+ const protocol = new URL(target, "http://base.invalid").protocol;
57
+ return protocol === "http:" || protocol === "https:";
58
+ } catch {
59
+ return false;
60
+ }
61
+ }
51
62
 
52
63
  const transparentOptions = {
53
64
  transparent: true,
@@ -56,14 +67,184 @@ const transparentOptions = {
56
67
  const syncOptions = {
57
68
  sync: true
58
69
  };
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);
70
+ function effect(fn, effectFn, options) {
71
+ const nodeOptions = options ? {
72
+ sync: true,
73
+ ...options,
74
+ transparent: !options.scope
75
+ } : transparentOptions;
76
+ createRenderEffect(fn, effectFn, nodeOptions);
77
+ }
78
+ function memo(fn) {
79
+ return createMemo(() => fn(), syncOptions);
80
+ }
81
+
82
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;
83
+ const ZERO_TRACE = "00000000000000000000000000000000";
84
+ const ZERO_SPAN = "0000000000000000";
85
+ function parseTraceparent(value) {
86
+ if (!value) return undefined;
87
+ const m = TRACEPARENT.exec(value.trim());
88
+ if (!m) return undefined;
89
+ const [, version, traceId, parentId, flags, rest] = m;
90
+ if (version === "ff") return undefined;
91
+ if (version === "00" && rest !== undefined) return undefined;
92
+ if (traceId === ZERO_TRACE || parentId === ZERO_SPAN) return undefined;
93
+ return {
94
+ traceId,
95
+ parentId,
96
+ sampled: (parseInt(flags, 16) & 1) === 1
97
+ };
98
+ }
99
+ function randomHex(bytes) {
100
+ const buffer = new Uint8Array(bytes);
101
+ crypto.getRandomValues(buffer);
102
+ let out = "";
103
+ for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
104
+ return out;
105
+ }
106
+ function randomTraceId() {
107
+ let id = randomHex(16);
108
+ while (id === ZERO_TRACE) id = randomHex(16);
109
+ return id;
110
+ }
111
+ function randomSpanId() {
112
+ let id = randomHex(8);
113
+ while (id === ZERO_SPAN) id = randomHex(8);
114
+ return id;
115
+ }
116
+ function formatTraceparent(context) {
117
+ return `00-${context.traceId}-${context.spanId}-${context.sampled === true ? "01" : "00"}`;
118
+ }
119
+ const RECORDS_KEY = Symbol.for("@solidjs/web/trace/records");
120
+ function records() {
121
+ const g = globalThis;
122
+ return g[RECORDS_KEY] || (g[RECORDS_KEY] = new WeakMap());
123
+ }
124
+ function traceFor(key, request) {
125
+ const store = records();
126
+ let record = store.get(key);
127
+ if (record) return record;
128
+ const headers = request ? request.headers : undefined;
129
+ const incoming = headers ? parseTraceparent(headers.get("traceparent")) : undefined;
130
+ const context = {
131
+ traceId: incoming ? incoming.traceId : randomTraceId(),
132
+ spanId: randomSpanId(),
133
+ entries: {}
134
+ };
135
+ if (incoming) {
136
+ context.parentId = incoming.parentId;
137
+ context.sampled = incoming.sampled;
138
+ }
139
+ if (headers) {
140
+ const state = headers.get("tracestate");
141
+ if (state) context.state = state;
142
+ const baggage = headers.get("baggage");
143
+ if (baggage) context.baggage = baggage;
144
+ }
145
+ let answered = false;
146
+ context.entries.traceparent = formatTraceparent(context);
147
+ record = {
148
+ context,
149
+ emit: incoming !== undefined && incoming.sampled || answered,
150
+ timing: []
151
+ };
152
+ store.set(key, record);
153
+ return record;
154
+ }
155
+ function traceForEvent(event) {
156
+ return traceFor(event.request || event, event.request);
157
+ }
158
+ const TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
159
+ function splitServerTiming(value) {
160
+ const entries = [];
161
+ let start = 0;
162
+ let quoted = false;
163
+ for (let i = 0; i < value.length; i++) {
164
+ const c = value[i];
165
+ if (quoted) {
166
+ if (c === "\\") i++;else if (c === '"') quoted = false;
167
+ } else if (c === '"') quoted = true;else if (c === ",") {
168
+ entries.push(value.slice(start, i));
169
+ start = i + 1;
170
+ }
171
+ }
172
+ entries.push(value.slice(start));
173
+ return entries;
174
+ }
175
+ function metricName(entry) {
176
+ return entry.split(";")[0].trim().toLowerCase();
177
+ }
178
+ function namesOnServerTiming(headers) {
179
+ const names = new Set();
180
+ const existing = headers.get("server-timing");
181
+ if (existing) {
182
+ for (const entry of splitServerTiming(existing)) {
183
+ const name = metricName(entry);
184
+ if (name) names.add(name);
185
+ }
186
+ }
187
+ return names;
188
+ }
189
+ function quoteDesc(value) {
190
+ return value.replace(/[\x00-\x1f\x7f]/g, "").replace(/[^\x20-\x7e]/g, "?").replace(/[\\"]/g, m => "\\" + m);
191
+ }
192
+ function shellMs(record) {
193
+ return record.render !== undefined ? record.render.shellMs : undefined;
194
+ }
195
+ function hasServerTiming(record) {
196
+ return record.emit || record.timing.length > 0 || shellMs(record) !== undefined;
197
+ }
198
+ function appendTraceServerTiming(headers, record) {
199
+ if (record.emit) {
200
+ const entries = record.context.entries;
201
+ let present;
202
+ for (const name in entries) {
203
+ if (!TOKEN.test(name)) continue;
204
+ if (!present) present = namesOnServerTiming(headers);
205
+ if (present.has(name.toLowerCase())) continue;
206
+ headers.append("Server-Timing", `${name};desc="${quoteDesc(entries[name])}"`);
207
+ present.add(name.toLowerCase());
208
+ }
209
+ }
210
+ const shell = shellMs(record);
211
+ if (shell !== undefined) headers.append("Server-Timing", formatMetric("solid-shell", shell));
212
+ for (const work of record.timing) headers.append("Server-Timing", metricOf(work));
213
+ }
214
+ function metricOf(work) {
215
+ if (work.type === "invocation") return formatMetric("solid-invocation", work.event.durationMs, work.event.id);
216
+ const boundary = work.event;
217
+ return formatMetric("solid-boundary", boundary.durationMs, boundary.ownerPath !== undefined ? boundary.ownerPath.join(" > ") : boundary.id);
218
+ }
219
+ function formatMetric(name, dur, desc) {
220
+ let out = `${name};dur=${Math.round(dur * 10) / 10}`;
221
+ if (desc) out += `;desc="${quoteDesc(desc)}"`;
222
+ return out;
223
+ }
224
+ function mergeServerTiming(target, value) {
225
+ const present = namesOnServerTiming(target);
226
+ for (const entry of splitServerTiming(value)) {
227
+ const trimmed = entry.trim();
228
+ const name = metricName(trimmed);
229
+ if (!name || present.has(name)) continue;
230
+ target.append("Server-Timing", trimmed);
231
+ }
232
+ }
233
+ function escapeAttr(value) {
234
+ return value.replace(/[&"<>]/g, c => c === "&" ? "&amp;" : c === '"' ? "&quot;" : c === "<" ? "&lt;" : "&gt;");
235
+ }
236
+ function traceMetaMarkup(record) {
237
+ if (!record.emit) return "";
238
+ let markup = "";
239
+ const entries = record.context.entries;
240
+ for (const name in entries) {
241
+ if (!TOKEN.test(name)) continue;
242
+ markup += `<meta name="${name}" content="${escapeAttr(entries[name])}">`;
243
+ }
244
+ return markup;
245
+ }
65
246
 
66
- const STATE = Symbol.for("dom-expressions.container-trace-state");
247
+ const STATE = Symbol.for("solid.container-trace-state");
67
248
  const state = globalThis[STATE] || (globalThis[STATE] = {
68
249
  materialized: new WeakMap(),
69
250
  materializedValues: new WeakSet()
@@ -71,7 +252,53 @@ const state = globalThis[STATE] || (globalThis[STATE] = {
71
252
  function setContainerTraceResolver(fn) {
72
253
  state.resolveTrace = fn;
73
254
  }
74
- const TRACE = Symbol.for("dom-expressions.container-trace");
255
+ function setAsyncIterableSharer(fn) {
256
+ state.shareIterable = fn;
257
+ }
258
+ function setContainerTraceStreamMint(fn) {
259
+ state.streamOf = fn;
260
+ }
261
+ const TRACE = Symbol.for("solid.container-trace");
262
+ function toBorderForm(value, envelopeContainers) {
263
+ if (value == null || typeof value !== "object") return value;
264
+ const share = state.shareIterable;
265
+ if (!share) return value;
266
+ if (share && isShareableIterable(value)) return share(value);
267
+ if (Array.isArray(value)) {
268
+ let out = value;
269
+ for (let i = 0; i < value.length; i++) {
270
+ const next = toBorderForm(value[i]);
271
+ if (next !== value[i]) {
272
+ if (out === value) out = value.slice();
273
+ out[i] = next;
274
+ }
275
+ }
276
+ return out;
277
+ }
278
+ if (Object.getPrototypeOf(value) === Object.prototype) {
279
+ let out = value;
280
+ for (const key of Object.keys(value)) {
281
+ const next = toBorderForm(value[key]);
282
+ if (next !== value[key]) {
283
+ if (out === value) out = {
284
+ ...value
285
+ };
286
+ out[key] = next;
287
+ }
288
+ }
289
+ return out;
290
+ }
291
+ return value;
292
+ }
293
+ function isShareableIterable(value) {
294
+ try {
295
+ if (value.__SEROVAL_STREAM__ === true) return false;
296
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return false;
297
+ return typeof value[Symbol.asyncIterator] === "function";
298
+ } catch {
299
+ return false;
300
+ }
301
+ }
75
302
  function materialize(marker) {
76
303
  let value = state.materialized.get(marker.$tr);
77
304
  if (value === undefined) {
@@ -83,13 +310,14 @@ function materialize(marker) {
83
310
  }
84
311
  function parseTrace(value, ctx) {
85
312
  const trace = value[TRACE];
313
+ const sub = trace.subscribe();
86
314
  return {
87
315
  a: trace.array ? 1 : 0,
88
- i: ctx.parse(trace.subscribe())
316
+ i: ctx.parse(state.streamOf ? state.streamOf(sub) : sub)
89
317
  };
90
318
  }
91
319
  const ContainerTracePlugin = {
92
- tag: "dom-expressions/container-trace",
320
+ tag: "solid/container-trace",
93
321
  test(value) {
94
322
  return value != null && typeof value === "object" && TRACE in value;
95
323
  },
@@ -99,9 +327,10 @@ const ContainerTracePlugin = {
99
327
  },
100
328
  async async(value, ctx) {
101
329
  const trace = value[TRACE];
330
+ const sub = trace.subscribe();
102
331
  return {
103
332
  a: trace.array ? 1 : 0,
104
- i: await ctx.parse(trace.subscribe())
333
+ i: await ctx.parse(state.streamOf ? state.streamOf(sub) : sub)
105
334
  };
106
335
  },
107
336
  stream: parseTrace
@@ -119,6 +348,18 @@ const ContainerTracePlugin = {
119
348
  }
120
349
  };
121
350
 
351
+ setContainerTraceStreamMint(iterable => {
352
+ const stream = createStream();
353
+ (async () => {
354
+ try {
355
+ for await (const value of iterable) stream.next(value);
356
+ stream.return(undefined);
357
+ } catch (error) {
358
+ stream.throw(error);
359
+ }
360
+ })();
361
+ return stream;
362
+ });
122
363
  const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
123
364
  CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
124
365
  FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin,
@@ -129,13 +370,13 @@ function resolveSerializerPlugins(customPlugins) {
129
370
  Feature.RegExp;
130
371
 
131
372
  const DEFAULT_DISABLED_FEATURES = Feature.AggregateError | Feature.BigIntTypedArray;
132
- const serializeOnlyDisabledFeatures = () => process.env.NODE_ENV === "development" ? 0 : Feature.ErrorPrototypeStack;
373
+ const serializeOnlyDisabledFeatures = serializeErrorStacks => (serializeErrorStacks === undefined ? process.env.NODE_ENV === "development" : serializeErrorStacks) ? 0 : Feature.ErrorPrototypeStack;
133
374
  const HYDRATION_GLOBAL = "_$HY.r";
134
375
  function createSerializer(options) {
135
376
  return new Serializer({
136
377
  ...options,
137
378
  plugins: resolveSerializerPlugins(options.plugins),
138
- disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures()
379
+ disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures(options.serializeErrorStacks)
139
380
  });
140
381
  }
141
382
  function createHydrationSerializer({
@@ -192,11 +433,16 @@ function isSafeError(value) {
192
433
  return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
193
434
  }
194
435
  const REVALIDATE_HEADER = "X-Revalidate";
195
- function initWithRevalidate(init) {
436
+ const REVALIDATE_ALL = "*";
437
+ const RESPONSE_HEADER_VALUE_LIMIT = 4096;
438
+ function initWithRevalidate(init = {}) {
439
+ const resolved = typeof init === "number" ? {
440
+ status: init
441
+ } : init;
196
442
  const {
197
443
  revalidate,
198
444
  ...responseInit
199
- } = init;
445
+ } = resolved;
200
446
  let headers;
201
447
  if (responseInit.headers && responseInit.headers.getSetCookie) {
202
448
  headers = new Headers();
@@ -209,7 +455,17 @@ function initWithRevalidate(init) {
209
455
  } else {
210
456
  headers = new Headers(responseInit.headers);
211
457
  }
212
- revalidate !== undefined && headers.set(REVALIDATE_HEADER, revalidate.toString());
458
+ if (revalidate !== undefined) {
459
+ const list = Array.isArray(revalidate) ? revalidate : [revalidate];
460
+ if (list.length > 1 && list.includes(REVALIDATE_ALL)) {
461
+ 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.`);
462
+ }
463
+ const keys = list.join(",");
464
+ if (keys.length > RESPONSE_HEADER_VALUE_LIMIT) {
465
+ 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.`);
466
+ }
467
+ headers.set(REVALIDATE_HEADER, keys);
468
+ }
213
469
  return {
214
470
  responseInit,
215
471
  headers
@@ -222,13 +478,17 @@ function redirect(url, init = 302) {
222
478
  const {
223
479
  responseInit,
224
480
  headers
225
- } = initWithRevalidate(typeof init === "number" ? {
226
- status: init
227
- } : init);
481
+ } = initWithRevalidate(init);
228
482
  if (responseInit.status === undefined) {
229
483
  responseInit.status = 302;
230
484
  }
231
- headers.set("Location", String(url));
485
+ const target = typeof url === "string" ? url : url[HREF];
486
+ const location = typeof target === "string" ? target : String(url);
487
+ const encoded = location.replace(/[^\x00-\x7f]/gu, encodeURIComponent);
488
+ if (encoded.length > RESPONSE_HEADER_VALUE_LIMIT) {
489
+ 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.`);
490
+ }
491
+ headers.set("Location", encoded);
232
492
  return new Response(null, {
233
493
  ...responseInit,
234
494
  headers
@@ -244,11 +504,19 @@ function reload(init = {}) {
244
504
  headers
245
505
  });
246
506
  }
507
+ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
247
508
  function respond(value, init = {}) {
248
509
  const {
249
510
  responseInit,
250
511
  headers
251
512
  } = initWithRevalidate(init);
513
+ for (const header of COMPOSED_BODY_FRAMING) headers.delete(header);
514
+ if (NULL_BODY_STATUSES.has(responseInit.status)) {
515
+ return new ResponseEnvelope(new Response(null, {
516
+ ...responseInit,
517
+ headers
518
+ }), value);
519
+ }
252
520
  headers.set("Content-Type", "application/json");
253
521
  return new ResponseEnvelope(new Response(JSON.stringify(value), {
254
522
  ...responseInit,
@@ -299,6 +567,7 @@ function serializeCookie(name, value, options = {}) {
299
567
  if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
300
568
  if (options.httpOnly) cookie += "; HttpOnly";
301
569
  if (options.secure) cookie += "; Secure";
570
+ if (options.partitioned) cookie += "; Partitioned";
302
571
  if (options.sameSite) {
303
572
  const sameSite = options.sameSite.toLowerCase();
304
573
  cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
@@ -316,7 +585,9 @@ function clearFlashCookie() {
316
585
 
317
586
  const ERROR_HEADER = "X-Server-Function-Error";
318
587
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
588
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
319
589
  const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
590
+ new TextEncoder().encode(":\n\n");
320
591
 
321
592
  const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
322
593
  const HEAD_ATTR_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;
@@ -350,11 +621,24 @@ function classifyHeadTag(desc) {
350
621
  resource: false
351
622
  };
352
623
  }
624
+ function qualifierValue(name, value) {
625
+ if (value == null || value === false) return null;
626
+ if (name === "imagesrcset" || name === "imagesizes") return typeof value === "string" && value !== "" ? value : null;
627
+ const v = value === true ? "" : String(value);
628
+ if (name === "as") return asciiLowerCase(v);
629
+ if (name !== "crossorigin") return v;
630
+ return v.length === 15 && v.toLowerCase() === "use-credentials" ? v.toLowerCase() : "anonymous";
631
+ }
632
+ function asciiLowerCase(value) {
633
+ return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
634
+ }
353
635
  function resourceIdentity(tag, props) {
354
- let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
636
+ const url = String(props.href || props.src || "");
637
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + url.length + ":" + url;
355
638
  for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
356
639
  const q = RESOURCE_QUALIFIERS[i];
357
- if (props[q] != null) id += ":" + q + "=" + props[q];
640
+ const value = qualifierValue(q, props[q]);
641
+ if (value !== null) id += ":" + q + "=" + value.length + ":" + value;
358
642
  }
359
643
  return id;
360
644
  }
@@ -416,6 +700,7 @@ function resolveAssets(moduleUrl, manifest) {
416
700
  if (!entry) return null;
417
701
  const css = [];
418
702
  const js = [];
703
+ let preloads;
419
704
  const visited = new Set();
420
705
  const walk = key => {
421
706
  if (visited.has(key)) return;
@@ -424,13 +709,34 @@ function resolveAssets(moduleUrl, manifest) {
424
709
  if (!e) return;
425
710
  js.push(joinAssetPath(base, e.file));
426
711
  if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
712
+ if (e.preloads) {
713
+ for (let i = 0; i < e.preloads.length; i++) {
714
+ const link = e.preloads[i];
715
+ const href = link && typeof link.href === "string" && link.href;
716
+ const srcset = link && typeof link.imagesrcset === "string" && link.imagesrcset;
717
+ if (!href && !srcset) continue;
718
+ if (!preloads) preloads = [];
719
+ if (href) preloads.push({
720
+ ...link,
721
+ href: joinAssetPath(base, href)
722
+ });else {
723
+ const {
724
+ href: bad,
725
+ ...rest
726
+ } = link;
727
+ preloads.push(rest);
728
+ }
729
+ }
730
+ }
427
731
  if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
428
732
  };
429
733
  walk(moduleUrl);
430
- return {
734
+ const assets = {
431
735
  js,
432
736
  css
433
737
  };
738
+ if (preloads) assets.preloads = preloads;
739
+ return assets;
434
740
  }
435
741
  function registerEntryAssets(manifest) {
436
742
  if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
@@ -440,7 +746,9 @@ function registerEntryAssets(manifest) {
440
746
  if (manifest[key].isEntry) {
441
747
  const assets = resolveAssets(key, manifest);
442
748
  if (assets) {
749
+ if (assets.preloads) for (let i = 0; i < assets.preloads.length; i++) ctx.registerAsset("preload", assets.preloads[i]);
443
750
  for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
751
+ for (let i = 1; i < assets.js.length; i++) ctx.registerAsset("module", assets.js[i]);
444
752
  }
445
753
  return;
446
754
  }
@@ -457,6 +765,7 @@ function createAssetTracking() {
457
765
  boundaryStyles,
458
766
  emittedAssets,
459
767
  inlineStyles,
768
+ preloadLinks: null,
460
769
  registerInlineStyle(desc) {
461
770
  let entry = inlineStyles.get(desc.id);
462
771
  if (!entry) {
@@ -548,6 +857,82 @@ function isCssUrl(url) {
548
857
  const q = url.search(/[?#]/);
549
858
  return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
550
859
  }
860
+ const RESPONSIVE_ATTRIBUTES = ["imagesrcset", "imagesizes"];
861
+ function isSetAttr(value) {
862
+ return value != null && value !== false && value !== "";
863
+ }
864
+ const PRELOAD_LINK_ATTRIBUTES = ["type", "crossorigin", "integrity", "referrerpolicy", "fetchpriority", "media", "imagesrcset", "imagesizes"];
865
+ function registerPreloadLink(tracking, headRegistry, link, nonce) {
866
+ if (!link || typeof link !== "object") {
867
+ return null;
868
+ }
869
+ if (typeof link.as !== "string") {
870
+ return null;
871
+ }
872
+ const as = asciiLowerCase(link.as);
873
+ let destination = null;
874
+ switch (as) {
875
+ case "script":
876
+ case "style":
877
+ destination = as;
878
+ break;
879
+ case "fetch":
880
+ case "font":
881
+ case "image":
882
+ case "track":
883
+ break;
884
+ default:
885
+ return null;
886
+ }
887
+ const responsive = as === "image";
888
+ let srcset = null;
889
+ let sizes = null;
890
+ if (responsive) {
891
+ for (const name of RESPONSIVE_ATTRIBUTES) {
892
+ const value = link[name];
893
+ if (!isSetAttr(value)) continue;
894
+ if (typeof value !== "string") {
895
+ continue;
896
+ }
897
+ if (name === "imagesrcset") srcset = value;else sizes = value;
898
+ }
899
+ }
900
+ const href = typeof link.href === "string" && link.href ? link.href : null;
901
+ if (!href && !srcset) {
902
+ return null;
903
+ }
904
+ const props = {
905
+ rel: "preload"
906
+ };
907
+ if (href) props.href = href;
908
+ props.as = as;
909
+ for (let i = 0; i < PRELOAD_LINK_ATTRIBUTES.length; i++) {
910
+ const name = PRELOAD_LINK_ATTRIBUTES[i];
911
+ if (RESPONSIVE_ATTRIBUTES.indexOf(name) !== -1) {
912
+ const value = name === "imagesrcset" ? srcset : sizes;
913
+ if (value !== null) props[name] = value;
914
+ continue;
915
+ }
916
+ const value = link[name];
917
+ if (value == null || value === false) continue;
918
+ props[name] = value === true ? "" : String(value);
919
+ }
920
+ const identity = resourceIdentity("link", props);
921
+ if (headRegistry.resources.has(identity)) return null;
922
+ const attrs = headAttrRecord(props);
923
+ const nonceValue = destination && nonce && nonce[destination];
924
+ if (typeof nonceValue === "string" && nonceValue) attrs.nonce = nonceValue;
925
+ const entry = {
926
+ href: props.href,
927
+ attrs,
928
+ attrHtml: renderHeadAttrHtml(props) + nonceAttr(nonce, destination)
929
+ };
930
+ headRegistry.resources.add(identity);
931
+ let links = tracking.preloadLinks;
932
+ if (!links) tracking.preloadLinks = links = [];
933
+ links.push(entry);
934
+ return entry;
935
+ }
551
936
  function createHeadRegistry() {
552
937
  return {
553
938
  pending: [],
@@ -700,7 +1085,7 @@ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc
700
1085
  if (!styles) tracking.boundaryStyles.set(tracking.currentBoundaryId, styles = new Set());
701
1086
  styles.add(entry);
702
1087
  }
703
- const markup = `<link${attrHtml}>`;
1088
+ const markup = `<link${attrHtml}${nonceAttr(nonce, "style")}>`;
704
1089
  if (emitResource) emitResource(markup, entry);else {
705
1090
  registry.eagerHtml += markup;
706
1091
  entry.emitted = true;
@@ -798,7 +1183,7 @@ function headGroupSignature(winner) {
798
1183
  }
799
1184
  return sig;
800
1185
  }
801
- function renderShellHead(registry, nonce, isPendingFragment) {
1186
+ function renderShellHead(registry, nonce, isPendingFragment, noScripts, traceMetas = "") {
802
1187
  commitHeadBoundary(registry, "", isPendingFragment);
803
1188
  registry.shellFlushed = true;
804
1189
  const winners = resolveHead(registry.committed);
@@ -808,8 +1193,14 @@ function renderShellHead(registry, nonce, isPendingFragment) {
808
1193
  let metas = "";
809
1194
  let others = "";
810
1195
  let scripts = "";
1196
+ let title = null;
811
1197
  for (const [identity, winner] of winners) {
812
1198
  registry.flushed.set(identity, headGroupSignature(winner));
1199
+ if (identity === "title") {
1200
+ const children = winner.tags[0].props.children;
1201
+ title = children == null ? "" : String(children);
1202
+ continue;
1203
+ }
813
1204
  for (let i = 0; i < winner.tags.length; i++) {
814
1205
  const t = winner.tags[i];
815
1206
  const markup = renderHeadTagMarkup(t.tag, t.props, identity, nonce);
@@ -818,10 +1209,12 @@ function renderShellHead(registry, nonce, isPendingFragment) {
818
1209
  }
819
1210
  return {
820
1211
  prelude,
821
- html: registry.eagerHtml + links + metas + others + scripts
1212
+ html: registry.eagerHtml + links + metas + traceMetas + others + scripts,
1213
+ title,
1214
+ noScripts
822
1215
  };
823
1216
  }
824
- function flushHeadFragment(registry, boundary) {
1217
+ function flushHeadFragment(registry, boundary, nonce) {
825
1218
  const groups = commitHeadBoundary(registry, boundary);
826
1219
  if (!groups.length) return null;
827
1220
  const winners = resolveHead(registry.committed);
@@ -852,12 +1245,84 @@ function flushHeadFragment(registry, boundary) {
852
1245
  if (v == null || v === false) continue;
853
1246
  attrs[name] = v === true ? "" : String(v);
854
1247
  }
1248
+ if (nonce && !hasNonceProp(t.props)) {
1249
+ const destination = nonceDestination(t.tag, t.props);
1250
+ const value = destination && nonce[destination];
1251
+ if (value) attrs.nonce = String(value);
1252
+ }
855
1253
  const children = t.props.children;
856
1254
  ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
857
1255
  }
858
1256
  }
859
1257
  return ops.length ? ops : null;
860
1258
  }
1259
+ function normalizeNonce(nonce) {
1260
+ if (nonce == null) return undefined;
1261
+ if (typeof nonce === "string") {
1262
+ const attr = nonce ? ` nonce="${escape(nonce, true)}"` : "";
1263
+ return {
1264
+ script: nonce,
1265
+ style: nonce,
1266
+ scriptAttr: attr,
1267
+ styleAttr: attr
1268
+ };
1269
+ }
1270
+ const script = nonce.script;
1271
+ const style = nonce.style;
1272
+ if (!script && !style) return undefined;
1273
+ return {
1274
+ script,
1275
+ style,
1276
+ scriptAttr: typeof script === "string" && script ? ` nonce="${escape(script, true)}"` : "",
1277
+ styleAttr: typeof style === "string" && style ? ` nonce="${escape(style, true)}"` : ""
1278
+ };
1279
+ }
1280
+ function destinationNonce(nonce, destination) {
1281
+ if (nonce == null) return undefined;
1282
+ if (typeof nonce === "string") return nonce || undefined;
1283
+ const value = nonce[destination];
1284
+ return typeof value === "string" && value ? value : undefined;
1285
+ }
1286
+ function scriptNonce(nonce) {
1287
+ return destinationNonce(nonce, "script");
1288
+ }
1289
+ function styleNonce(nonce) {
1290
+ return destinationNonce(nonce, "style");
1291
+ }
1292
+ function hasNonceProp(props) {
1293
+ for (const name in props) if (name.length === 5 && asciiLowerCase(name) === "nonce" && props[name] != null) return true;
1294
+ return false;
1295
+ }
1296
+ function nonceDestination(tag, props) {
1297
+ if (tag === "script") return "script";
1298
+ if (tag === "style") return "style";
1299
+ if (tag !== "link") return null;
1300
+ const rel = props.rel;
1301
+ if (typeof rel !== "string") return null;
1302
+ const rels = asciiLowerCase(rel).split(/[\t\n\f\r ]+/);
1303
+ if (rels.includes("stylesheet")) return "style";
1304
+ const isModulePreload = rels.includes("modulepreload");
1305
+ if (!isModulePreload && !rels.includes("preload")) return null;
1306
+ const as = typeof props.as === "string" ? asciiLowerCase(props.as) : "";
1307
+ if (as === "style") return "style";
1308
+ if (as === "script") return "script";
1309
+ if (!isModulePreload) return null;
1310
+ switch (as) {
1311
+ case "fetch":
1312
+ case "font":
1313
+ case "image":
1314
+ case "json":
1315
+ case "text":
1316
+ case "track":
1317
+ return null;
1318
+ default:
1319
+ return "script";
1320
+ }
1321
+ }
1322
+ function nonceAttr(nonce, destination) {
1323
+ if (!nonce || !destination) return "";
1324
+ return destination === "script" ? nonce.scriptAttr : nonce.styleAttr;
1325
+ }
861
1326
  function renderHeadAttrHtml(props) {
862
1327
  let attrs = "";
863
1328
  for (const name in props) {
@@ -886,7 +1351,7 @@ function headAttrRecord(props, skipRelHref) {
886
1351
  function renderHeadTagMarkup(tag, props, identity, nonce) {
887
1352
  let attrs = renderHeadAttrHtml(props);
888
1353
  if (identity != null) attrs += ` data-dh="${escape(identity, true)}"`;
889
- if (nonce && (tag === "script" || tag === "style")) attrs += ` nonce="${nonce}"`;
1354
+ if (nonce && !hasNonceProp(props)) attrs += nonceAttr(nonce, nonceDestination(tag, props));
890
1355
  if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
891
1356
  let body = props.children == null ? "" : String(props.children);
892
1357
  if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
@@ -900,16 +1365,38 @@ function useHead(tags) {
900
1365
  ctx.registerHeadTags(tags);
901
1366
  }
902
1367
  const VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
1368
+ const tagInfos = /*#__PURE__*/new Map();
1369
+ function tagInfo(tag) {
1370
+ let info = tagInfos.get(tag);
1371
+ if (info === undefined) {
1372
+ info = {
1373
+ open: "<" + tag,
1374
+ close: "</" + tag + ">",
1375
+ isVoid: VOID_ELEMENTS.test(tag),
1376
+ textarea: tag === "textarea",
1377
+ raw: tag === "script" || tag === "style"
1378
+ };
1379
+ if (tagInfos.size < 512) tagInfos.set(tag, info);
1380
+ }
1381
+ return info;
1382
+ }
1383
+ const safeAttrNames = /*#__PURE__*/new Set();
1384
+ function attrName(prop) {
1385
+ if (safeAttrNames.has(prop)) return prop;
1386
+ const escaped = escape(prop);
1387
+ if (escaped === prop && safeAttrNames.size < 512) safeAttrNames.add(prop);
1388
+ return escaped;
1389
+ }
903
1390
  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])}`;
904
- const HEAD_SCRIPT = `function $dha(o,i,e,n){for(i=0;i<o.length;i++)e=o[i],"t"==e[0]?((n=document.querySelector("title"))||(n=document.createElement("title"),document.head.appendChild(n)),n.textContent=e[1],n.setAttribute("data-dh","title")):"r"==e[0]?$dhr(e[1]):(n=document.createElement(e[2]),Object.keys(e[3]).forEach(function(a){n.setAttribute(a,e[3][a])}),null!=e[4]&&(n.textContent=e[4]),n.setAttribute("data-dh",e[1]),document.head.appendChild(n))}function $dhr(v,l,i){for(l=document.head.querySelectorAll("[data-dh]"),i=0;i<l.length;i++)l[i].getAttribute("data-dh")==v&&l[i].remove()}function $dh(o){_$HY.h?_$HY.h(o):$dha(o)}`;
1391
+ 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)}`;
905
1392
  function renderToString(code, options = {}) {
906
1393
  const {
907
1394
  renderId = "",
908
- nonce,
909
1395
  noScripts,
910
1396
  manifest,
911
1397
  onHead
912
1398
  } = options;
1399
+ const nonce = normalizeNonce(options.nonce);
913
1400
  let scripts = "";
914
1401
  const serializer = createHydrationSerializer({
915
1402
  scopeId: renderId,
@@ -921,15 +1408,16 @@ function renderToString(code, options = {}) {
921
1408
  }
922
1409
  scripts += script + ";";
923
1410
  },
924
- onError: options.onError
1411
+ onError: serializerErrorHook(options.onError)
925
1412
  });
926
1413
  const tracking = createAssetTracking();
927
1414
  const headRegistry = createHeadRegistry();
928
1415
  sharedConfig.context = {
929
- nonce,
1416
+ nonce: options.nonce,
930
1417
  escape: escape,
931
1418
  resolve: resolveSSRNode,
932
1419
  ssr: ssr,
1420
+ errorPolicy: options.onError,
933
1421
  registerHeadTags(tags) {
934
1422
  registerHeadTags(headRegistry, sharedConfig.context, tracking, null, nonce, tags);
935
1423
  },
@@ -941,6 +1429,10 @@ function renderToString(code, options = {}) {
941
1429
  serializer.write(id, p);
942
1430
  },
943
1431
  registerAsset(type, value) {
1432
+ if (type === "preload") {
1433
+ registerPreloadLink(tracking, headRegistry, value, nonce);
1434
+ return;
1435
+ }
944
1436
  if (type === "inline-style") {
945
1437
  tracking.registerInlineStyle(value);
946
1438
  return;
@@ -958,21 +1450,40 @@ function renderToString(code, options = {}) {
958
1450
  };
959
1451
  applyAssetTracking(sharedConfig.context, tracking, manifest, noScripts);
960
1452
  registerEntryAssets(manifest);
961
- let html = createRoot(d => {
962
- setTimeout(d);
963
- return resolveSSRSync(escape(code()));
964
- }, {
965
- id: renderId
966
- });
967
- serializeFragmentAssets("", tracking.boundaryModules, sharedConfig.context, renderId);
968
- sharedConfig.context.noHydrate = true;
969
- serializer.close();
970
- const head = renderShellHead(headRegistry, nonce, null);
971
- return assembleDocument(resolveSSRSelectValues(html), tracking.emittedAssets, tracking.inlineStyles, scripts.length ? scripts : "", nonce, head, onHead);
1453
+ const context = sharedConfig.context;
1454
+ const requestEvent = peekRequestEvent();
1455
+ context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
1456
+ const render = timeDocument(context, context.trace);
1457
+ let dispose;
1458
+ let rendered = false;
1459
+ try {
1460
+ const html = createRoot(d => {
1461
+ dispose = d;
1462
+ return resolveSSRSync(escape(code()));
1463
+ }, {
1464
+ id: renderId
1465
+ });
1466
+ serializeFragmentAssets("", tracking.boundaryModules, sharedConfig.context, renderId);
1467
+ sharedConfig.context.noHydrate = true;
1468
+ serializer.close();
1469
+ const head = renderShellHead(headRegistry, nonce, null, noScripts, traceMetaMarkup(context.trace));
1470
+ const document = assembleDocument(resolveSSRSelectValues(html), tracking.emittedAssets, tracking.preloadLinks, tracking.inlineStyles, scripts.length ? scripts : "", nonce, head, onHead);
1471
+ if (render) render.shell();
1472
+ if (requestEvent && requestEvent.response) {
1473
+ commitResponseStub(requestEvent.response, {
1474
+ event: requestEvent
1475
+ });
1476
+ }
1477
+ rendered = true;
1478
+ return document;
1479
+ } finally {
1480
+ if (render) render.settle(rendered ? "complete" : "error");
1481
+ context.trace = undefined;
1482
+ if (dispose) dispose();
1483
+ }
972
1484
  }
973
1485
  function renderToStream(code, options = {}) {
974
1486
  let {
975
- nonce,
976
1487
  onCompleteShell,
977
1488
  onCompleteAll,
978
1489
  renderId = "",
@@ -980,12 +1491,40 @@ function renderToStream(code, options = {}) {
980
1491
  manifest,
981
1492
  onHead
982
1493
  } = options;
1494
+ const nonce = normalizeNonce(options.nonce);
1495
+ const requestEvent = peekRequestEvent();
983
1496
  let dispose;
984
1497
  let dead = false;
985
- const abandon = () => {
1498
+ let render;
1499
+ let serializer;
1500
+ let disconnected = false;
1501
+ let failed = false;
1502
+ let onFailed;
1503
+ const defuse = p => {
1504
+ if (p && typeof p.then === "function") p.then(undefined, () => {});
1505
+ };
1506
+ const abandonedSerializer = {
1507
+ write(_, value) {
1508
+ defuse(value);
1509
+ },
1510
+ flush() {},
1511
+ close() {}
1512
+ };
1513
+ const onFailure = complete => {
1514
+ if (failed) return complete(undefined);
1515
+ const prev = onFailed;
1516
+ onFailed = prev ? sink => {
1517
+ prev(sink);
1518
+ complete(sink);
1519
+ } : complete;
1520
+ };
1521
+ const abandon = disconnect => {
986
1522
  if (dead) return;
987
1523
  dead = true;
988
1524
  completed = true;
1525
+ if (disconnect) disconnected = true;
1526
+ if (render) render.settle(disconnect ? "abandoned" : "error");
1527
+ const sink = writable;
989
1528
  buffer = {
990
1529
  write() {}
991
1530
  };
@@ -997,32 +1536,99 @@ function renderToStream(code, options = {}) {
997
1536
  dispose = () => {};
998
1537
  d();
999
1538
  }
1539
+ if (serializer && typeof serializer.close === "function") {
1540
+ try {
1541
+ serializer.close();
1542
+ } catch (err) {
1543
+ reportServerError(err, {
1544
+ kind: "render",
1545
+ handling: "serialize"
1546
+ }, null, options.onError);
1547
+ }
1548
+ }
1549
+ serializer = abandonedSerializer;
1550
+ if (stubBatch) {
1551
+ for (const p of stubBatch.values()) defuse(p);
1552
+ stubBatch = null;
1553
+ }
1554
+ if (!disconnect) {
1555
+ failed = true;
1556
+ onFailed && onFailed(sink);
1557
+ }
1000
1558
  };
1001
1559
  const failRender = err => {
1002
- try {
1003
- options.onError ? options.onError(err) : console.error(err);
1004
- } catch (_) {}
1560
+ reportServerError(err, {
1561
+ kind: "render",
1562
+ handling: "failed"
1563
+ }, null);
1564
+ if (!options.onError && ambientServerErrorHook() === undefined) console.error(err);
1005
1565
  abandon();
1006
1566
  };
1567
+ const failRootRender = err => {
1568
+ failRender(err);
1569
+ };
1570
+ const coalesceWrites = (writeRaw, endRaw) => {
1571
+ let buf = "";
1572
+ let scheduled = false;
1573
+ const flush = () => {
1574
+ scheduled = false;
1575
+ if (!buf) return;
1576
+ const out = buf;
1577
+ buf = "";
1578
+ writeRaw(out);
1579
+ };
1580
+ return {
1581
+ write(payload) {
1582
+ buf += payload;
1583
+ if (buf.length >= 16384) return flush();
1584
+ if (!scheduled) {
1585
+ scheduled = true;
1586
+ deferFlush(flush);
1587
+ }
1588
+ },
1589
+ flush,
1590
+ end() {
1591
+ flush();
1592
+ endRaw();
1593
+ }
1594
+ };
1595
+ };
1007
1596
  const guardSink = w => ({
1008
1597
  write(payload) {
1009
- if (dead) return;
1598
+ if (disconnected) return;
1010
1599
  try {
1011
1600
  w.write(payload);
1012
1601
  } catch (_) {
1013
- abandon();
1602
+ abandon("sink");
1014
1603
  }
1015
1604
  },
1016
1605
  end() {
1017
- if (dead) return;
1606
+ if (disconnected) return;
1018
1607
  try {
1019
1608
  w.end();
1020
1609
  } catch (_) {
1021
- abandon();
1610
+ abandon("sink");
1022
1611
  }
1023
1612
  }
1024
1613
  });
1025
1614
  const blockingPromises = new Set();
1615
+ const canBatchStubs = !options.serializer && !options.sink;
1616
+ let stubBatch = null;
1617
+ const STUB_BATCH_KEY = "$B";
1618
+ const flushStubBatch = () => {
1619
+ if (!stubBatch) return;
1620
+ const batch = stubBatch;
1621
+ stubBatch = null;
1622
+ if (batch.size === 1) {
1623
+ const [id, p] = batch.entries().next().value;
1624
+ serializer.write(id, p);
1625
+ return;
1626
+ }
1627
+ const obj = {};
1628
+ for (const [id, p] of batch) obj[id] = p;
1629
+ serializer.write(STUB_BATCH_KEY, obj);
1630
+ pushTask(`(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r["${STUB_BATCH_KEY}"]})(_$HY.r["${STUB_BATCH_KEY}"])`);
1631
+ };
1026
1632
  let headerEmitted = false;
1027
1633
  const pushTask = task => {
1028
1634
  if (noScripts) return;
@@ -1037,7 +1643,9 @@ function renderToStream(code, options = {}) {
1037
1643
  }
1038
1644
  };
1039
1645
  const onDone = () => {
1646
+ if (dead) return;
1040
1647
  writeTasks();
1648
+ lastBlockingSize = blockingPromises.size;
1041
1649
  doShell();
1042
1650
  onCompleteAll && onCompleteAll({
1043
1651
  write(v) {
@@ -1046,6 +1654,7 @@ function renderToStream(code, options = {}) {
1046
1654
  });
1047
1655
  writable && writable.end();
1048
1656
  completed = true;
1657
+ if (render) render.settle("complete");
1049
1658
  if (firstFlushed) dispose();
1050
1659
  };
1051
1660
  const sink = {
@@ -1059,10 +1668,11 @@ function renderToStream(code, options = {}) {
1059
1668
  buffer.write(renderInlineStyle(styles.inline[i], nonce));
1060
1669
  }
1061
1670
  if (styles.links.length) {
1671
+ const styleAttr = nonceAttr(nonce, "style");
1062
1672
  emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
1063
1673
  writeTasks();
1064
1674
  for (const entry of styles.links) {
1065
- buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}" onload="$dfc('${key}')" onerror="$dfc('${key}')">` : `<link${entry.attrHtml} onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
1675
+ 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}')">`);
1066
1676
  }
1067
1677
  buffer.write(`<template id="${key}">${value}</template>`);
1068
1678
  } else {
@@ -1077,7 +1687,9 @@ function renderToStream(code, options = {}) {
1077
1687
  },
1078
1688
  asset(type, value) {
1079
1689
  if (type === "module") {
1080
- buffer.write(`<link rel="modulepreload" href="${value}">`);
1690
+ buffer.write(`<link rel="modulepreload" href="${value}"${nonceAttr(nonce, "script")}>`);
1691
+ } else if (type === "preload") {
1692
+ buffer.write(`<link${value.attrHtml}>`);
1081
1693
  } else if (type === "inline-style") {
1082
1694
  buffer.write(renderInlineStyle(value, nonce));
1083
1695
  } else if (type === "head-tag") {
@@ -1085,16 +1697,16 @@ function renderToStream(code, options = {}) {
1085
1697
  }
1086
1698
  },
1087
1699
  shell(shellHtml, meta) {
1088
- buffer.write(assembleDocument(shellHtml, meta.preloads, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
1700
+ buffer.write(assembleDocument(shellHtml, meta.preloads, meta.preloadLinks, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
1089
1701
  },
1090
1702
  ...options.sink
1091
1703
  };
1092
- const serializer = (options.serializer || createHydrationSerializer)({
1704
+ serializer = (options.serializer || createHydrationSerializer)({
1093
1705
  scopeId: options.renderId,
1094
1706
  plugins: options.plugins,
1095
1707
  onData: payload => sink.data(payload),
1096
1708
  onDone,
1097
- onError: options.onError
1709
+ onError: serializerErrorHook(options.onError)
1098
1710
  });
1099
1711
  let rootAssetsSerialized = false;
1100
1712
  const serializeRootAssets = () => {
@@ -1112,14 +1724,86 @@ function renderToStream(code, options = {}) {
1112
1724
  context.live.end = null;
1113
1725
  end();
1114
1726
  }
1727
+ flushStubBatch();
1115
1728
  serializer.flush();
1116
1729
  }));
1117
1730
  }
1118
1731
  };
1119
1732
  const registry = new Map();
1733
+ const pendingSerialized = new Map();
1734
+ const guardedChannels = new WeakMap();
1735
+ const verdictNow = error => {
1736
+ throw ssrSanitizeError(error, null);
1737
+ };
1738
+ const borderForm = value => toBorderForm(value);
1739
+ const guardIterable = iterable => ({
1740
+ [Symbol.asyncIterator]() {
1741
+ const iterator = iterable[Symbol.asyncIterator]();
1742
+ return {
1743
+ next: value => iterator.next(value).then(undefined, verdictNow),
1744
+ return: value => iterator.return ? iterator.return(value) : Promise.resolve({
1745
+ done: true,
1746
+ value
1747
+ }),
1748
+ throw: error => iterator.throw ? iterator.throw(error) : Promise.reject(error)
1749
+ };
1750
+ }
1751
+ });
1752
+ const guardStream = source => {
1753
+ const reader = source.getReader();
1754
+ return new ReadableStream({
1755
+ pull: c => reader.read().then(r => r.done ? c.close() : c.enqueue(r.value), e => {
1756
+ try {
1757
+ verdictNow(e);
1758
+ } catch (sanitized) {
1759
+ c.error(sanitized);
1760
+ }
1761
+ }),
1762
+ cancel: reason => reader.cancel(reason)
1763
+ });
1764
+ };
1765
+ const guardChannel = p => {
1766
+ if (!p || typeof p !== "object" || "__SEROVAL_STREAM__" in p) return p;
1767
+ let guarded = guardedChannels.get(p);
1768
+ if (guarded !== undefined) return guarded;
1769
+ if (typeof p.then === "function") {
1770
+ guarded = p.then(borderForm, verdictNow);
1771
+ } else if (typeof ReadableStream === "function" && p instanceof ReadableStream) {
1772
+ guarded = guardStream(p);
1773
+ } else {
1774
+ const border = borderForm(p);
1775
+ guarded = typeof border[Symbol.asyncIterator] === "function" ? guardIterable(border) : border;
1776
+ if (guarded === p) return p;
1777
+ }
1778
+ guardedChannels.set(p, guarded);
1779
+ return guarded;
1780
+ };
1781
+ const trackSerialized = (id, p) => {
1782
+ let settle;
1783
+ const raced = Promise.race([p, new Promise(r => settle = r)]);
1784
+ raced.catch(() => {});
1785
+ pendingSerialized.set(id, settle);
1786
+ const drop = () => pendingSerialized.delete(id);
1787
+ p.then(drop, drop);
1788
+ return raced;
1789
+ };
1790
+ const abandonSubtree = (key, error) => {
1791
+ for (const [k, entry] of registry) {
1792
+ if (k.length > key.length && k.startsWith(key)) {
1793
+ registry.delete(k);
1794
+ entry.resolve();
1795
+ }
1796
+ }
1797
+ for (const [id, settle] of pendingSerialized) {
1798
+ if (id.startsWith(key)) {
1799
+ pendingSerialized.delete(id);
1800
+ settle();
1801
+ }
1802
+ }
1803
+ };
1120
1804
  const writeTasks = () => {
1121
1805
  if (tasks.length && !completed && firstFlushed) {
1122
- buffer.write(`<script${nonce ? ` nonce="${nonce}"` : ""}>${tasks}</script>`);
1806
+ buffer.write(`<script${nonceAttr(nonce, "script")}>${tasks}</script>`);
1123
1807
  tasks = "";
1124
1808
  }
1125
1809
  timer = null;
@@ -1173,7 +1857,8 @@ function renderToStream(code, options = {}) {
1173
1857
  };
1174
1858
  sharedConfig.context = context = {
1175
1859
  async: true,
1176
- nonce,
1860
+ nonce: options.nonce,
1861
+ document: !options.sink,
1177
1862
  live: {},
1178
1863
  registerHeadTags(tags) {
1179
1864
  registerHeadTags(headRegistry, context, tracking,
@@ -1187,6 +1872,11 @@ function renderToStream(code, options = {}) {
1187
1872
  }, nonce, tags);
1188
1873
  },
1189
1874
  registerAsset(type, value) {
1875
+ if (type === "preload") {
1876
+ const entry = registerPreloadLink(tracking, headRegistry, value, nonce);
1877
+ if (entry && firstFlushed) sink.asset("preload", entry);
1878
+ return;
1879
+ }
1190
1880
  if (type === "inline-style") {
1191
1881
  const entry = tracking.registerInlineStyle(value);
1192
1882
  if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
@@ -1231,10 +1921,20 @@ function renderToStream(code, options = {}) {
1231
1921
  },
1232
1922
  serialize(id, p, deferStream) {
1233
1923
  if (sharedConfig.context.noHydrate) return;
1234
- if (!firstFlushed && deferStream && typeof p === "object" && "then" in p) {
1235
- blockingPromises.add(p);
1236
- p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
1237
- } else serializer.write(id, p);
1924
+ p = guardChannel(p);
1925
+ if (p && typeof p === "object" && typeof p.then === "function") {
1926
+ if (!firstFlushed && deferStream) {
1927
+ blockingPromises.add(p);
1928
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
1929
+ return;
1930
+ }
1931
+ p = trackSerialized(id, p);
1932
+ if (!firstFlushed && canBatchStubs && !shellCompleted && !dead) {
1933
+ (stubBatch ||= new Map()).set(id, p);
1934
+ return;
1935
+ }
1936
+ }
1937
+ serializer.write(id, p);
1238
1938
  },
1239
1939
  escape: escape,
1240
1940
  resolve: resolveSSRNode,
@@ -1262,19 +1962,21 @@ function renderToStream(code, options = {}) {
1262
1962
  if (!registry.has(key)) {
1263
1963
  let resolve, reject;
1264
1964
  const p = new Promise((r, rej) => (resolve = r, reject = rej));
1965
+ defuse(p);
1265
1966
  registry.set(key, {
1266
1967
  resolve: err => queue(() => queue(() => {
1267
- err ? reject(err) : resolve(true);
1968
+ err ? reject(ssrSanitizeError(err, null)) : resolve(true);
1268
1969
  queue(flushEnd);
1269
1970
  }))
1270
1971
  });
1271
- serializer.write(key + "_fr", p);
1972
+ if (canBatchStubs && !shellCompleted && !dead) (stubBatch ||= new Map()).set(key + "_fr", p);else serializer.write(key + "_fr", p);
1272
1973
  }
1273
1974
  return (value, error) => {
1274
1975
  if (registry.has(key)) {
1275
1976
  const item = registry.get(key);
1276
1977
  registry.delete(key);
1277
- if (item.children) {
1978
+ if (error) abandonSubtree(key);
1979
+ if (item.children && !error) {
1278
1980
  for (const k in item.children) {
1279
1981
  value = replacePlaceholder(value, k, item.children[k]);
1280
1982
  }
@@ -1299,12 +2001,12 @@ function renderToStream(code, options = {}) {
1299
2001
  } else {
1300
2002
  serializeFragmentAssets(key, tracking.boundaryModules, context);
1301
2003
  const styles = collectStreamStyles(key, tracking, headStyles);
1302
- const headOps = error ? null : flushHeadFragment(headRegistry, key);
2004
+ const headOps = error ? null : flushHeadFragment(headRegistry, key, nonce);
1303
2005
  if (headOps) emitHeadOps(key, headOps);
1304
2006
  sink.fragment(key, resolveSSRSelectValues(value !== undefined ? value : " "), {
1305
2007
  styles,
1306
2008
  revealGroup,
1307
- error
2009
+ error: error ? ssrSanitizeError(error, null) : error
1308
2010
  });
1309
2011
  item.resolve(error);
1310
2012
  }
@@ -1330,9 +2032,19 @@ function renderToStream(code, options = {}) {
1330
2032
  };
1331
2033
  applyAssetTracking(context, tracking, manifest, noScripts);
1332
2034
  context.failRender = failRender;
2035
+ context.errorPolicy = options.onError;
2036
+ context.flushed = () => firstFlushed;
2037
+ context.trace = requestEvent ? traceForEvent(requestEvent) : traceFor(context, undefined);
2038
+ render = timeDocument(context, context.trace);
1333
2039
  registerEntryAssets(manifest);
2040
+ const signal = options.signal;
2041
+ const onAbort = signal ? () => abandon("signal") : undefined;
1334
2042
  let html = createRoot(d => {
1335
- dispose = d;
2043
+ dispose = () => {
2044
+ context.trace = undefined;
2045
+ if (onAbort) signal.removeEventListener("abort", onAbort);
2046
+ d();
2047
+ };
1336
2048
  const res = resolveSSRNode(escape(code()));
1337
2049
  if (!res.h.length) return res.t[0];
1338
2050
  rootHoles = [];
@@ -1350,6 +2062,11 @@ function renderToStream(code, options = {}) {
1350
2062
  }, {
1351
2063
  id: renderId
1352
2064
  });
2065
+ if (onAbort) {
2066
+ if (signal.aborted) onAbort();else signal.addEventListener("abort", onAbort, {
2067
+ once: true
2068
+ });
2069
+ }
1353
2070
  function resolveRootHoles() {
1354
2071
  if (!rootHoles) return true;
1355
2072
  const pending = [];
@@ -1385,16 +2102,21 @@ function renderToStream(code, options = {}) {
1385
2102
  function doShell() {
1386
2103
  if (shellCompleted) return;
1387
2104
  sharedConfig.context = context;
2105
+ if (blockingPromises.size !== lastBlockingSize) return;
1388
2106
  if (!resolveRootHoles()) return;
2107
+ if (blockingPromises.size !== lastBlockingSize) return;
1389
2108
  if (!headShellReady(headRegistry, p => blockingPromises.add(p))) return;
1390
2109
  headStyles = new Set();
1391
2110
  for (const url of tracking.emittedAssets) {
1392
2111
  if (isCssUrl(url)) headStyles.add(url);
1393
2112
  }
1394
2113
  serializeRootAssets();
1395
- const head = renderShellHead(headRegistry, nonce, k => registry.has(k));
2114
+ flushStubBatch();
2115
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k), noScripts, traceMetaMarkup(context.trace));
2116
+ if (render) render.shell();
1396
2117
  sink.shell(resolveSSRSelectValues(html), {
1397
2118
  preloads: tracking.emittedAssets,
2119
+ preloadLinks: tracking.preloadLinks,
1398
2120
  inlineStyles: tracking.inlineStyles,
1399
2121
  tasks,
1400
2122
  head
@@ -1411,8 +2133,9 @@ function renderToStream(code, options = {}) {
1411
2133
  let lastBlockingSize = -1;
1412
2134
  let lastRegistrySize = -1;
1413
2135
  let drainTurn = 0;
1414
- const scheduleFlush = fn => {
2136
+ const scheduleFlush = (fn, awaited) => {
1415
2137
  const attempt = () => {
2138
+ flushStubBatch();
1416
2139
  if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1417
2140
  if (registry.size !== lastRegistrySize) drainTurn = 0;
1418
2141
  lastRegistrySize = registry.size;
@@ -1421,8 +2144,8 @@ function renderToStream(code, options = {}) {
1421
2144
  }
1422
2145
  fn();
1423
2146
  };
1424
- const progressed = blockingPromises.size !== lastBlockingSize;
1425
- lastBlockingSize = blockingPromises.size;
2147
+ const progressed = awaited !== lastBlockingSize;
2148
+ lastBlockingSize = awaited;
1426
2149
  lastRegistrySize = -1;
1427
2150
  drainTurn = 0;
1428
2151
  progressed ? queue(attempt) : setTimeout(attempt);
@@ -1438,15 +2161,21 @@ function renderToStream(code, options = {}) {
1438
2161
  const pipeToImpl = w => {
1439
2162
  let resolve;
1440
2163
  const p = new Promise(r => resolve = r);
2164
+ onFailure(sink => {
2165
+ try {
2166
+ if (sink) sink.end();else w.close().catch(() => {});
2167
+ } catch (_) {}
2168
+ resolve();
2169
+ });
1441
2170
  function flush() {
1442
- allSettled(blockingPromises).then(() => {
2171
+ allSettled(blockingPromises).then(awaited => {
1443
2172
  scheduleFlush(() => {
1444
2173
  if (dead) return resolve();
1445
2174
  try {
1446
2175
  doShell();
1447
2176
  } catch (err) {
1448
- failRender(err);
1449
- return resolve();
2177
+ failRootRender(err);
2178
+ return;
1450
2179
  }
1451
2180
  if (!shellCompleted) return flush();
1452
2181
  const encoder = new TextEncoder();
@@ -1455,33 +2184,29 @@ function renderToStream(code, options = {}) {
1455
2184
  let ended = false;
1456
2185
  const failed = () => {
1457
2186
  if (!ended) {
1458
- abandon();
2187
+ abandon("consumer");
1459
2188
  resolve();
1460
2189
  }
1461
2190
  };
1462
2191
  writer.closed && writer.closed.catch(failed);
1463
- writable = {
1464
- end() {
1465
- pendingWrites.then(() => {
1466
- ended = true;
1467
- writer.releaseLock();
1468
- w.close().catch(() => {});
1469
- resolve();
1470
- });
1471
- }
1472
- };
1473
- buffer = {
1474
- write(payload) {
1475
- pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
1476
- }
1477
- };
2192
+ buffer = writable = coalesceWrites(payload => {
2193
+ pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
2194
+ }, () => {
2195
+ pendingWrites.then(() => {
2196
+ ended = true;
2197
+ writer.releaseLock();
2198
+ w.close().catch(() => {});
2199
+ resolve();
2200
+ });
2201
+ });
1478
2202
  buffer.write(tmp);
2203
+ buffer.flush();
1479
2204
  firstFlushed = true;
1480
2205
  if (completed) {
1481
2206
  dispose();
1482
2207
  writable.end();
1483
2208
  } else flushEnd();
1484
- });
2209
+ }, awaited);
1485
2210
  });
1486
2211
  }
1487
2212
  flush();
@@ -1489,8 +2214,14 @@ function renderToStream(code, options = {}) {
1489
2214
  };
1490
2215
  return {
1491
2216
  then(onFulfilled, onRejected) {
2217
+ const freezeHead = () => {
2218
+ if (requestEvent && requestEvent.response) commitResponseStub(requestEvent.response, {
2219
+ event: requestEvent
2220
+ });
2221
+ };
1492
2222
  const p = new Promise(resolve => {
1493
2223
  function complete() {
2224
+ freezeHead();
1494
2225
  dispose();
1495
2226
  resolve(tmp);
1496
2227
  }
@@ -1501,17 +2232,19 @@ function renderToStream(code, options = {}) {
1501
2232
  complete();
1502
2233
  };
1503
2234
  } else onCompleteAll = complete;
2235
+ onFailure(() => resolve(tmp));
1504
2236
  function flush() {
1505
- allSettled(blockingPromises).then(() => {
2237
+ allSettled(blockingPromises).then(awaited => {
1506
2238
  scheduleFlush(() => {
2239
+ if (dead) return;
1507
2240
  try {
1508
- if (!resolveRootHoles() || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
2241
+ if (blockingPromises.size !== lastBlockingSize || !resolveRootHoles() || blockingPromises.size !== lastBlockingSize || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
1509
2242
  } catch (err) {
1510
- failRender(err);
1511
- return resolve(tmp);
2243
+ failRootRender(err);
2244
+ return;
1512
2245
  }
1513
2246
  queue(flushEnd);
1514
- });
2247
+ }, awaited);
1515
2248
  });
1516
2249
  }
1517
2250
  flush();
@@ -1520,28 +2253,32 @@ function renderToStream(code, options = {}) {
1520
2253
  },
1521
2254
  pipe(w) {
1522
2255
  claimConsumer("pipe");
2256
+ onFailure(sink => {
2257
+ try {
2258
+ sink ? sink.end() : w.end();
2259
+ } catch (_) {}
2260
+ });
1523
2261
  function flush() {
1524
- allSettled(blockingPromises).then(() => {
2262
+ allSettled(blockingPromises).then(awaited => {
1525
2263
  scheduleFlush(() => {
1526
2264
  if (dead) return;
1527
2265
  try {
1528
2266
  doShell();
1529
2267
  } catch (err) {
1530
- failRender(err);
1531
- try {
1532
- w.end();
1533
- } catch (_) {}
2268
+ failRootRender(err);
1534
2269
  return;
1535
2270
  }
1536
2271
  if (!shellCompleted) return flush();
1537
- buffer = writable = guardSink(w);
2272
+ const sink = guardSink(w);
2273
+ buffer = writable = coalesceWrites(sink.write, sink.end);
1538
2274
  buffer.write(tmp);
2275
+ buffer.flush();
1539
2276
  firstFlushed = true;
1540
2277
  if (completed) {
1541
2278
  dispose();
1542
2279
  writable.end();
1543
2280
  } else flushEnd();
1544
- });
2281
+ }, awaited);
1545
2282
  });
1546
2283
  }
1547
2284
  flush();
@@ -1562,9 +2299,7 @@ function renderToStream(code, options = {}) {
1562
2299
  };
1563
2300
  }
1564
2301
  function HydrationScript(props) {
1565
- const {
1566
- nonce
1567
- } = sharedConfig.context;
2302
+ const nonce = scriptNonce(sharedConfig.context && sharedConfig.context.nonce);
1568
2303
  return ssr(generateHydrationScript({
1569
2304
  nonce,
1570
2305
  ...props
@@ -1657,6 +2392,10 @@ function ssrGroupSlot(fn, idx) {
1657
2392
  }
1658
2393
  };
1659
2394
  }
2395
+ function wireErrorMessage(err) {
2396
+ const wire = ssrSanitizeError(err, null);
2397
+ return String(wire && wire.message || wire);
2398
+ }
1660
2399
  const holePositionCache = new WeakMap();
1661
2400
  function holeContentPositions(t) {
1662
2401
  let cached = holePositionCache.get(t);
@@ -1721,6 +2460,15 @@ function createLiveHoles(sink, scoped) {
1721
2460
  const stamp = typeof creationStamp === "function" ? creationStamp : () => 0;
1722
2461
  const inScope = scoped && typeof inServerComponentScope === "function" ? inServerComponentScope : null;
1723
2462
  const stripMarkers = html => html.replace(/<!--lh:\/?\d+-->/g, "");
2463
+ const swept = (owner, ctx, fn) => {
2464
+ const prev = sharedConfig.context;
2465
+ sharedConfig.context = ctx;
2466
+ try {
2467
+ return owner ? runWithOwner(owner, fn) : fn();
2468
+ } finally {
2469
+ sharedConfig.context = prev;
2470
+ }
2471
+ };
1724
2472
  function resolveHoleValue(hole) {
1725
2473
  const result = {
1726
2474
  t: [""],
@@ -1786,6 +2534,7 @@ function createLiveHoles(sink, scoped) {
1786
2534
  const recordsBefore = engine.recordStamp;
1787
2535
  const ownersBefore = stamp();
1788
2536
  const owner = getOwner();
2537
+ const holeCtx = sharedConfig.context;
1789
2538
  const b = {
1790
2539
  key: null,
1791
2540
  children: [],
@@ -1799,11 +2548,11 @@ function createLiveHoles(sink, scoped) {
1799
2548
  const sweepOwnersBefore = stamp();
1800
2549
  let res;
1801
2550
  try {
1802
- res = owner ? runWithOwner(owner, () => resolveHoleValue(hole)) : resolveHoleValue(hole);
2551
+ res = swept(owner, holeCtx, () => resolveHoleValue(hole));
1803
2552
  } catch (err) {
1804
2553
  b.closed = true;
1805
2554
  sink.closeBinding(b.key);
1806
- sink.error(b.key, String(err && err.message || err));
2555
+ sink.error(b.key, wireErrorMessage(err));
1807
2556
  return;
1808
2557
  } finally {
1809
2558
  engine.sweeping = prevSweeping;
@@ -1907,6 +2656,7 @@ function createLiveHoles(sink, scoped) {
1907
2656
  },
1908
2657
  attr(cap) {
1909
2658
  const owner = getOwner();
2659
+ const holeCtx = sharedConfig.context;
1910
2660
  const b = {
1911
2661
  key: "lha:" + cap.id,
1912
2662
  children: [],
@@ -1942,12 +2692,12 @@ function createLiveHoles(sink, scoped) {
1942
2692
  if (vt === "string" || vt === "number") html += v;
1943
2693
  }
1944
2694
  };
1945
- owner ? runWithOwner(owner, run) : run();
2695
+ swept(owner, holeCtx, run);
1946
2696
  } catch (err) {
1947
2697
  if (ssrHandleError(err, true)) return;
1948
2698
  b.closed = true;
1949
2699
  sink.closeBinding(b.key);
1950
- sink.error("lha:" + cap.id, String(err && err.message || err));
2700
+ sink.error("lha:" + cap.id, wireErrorMessage(err));
1951
2701
  return;
1952
2702
  } finally {
1953
2703
  engine.sweeping = prevSweeping;
@@ -1965,6 +2715,7 @@ function createLiveHoles(sink, scoped) {
1965
2715
  sink.attr(String(cap.id), html, removed);
1966
2716
  }
1967
2717
  };
2718
+ if (sink.attrBaseline) sink.attrBaseline(b.key, cap.base);
1968
2719
  sink.openBinding(b.key, b);
1969
2720
  }
1970
2721
  };
@@ -2203,6 +2954,7 @@ function ssr(t) {
2203
2954
  return result;
2204
2955
  }
2205
2956
  function ssrClassName(value) {
2957
+ if (typeof value === "number") return "" + value;
2206
2958
  if (!value) return "";
2207
2959
  if (typeof value === "string") return escape(value, true);
2208
2960
  value = classListToObject(value);
@@ -2238,38 +2990,103 @@ function ssrStyle(value) {
2238
2990
  function ssrStyleProperty(name, value) {
2239
2991
  return value != null ? name + value : "";
2240
2992
  }
2241
- function ssrElement(tag, props, children, needsId) {
2993
+ function ssrElement(tag, props, children, needsId, skip, attrs) {
2242
2994
  const hk = needsId ? ssrHydrationKey() : "";
2243
- if (props == null) props = {};else if (typeof props === "function") props = props();
2244
- const skipChildren = VOID_ELEMENTS.test(tag);
2245
- const keys = Object.keys(props);
2246
- let result = `<${tag}${hk} `;
2247
- for (let i = 0; i < keys.length; i++) {
2248
- const prop = keys[i];
2249
- if (ChildProperties.has(prop)) {
2250
- if (children === undefined && !skipChildren) children = tag === "script" || tag === "style" || prop === "innerHTML" ? props[prop] : escape(props[prop]);
2251
- continue;
2995
+ if (typeof props === "function") props = props();
2996
+ let sources = null;
2997
+ let proxy = false;
2998
+ let viewKeys = null;
2999
+ let owners = null;
3000
+ if (Array.isArray(props)) {
3001
+ let i = 0;
3002
+ for (; i < props.length; i++) {
3003
+ const s = props[i];
3004
+ if (s == null || typeof s === "function" || $PROXY in s) break;
2252
3005
  }
2253
- const value = props[prop];
2254
- if (prop === "style") {
2255
- result += `style="${ssrStyle(value)}"`;
2256
- } else if (prop === "class") {
2257
- result += `class="${ssrClassName(value)}"`;
2258
- } else if (value == undefined || prop === "ref" || prop.slice(0, 2) === "on" || prop.slice(0, 5) === "prop:") {
2259
- continue;
2260
- } else if (typeof value === "boolean") {
2261
- if (!value) continue;
2262
- result += escape(prop);
2263
- } else {
2264
- result += value === "" ? escape(prop) : `${escape(prop)}="${escape(value, true)}"`;
3006
+ if (i === props.length) sources = props;else {
3007
+ viewKeys = [];
3008
+ owners = [];
3009
+ for (let i = 0; i < props.length; i++) {
3010
+ let s = props[i];
3011
+ if (typeof s === "function") s = s();
3012
+ if (s != null) sourceOwners(s, viewKeys, owners);
3013
+ }
3014
+ }
3015
+ } else if (props == null) {
3016
+ props = {};
3017
+ } else if ($PROXY in props) {
3018
+ if (viewOf(props) !== undefined) {
3019
+ viewKeys = [];
3020
+ owners = [];
3021
+ sourceOwners(props, viewKeys, owners);
3022
+ } else proxy = true;
3023
+ }
3024
+ const info = tagInfo(tag);
3025
+ const skipChildren = info.isVoid;
3026
+ let result = info.open + hk;
3027
+ const last = sources === null ? 0 : sources.length - 1;
3028
+ let keysOf = null;
3029
+ if (sources !== null) {
3030
+ keysOf = new Array(last + 1);
3031
+ for (let s = 0; s <= last; s++) keysOf[s] = Object.keys(sources[s]);
3032
+ }
3033
+ for (let s = 0; s <= last; s++) {
3034
+ const keys = owners !== null ? viewKeys : keysOf !== null ? keysOf[s] : proxy ? Reflect.ownKeys(props) : Object.keys(props);
3035
+ if (sources !== null) props = sources[s];
3036
+ nextKey: for (let i = 0; i < keys.length; i++) {
3037
+ const prop = keys[i];
3038
+ if (typeof prop !== "string" || skip !== undefined && skip(prop)) continue;
3039
+ if (owners !== null) props = owners[i];
3040
+ for (let j = s + 1; j <= last; j++) {
3041
+ if (keysOf[j].includes(prop)) continue nextKey;
3042
+ }
3043
+ if (info.textarea && (prop === "value" || prop === "defaultValue")) {
3044
+ const value = props[prop];
3045
+ if (value !== null) children = escape(value);
3046
+ continue;
3047
+ }
3048
+ if (ChildProperties.has(prop)) {
3049
+ if (children === undefined && !skipChildren) children = info.raw || prop === "innerHTML" ? props[prop] : escape(props[prop]);
3050
+ continue;
3051
+ }
3052
+ const value = props[prop];
3053
+ if (value == undefined || prop === "ref" || prop.startsWith("on") || prop.startsWith("prop:")) {
3054
+ continue;
3055
+ } else if (prop === "style") {
3056
+ result += ` style="${ssrStyle(value)}"`;
3057
+ } else if (prop === "class") {
3058
+ result += ` class="${ssrClassName(value)}"`;
3059
+ } else if (typeof value === "boolean") {
3060
+ if (!value) continue;
3061
+ result += ` ${attrName(prop)}`;
3062
+ } else {
3063
+ result += value === "" ? ` ${attrName(prop)}` : ` ${attrName(prop)}="${escape(value, true)}"`;
3064
+ }
2265
3065
  }
2266
- if (i !== keys.length - 1) result += " ";
2267
3066
  }
3067
+ if (attrs !== undefined) result += typeof attrs === "function" ? attrs() : attrs;
2268
3068
  if (skipChildren) return {
2269
- t: result + "/>"
3069
+ t: result + " />"
2270
3070
  };
2271
3071
  if (typeof children === "function") children = children();
2272
- return ssr([result + ">", `</${tag}>`], resolveSSRNode(children, undefined, true));
3072
+ const ct = typeof children;
3073
+ if (ct === "string" || ct === "number") return {
3074
+ t: result + ">" + children + info.close
3075
+ };
3076
+ if (children == null || ct === "boolean") return {
3077
+ t: result + ">" + info.close
3078
+ };
3079
+ if (ct === "object" && !children.h && typeof children.t === "string") return {
3080
+ t: result + ">" + children.t + info.close
3081
+ };
3082
+ return ssr([result + ">", info.close], resolveSSRNode(children, undefined, true));
3083
+ }
3084
+ function ssrElementAttribute(key, value) {
3085
+ if (value == undefined) return "";
3086
+ if (key === "style") return ` style="${ssrStyle(value)}"`;
3087
+ if (key === "class") return ` class="${ssrClassName(value)}"`;
3088
+ if (typeof value === "boolean") return value ? ` ${key}` : "";
3089
+ return value === "" ? ` ${key}` : ` ${key}="${escape(value, true)}"`;
2273
3090
  }
2274
3091
  function ssrAttribute(key, value) {
2275
3092
  return value == null || value === false ? "" : value === true ? ` ${key}` : ` ${key}="${value}"`;
@@ -2278,10 +3095,36 @@ function ssrHydrationKey() {
2278
3095
  const hk = getHydrationKey();
2279
3096
  return hk ? ` _hk=${hk}` : "";
2280
3097
  }
3098
+ const CLAIM_PROP = /*#__PURE__*/Symbol.for("solid.claim-prop");
3099
+ const CLAIMS_STREAM = 1;
3100
+ const CLAIMS_DOCUMENT = 2;
3101
+ const CLAIM_UNSAFE = /[^A-Za-z0-9_.!~*'()-]/g;
3102
+ function encodeClaimKey(key) {
3103
+ return String(key).replace(CLAIM_UNSAFE, c => encodeURIComponent(c));
3104
+ }
3105
+ function ssrClaim(map) {
3106
+ const mode = sharedConfig.context && sharedConfig.context.claims;
3107
+ if (!mode || mode === CLAIMS_DOCUMENT && !(typeof inServerComponentScope === "function" && inServerComponentScope())) {
3108
+ return "";
3109
+ }
3110
+ let out = "";
3111
+ for (const pos in map) {
3112
+ const value = map[pos];
3113
+ const list = Array.isArray(value) ? value : [value];
3114
+ for (const fn of list) {
3115
+ const prop = typeof fn === "function" && fn[CLAIM_PROP] || undefined;
3116
+ if (prop === undefined) {
3117
+ continue;
3118
+ }
3119
+ out += `${out ? "," : ""}${pos}=${encodeClaimKey(prop)}`;
3120
+ }
3121
+ }
3122
+ return out ? ` _bnd="${out}"` : "";
3123
+ }
2281
3124
  function decodeSSREntities(s) {
2282
3125
  return s.indexOf("&") < 0 ? s : s.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&amp;/g, "&");
2283
3126
  }
2284
- const SELECT_VALUE_ATTR = /\svalue="([^"]*)"/;
3127
+ const SELECT_VALUE_ATTR = /\svalue(?:="([^"]*)")?(?=[\s>]|$)/;
2285
3128
  function tagEnd(html, i) {
2286
3129
  for (let j = i + 1; j < html.length; j++) {
2287
3130
  const c = html.charCodeAt(j);
@@ -2310,22 +3153,49 @@ function tagIs(html, i, name) {
2310
3153
  const c = html.charCodeAt(i + 1 + name.length);
2311
3154
  return c === 32 || c === 62 || c === 9 || c === 10 || c === 13;
2312
3155
  }
3156
+ let selectValuesActive = false;
3157
+ function ssrSelectValues() {
3158
+ selectValuesActive = true;
3159
+ }
2313
3160
  function resolveSSRSelectValues(html) {
2314
- if (html.indexOf("<select") < 0) return html;
3161
+ if (!selectValuesActive) return html;
3162
+ let cand = html.indexOf("<select");
3163
+ if (cand < 0) return html;
2315
3164
  let out = "";
2316
3165
  let idx = 0;
2317
- let sel = null;
2318
- let i = html.indexOf("<");
2319
- while (i >= 0) {
2320
- let e;
2321
- if (html.charCodeAt(i + 1) === 33) {
2322
- e = html.charCodeAt(i + 2) === 45 ? html.indexOf("-->", i) : html.indexOf(">", i);
2323
- if (e < 0) break;
2324
- if (html.charCodeAt(i + 2) === 45) e += 2;
2325
- } else {
2326
- e = tagEnd(html, i);
2327
- if (e < 0) break;
2328
- if (sel) {
3166
+ while (cand >= 0) {
3167
+ if (!tagIs(html, cand, "select")) {
3168
+ cand = html.indexOf("<select", cand + 7);
3169
+ continue;
3170
+ }
3171
+ const e0 = tagEnd(html, cand);
3172
+ if (e0 < 0) break;
3173
+ const open = html.slice(cand, e0 + 1);
3174
+ const m = SELECT_VALUE_ATTR.exec(open);
3175
+ if (!m) {
3176
+ cand = html.indexOf("<select", e0 + 1);
3177
+ continue;
3178
+ }
3179
+ const bound = decodeSSREntities(m[1] ?? "");
3180
+ const sel = {
3181
+ values: /\smultiple(?=[\s>=])/.test(open) ? bound.split(",") : [bound],
3182
+ strip: cand + m.index,
3183
+ stripEnd: cand + m.index + m[0].length,
3184
+ body: e0 + 1,
3185
+ marks: [],
3186
+ defaulted: false
3187
+ };
3188
+ let committed = false;
3189
+ let i = html.indexOf("<", e0 + 1);
3190
+ while (i >= 0) {
3191
+ let e;
3192
+ if (html.charCodeAt(i + 1) === 33) {
3193
+ e = html.charCodeAt(i + 2) === 45 ? html.indexOf("-->", i) : html.indexOf(">", i);
3194
+ if (e < 0) break;
3195
+ if (html.charCodeAt(i + 2) === 45) e += 2;
3196
+ } else {
3197
+ e = tagEnd(html, i);
3198
+ if (e < 0) break;
2329
3199
  if (html.startsWith("</select>", i)) {
2330
3200
  out += html.slice(idx, sel.strip) + html.slice(sel.stripEnd, sel.body);
2331
3201
  let seg = sel.body;
@@ -2337,32 +3207,23 @@ function resolveSSRSelectValues(html) {
2337
3207
  }
2338
3208
  out += html.slice(seg, i);
2339
3209
  idx = i;
2340
- sel = null;
3210
+ committed = true;
3211
+ break;
2341
3212
  } else if (tagIs(html, i, "option")) {
2342
3213
  const attrs = html.slice(i + 7, e);
2343
3214
  if (/\sselected(?=[\s=]|$)/.test(attrs)) sel.defaulted = true;else {
2344
3215
  const vm = SELECT_VALUE_ATTR.exec(attrs);
2345
- const value = vm ? decodeSSREntities(vm[1]) : decodeSSREntities(optionText(html, e + 1)).replace(/\s+/g, " ").trim();
3216
+ const value = vm ? decodeSSREntities(vm[1] ?? "") : decodeSSREntities(optionText(html, e + 1)).replace(/\s+/g, " ").trim();
2346
3217
  if (sel.values.includes(value)) sel.marks.push(e);
2347
3218
  }
2348
3219
  }
2349
- } else if (tagIs(html, i, "select")) {
2350
- const m = SELECT_VALUE_ATTR.exec(html.slice(i, e + 1));
2351
- if (m) {
2352
- const bound = decodeSSREntities(m[1]);
2353
- sel = {
2354
- values: /\smultiple(?=[\s>=])/.test(html.slice(i, e + 1)) ? bound.split(",") : [bound],
2355
- strip: i + m.index,
2356
- stripEnd: i + m.index + m[0].length,
2357
- body: e + 1,
2358
- marks: [],
2359
- defaulted: false
2360
- };
2361
- }
2362
3220
  }
3221
+ i = html.indexOf("<", e + 1);
2363
3222
  }
2364
- i = html.indexOf("<", e + 1);
3223
+ if (!committed) break;
3224
+ cand = html.indexOf("<select", idx);
2365
3225
  }
3226
+ if (idx === 0) return html;
2366
3227
  return out + html.slice(idx);
2367
3228
  }
2368
3229
  function escape(s, attr) {
@@ -2371,10 +3232,13 @@ function escape(s, attr) {
2371
3232
  if (!attr && Array.isArray(s)) {
2372
3233
  const joined = tryJoinPlainSSRArray(s);
2373
3234
  if (joined !== undefined) return joined;
3235
+ const src = s;
2374
3236
  s = s.slice();
2375
3237
  for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
3238
+ if (src.$slot) s.$slot = true;
2376
3239
  return s;
2377
3240
  }
3241
+ if (!attr && t === "function") return escapeLate(s);
2378
3242
  if (attr) {
2379
3243
  if (s == null || t === "boolean" || t === "number") return s;
2380
3244
  return escape(String(s), attr);
@@ -2385,23 +3249,30 @@ function escape(s, attr) {
2385
3249
  if (i < 0) return s;
2386
3250
  return escapeSlow(s, attr, i);
2387
3251
  }
3252
+ function escapeLate(fn) {
3253
+ if (fn.$esc) return fn;
3254
+ const w = () => escape(fn());
3255
+ w.$esc = true;
3256
+ if (fn.$lhSkip) w.$lhSkip = true;
3257
+ if (fn.$lhSuppress) w.$lhSuppress = true;
3258
+ if (fn.$lhBinding) w.$lhBinding = fn.$lhBinding;
3259
+ return w;
3260
+ }
2388
3261
  const ESCAPE_CONTENT = /[&<]/;
2389
- const ESCAPE_ATTR = /[&"]/;
3262
+ const ESCAPE_ATTR = /[&"<]/;
2390
3263
  function escapeSlow(s, attr, start) {
2391
- const delim = attr ? '"' : "<";
2392
- const delimCode = attr ? 34 : 60;
2393
- const escDelim = attr ? "&quot;" : "&lt;";
3264
+ if (attr) return escapeAttrSlow(s, start);
2394
3265
  const c0 = s.charCodeAt(start);
2395
- let iDelim = c0 === delimCode ? start : s.indexOf(delim, start);
3266
+ let iDelim = c0 === 60 ? start : s.indexOf("<", start);
2396
3267
  let iAmp = c0 === 38 ? start : s.indexOf("&", start);
2397
3268
  let left = 0,
2398
3269
  out = "";
2399
3270
  while (iDelim >= 0 && iAmp >= 0) {
2400
3271
  if (iDelim < iAmp) {
2401
3272
  if (left < iDelim) out += s.substring(left, iDelim);
2402
- out += escDelim;
3273
+ out += "&lt;";
2403
3274
  left = iDelim + 1;
2404
- iDelim = s.indexOf(delim, left);
3275
+ iDelim = s.indexOf("<", left);
2405
3276
  } else {
2406
3277
  if (left < iAmp) out += s.substring(left, iAmp);
2407
3278
  out += "&amp;";
@@ -2412,9 +3283,9 @@ function escapeSlow(s, attr, start) {
2412
3283
  if (iDelim >= 0) {
2413
3284
  do {
2414
3285
  if (left < iDelim) out += s.substring(left, iDelim);
2415
- out += escDelim;
3286
+ out += "&lt;";
2416
3287
  left = iDelim + 1;
2417
- iDelim = s.indexOf(delim, left);
3288
+ iDelim = s.indexOf("<", left);
2418
3289
  } while (iDelim >= 0);
2419
3290
  } else while (iAmp >= 0) {
2420
3291
  if (left < iAmp) out += s.substring(left, iAmp);
@@ -2424,6 +3295,36 @@ function escapeSlow(s, attr, start) {
2424
3295
  }
2425
3296
  return left < s.length ? out + s.substring(left) : out;
2426
3297
  }
3298
+ function escapeAttrSlow(s, start) {
3299
+ const c0 = s.charCodeAt(start);
3300
+ let iQuot = c0 === 34 ? start : s.indexOf('"', start);
3301
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
3302
+ let iLt = c0 === 60 ? start : s.indexOf("<", start);
3303
+ let left = 0,
3304
+ out = "";
3305
+ for (;;) {
3306
+ let i = -1,
3307
+ ent;
3308
+ if (iQuot >= 0) {
3309
+ i = iQuot;
3310
+ ent = "&quot;";
3311
+ }
3312
+ if (iAmp >= 0 && (i < 0 || iAmp < i)) {
3313
+ i = iAmp;
3314
+ ent = "&amp;";
3315
+ }
3316
+ if (iLt >= 0 && (i < 0 || iLt < i)) {
3317
+ i = iLt;
3318
+ ent = "&lt;";
3319
+ }
3320
+ if (i < 0) break;
3321
+ if (left < i) out += s.substring(left, i);
3322
+ out += ent;
3323
+ left = i + 1;
3324
+ if (i === iQuot) iQuot = s.indexOf('"', left);else if (i === iAmp) iAmp = s.indexOf("&", left);else iLt = s.indexOf("<", left);
3325
+ }
3326
+ return left < s.length ? out + s.substring(left) : out;
3327
+ }
2427
3328
  function tryJoinPlainSSRArray(nodes) {
2428
3329
  if (nodes.length === 0) return undefined;
2429
3330
  let out = "";
@@ -2447,23 +3348,25 @@ function generateHydrationScript({
2447
3348
  eventNames = ["click", "input"],
2448
3349
  nonce
2449
3350
  } = {}) {
2450
- return `<script${nonce ? ` nonce="${nonce}"` : ""}>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-->`;
3351
+ 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-->`;
2451
3352
  }
2452
3353
  function queue(fn) {
2453
3354
  return Promise.resolve().then(fn);
2454
3355
  }
3356
+ const deferFlush = typeof setImmediate === "function" ? setImmediate : fn => setTimeout(fn, 0);
2455
3357
  function allSettled(promises) {
2456
3358
  let size = promises.size;
2457
3359
  return Promise.allSettled(promises).then(() => {
2458
3360
  if (promises.size !== size) return allSettled(promises);
2459
- return;
3361
+ return size;
2460
3362
  });
2461
3363
  }
2462
- function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, headTags, onHead) {
2463
- const scriptTag = scripts ? `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>` : "";
2464
- const headTagsHtml = headTags ? headTags.html : "";
3364
+ function assembleDocument(html, emittedAssets, preloadLinks, inlineStyles, scripts, nonce, headTags, onHead) {
3365
+ const scriptTag = scripts ? `<script${nonceAttr(nonce, "script")}>${scripts}</script>` : "";
3366
+ const title = headTags ? headTags.title : null;
3367
+ let headTagsHtml = headTags ? headTags.html : "";
2465
3368
  const headPrelude = headTags ? headTags.prelude : "";
2466
- if (!onHead && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !(inlineStyles && inlineStyles.size)) {
3369
+ if (!onHead && title == null && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !preloadLinks && !(inlineStyles && inlineStyles.size)) {
2467
3370
  if (!scriptTag) return html;
2468
3371
  const xs = html.indexOf("<!--xs-->");
2469
3372
  return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
@@ -2475,28 +3378,51 @@ function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, hea
2475
3378
  html = html.slice(0, at) + headPrelude + html.slice(at);
2476
3379
  }
2477
3380
  }
2478
- const headIdx = html.indexOf("</head>");
3381
+ let headIdx = html.indexOf("</head>");
2479
3382
  if (headIdx === -1) {
2480
3383
  if (onHead) {
2481
- onHead(headPrelude + headTagsHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce));
3384
+ let titleHtml = "";
3385
+ if (title != null) {
3386
+ 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>`;
3387
+ }
3388
+ onHead(headPrelude + headTagsHtml + titleHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce));
2482
3389
  }
2483
3390
  if (!scriptTag) return html;
2484
3391
  const xs = html.indexOf("<!--xs-->");
2485
3392
  return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
2486
3393
  }
2487
- const head = headTagsHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce);
3394
+ if (title != null) {
3395
+ const winner = escape(title);
3396
+ const open = html.match(/<head(?:\s[^>]*)?>/);
3397
+ const from = open ? open.index + open[0].length : 0;
3398
+ const m = /<title(\s[^>]*)?>([\s\S]*?)<\/title>/.exec(html.slice(from, headIdx));
3399
+ if (m) {
3400
+ const at = from + m.index;
3401
+ const stash = m[2].replace(/"/g, "&quot;");
3402
+ html = html.slice(0, at) + `<title${m[1] || ""} data-dh="title" data-dhf="${stash}">${winner}</title>` + html.slice(at + m[0].length);
3403
+ headIdx = html.indexOf("</head>");
3404
+ } else {
3405
+ headTagsHtml = `<title data-dh="title">${winner}</title>` + headTagsHtml;
3406
+ }
3407
+ }
3408
+ const head = headTagsHtml + renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce);
2488
3409
  if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
2489
3410
  const xsIdx = html.indexOf("<!--xs-->");
2490
3411
  if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
2491
3412
  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);
2492
3413
  }
2493
- function renderHeadAssets(emittedAssets, inlineStyles, nonce) {
3414
+ function renderHeadAssets(emittedAssets, preloadLinks, inlineStyles, nonce) {
2494
3415
  let head = "";
3416
+ const styleAttr = nonceAttr(nonce, "style");
3417
+ const scriptAttr = nonceAttr(nonce, "script");
2495
3418
  if (emittedAssets && emittedAssets.size) {
2496
3419
  for (const url of emittedAssets) {
2497
- head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}">` : `<link rel="modulepreload" href="${url}">`;
3420
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}"${styleAttr}>` : `<link rel="modulepreload" href="${url}"${scriptAttr}>`;
2498
3421
  }
2499
3422
  }
3423
+ if (preloadLinks) {
3424
+ for (const entry of preloadLinks) head += `<link${entry.attrHtml}>`;
3425
+ }
2500
3426
  if (inlineStyles && inlineStyles.size) {
2501
3427
  for (const entry of inlineStyles.values()) {
2502
3428
  if (entry.emitted) continue;
@@ -2556,12 +3482,15 @@ function escapeStyleContent(content) {
2556
3482
  }
2557
3483
  function renderInlineStyle(entry, nonce) {
2558
3484
  let attrs = "";
3485
+ let hasNonce = false;
2559
3486
  if (entry.attrs) {
2560
3487
  for (const name in entry.attrs) {
3488
+ if (name.length === 5 && asciiLowerCase(name) === "nonce") hasNonce = true;
2561
3489
  attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
2562
3490
  }
2563
3491
  }
2564
- return `<style${nonce ? ` nonce="${nonce}"` : ""} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
3492
+ const nonceHtml = hasNonce ? "" : nonceAttr(nonce, "style");
3493
+ return `<style${nonceHtml} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
2565
3494
  }
2566
3495
  function waitForFragments(registry, key) {
2567
3496
  for (const k of [...registry.keys()].reverse()) {
@@ -2588,26 +3517,30 @@ function classListToObject(classList) {
2588
3517
  function flattenClassList(list, result) {
2589
3518
  for (let i = 0, len = list.length; i < len; i++) {
2590
3519
  const item = list[i];
2591
- 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;
3520
+ if (Array.isArray(item)) flattenClassList(item, result);else if (typeof item === "object" && item != null) Object.assign(result, item);
3521
+ else if (typeof item !== "boolean" && (item || item === 0)) result[item] = true;
2592
3522
  }
2593
3523
  }
2594
- function tryResolveString(node) {
3524
+ let ssrTextTail = false;
3525
+ function tryResolveString(node, nested) {
3526
+ if (!nested) ssrTextTail = false;
2595
3527
  const t = typeof node;
2596
- if (t === "string") return node;
2597
- if (t === "number") return "" + node;
3528
+ if (t === "string" || t === "number") {
3529
+ const s = ssrTextTail ? "<!--!$-->" + node : "" + node;
3530
+ ssrTextTail = true;
3531
+ return s;
3532
+ }
2598
3533
  if (node == null || t === "boolean") return "";
2599
3534
  if (t === "object") {
2600
3535
  if (Array.isArray(node)) {
2601
3536
  const joined = tryJoinPlainSSRArray(node);
2602
- if (joined !== undefined) return joined;
3537
+ if (joined !== undefined) {
3538
+ ssrTextTail = false;
3539
+ return joined;
3540
+ }
2603
3541
  let s = "";
2604
- let prevNonObj = false;
2605
3542
  for (let i = 0, len = node.length; i < len; i++) {
2606
- const item = node[i];
2607
- const itemNonObj = item !== null && typeof item !== "object";
2608
- if (prevNonObj && itemNonObj) s += "<!--!$-->";
2609
- prevNonObj = itemNonObj;
2610
- const r = tryResolveString(item);
3543
+ const r = tryResolveString(node[i], true);
2611
3544
  if (typeof r !== "string") return {
2612
3545
  bail: node
2613
3546
  };
@@ -2621,6 +3554,7 @@ function tryResolveString(node) {
2621
3554
  if (node.t === undefined) {
2622
3555
  return "";
2623
3556
  }
3557
+ ssrTextTail = false;
2624
3558
  return Array.isArray(node.t) ? node.t[0] : node.t;
2625
3559
  }
2626
3560
  if (t === "function") {
@@ -2628,9 +3562,11 @@ function tryResolveString(node) {
2628
3562
  try {
2629
3563
  v = node();
2630
3564
  } catch (err) {
2631
- return buildAsyncWrap(err, node) || "";
3565
+ const wrap = buildAsyncWrap(err, node);
3566
+ if (wrap) ssrTextTail = true;
3567
+ return wrap || "";
2632
3568
  }
2633
- return tryResolveString(v);
3569
+ return tryResolveString(v, true);
2634
3570
  }
2635
3571
  return "";
2636
3572
  }
@@ -2638,21 +3574,19 @@ function resolveSSRNode(node, result = {
2638
3574
  t: [""],
2639
3575
  h: [],
2640
3576
  p: []
2641
- }, top) {
3577
+ }, top, nested) {
3578
+ if (!nested) ssrTextTail = false;
2642
3579
  const t = typeof node;
2643
3580
  if (t === "string" || t === "number") {
2644
- result.t[result.t.length - 1] += node;
3581
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + node : node;
3582
+ ssrTextTail = true;
2645
3583
  } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
2646
3584
  const slotLive = node.$slot && sharedConfig.context && sharedConfig.context.liveHoles;
2647
3585
  if (slotLive) slotLive.suppressed++;
2648
3586
  try {
2649
- let prevNonObj = false;
2650
3587
  for (let i = 0, len = node.length; i < len; i++) {
2651
- const item = node[i];
2652
- const itemNonObj = item !== null && typeof item !== "object";
2653
- if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
2654
- prevNonObj = itemNonObj;
2655
- resolveSSRNode(item, result);
3588
+ if (top) ssrTextTail = false;
3589
+ resolveSSRNode(node[i], result, false, true);
2656
3590
  }
2657
3591
  } finally {
2658
3592
  if (slotLive) slotLive.suppressed--;
@@ -2665,23 +3599,30 @@ function resolveSSRNode(node, result = {
2665
3599
  result.h.push(...node.h);
2666
3600
  result.p.push(...node.p);
2667
3601
  }
3602
+ ssrTextTail = false;
2668
3603
  } else if (node.t !== undefined) {
2669
3604
  result.t[result.t.length - 1] += node.t;
3605
+ ssrTextTail = false;
2670
3606
  } else ;
2671
3607
  } else if (t === "function") {
2672
3608
  const live = sharedConfig.context && sharedConfig.context.liveHoles;
2673
3609
  let liveNode = null;
2674
3610
  if (live && (liveNode = live.content(node)) !== null) {
2675
- if (typeof liveNode === "string") result.t[result.t.length - 1] += liveNode;else resolveSSRNode(liveNode, result);
3611
+ if (typeof liveNode === "string") {
3612
+ result.t[result.t.length - 1] += ssrTextTail ? "<!--!$-->" + liveNode : liveNode;
3613
+ ssrTextTail = true;
3614
+ } else resolveSSRNode(liveNode, result, false, true);
2676
3615
  } else {
2677
3616
  try {
2678
- resolveSSRNode(node(), result);
3617
+ resolveSSRNode(node(), result, false, true);
2679
3618
  } catch (err) {
2680
3619
  const wrap = buildAsyncWrap(err, node);
2681
3620
  if (wrap) {
3621
+ if (ssrTextTail) result.t[result.t.length - 1] += "<!--!$-->";
2682
3622
  result.h.push(wrap.fn);
2683
3623
  result.p.push(wrap.p);
2684
3624
  result.t.push("");
3625
+ ssrTextTail = true;
2685
3626
  }
2686
3627
  }
2687
3628
  }
@@ -2694,9 +3635,49 @@ function resolveSSRSync(node) {
2694
3635
  throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
2695
3636
  }
2696
3637
  const RequestContext = Symbol.for("solid.RequestContext");
3638
+ const ServerErrors = Symbol.for("solid-js/server/errors");
3639
+ function serializerErrorHook(hook) {
3640
+ return hook === undefined ? undefined : err => {
3641
+ reportServerError(err, {
3642
+ kind: "render",
3643
+ handling: "serialize"
3644
+ }, null);
3645
+ };
3646
+ }
3647
+ function ambientServerErrorHook() {
3648
+ const slot = globalThis[ServerErrors];
3649
+ return slot === undefined ? undefined : slot.hook;
3650
+ }
3651
+ function configureServerErrors(config) {
3652
+ const g = globalThis;
3653
+ if (config && config.onError !== undefined && typeof config.onError !== "function") {
3654
+ throw new TypeError(`Invalid onError: expected a function, received ${typeof config.onError}.`);
3655
+ }
3656
+ (g[ServerErrors] ||= {}).hook = config ? config.onError : undefined;
3657
+ }
2697
3658
  function getRequestEvent() {
2698
3659
  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;
2699
3660
  }
3661
+ function peekRequestEvent() {
3662
+ const store = globalThis[RequestContext];
3663
+ return store ? store.getStore() : undefined;
3664
+ }
3665
+ function timeDocument(context, trace, mode, requestEvent) {
3666
+ return undefined;
3667
+ }
3668
+ function getTraceContext() {
3669
+ const event = peekRequestEvent();
3670
+ if (event) return traceForEvent(event).context;
3671
+ const ctx = sharedConfig.context;
3672
+ return ctx && ctx.trace ? ctx.trace.context : undefined;
3673
+ }
3674
+ function traceForStub(stub, event) {
3675
+ if (!event) {
3676
+ event = peekRequestEvent();
3677
+ if (!event || event.response !== stub) return undefined;
3678
+ }
3679
+ return traceForEvent(event);
3680
+ }
2700
3681
  function createResponseStub() {
2701
3682
  return {
2702
3683
  status: undefined,
@@ -2714,15 +3695,20 @@ function createRequestEvent(request, init) {
2714
3695
  };
2715
3696
  }
2716
3697
  function reportLostHeaderWrite(method, name) {
2717
- 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).";
3698
+ 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).";
2718
3699
  console.error(message);
2719
3700
  }
2720
3701
  function commitResponseStub(stub, {
2721
- allowLateLocation = false
3702
+ allowLateLocation = false,
3703
+ event
2722
3704
  } = {}) {
2723
3705
  if (!stub || stub.committed) return stub;
2724
- stub.committed = true;
2725
3706
  const headers = stub.headers;
3707
+ if (headers && typeof headers.append === "function") {
3708
+ const trace = traceForStub(stub, event);
3709
+ if (trace) appendTraceServerTiming(headers, trace);
3710
+ }
3711
+ stub.committed = true;
2726
3712
  if (!headers || typeof headers.set !== "function") return stub;
2727
3713
  for (const method of ["set", "append", "delete"]) {
2728
3714
  const original = headers[method].bind(headers);
@@ -2743,7 +3729,7 @@ function getExpectedRedirectStatus(response) {
2743
3729
  function mergeStubHeaders(target, stub) {
2744
3730
  if (!stub) return target;
2745
3731
  stub.headers.forEach((value, key) => {
2746
- if (key !== "set-cookie") target.set(key, value);
3732
+ if (key === "server-timing") mergeServerTiming(target, value);else if (key !== "set-cookie") target.set(key, value);
2747
3733
  });
2748
3734
  const setCookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
2749
3735
  for (const cookie of setCookies) target.append("set-cookie", cookie);
@@ -2758,7 +3744,8 @@ function copyInitHeaders(init) {
2758
3744
  for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
2759
3745
  return headers;
2760
3746
  }
2761
- const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
3747
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, REDIRECT_HEADER, "Location",
3748
+ ...COMPOSED_BODY_FRAMING].map(header => header.toLowerCase()));
2762
3749
  function fillsStubGap(key, headers, response) {
2763
3750
  if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
2764
3751
  if (response.body === null && (key === "content-type" || key === "content-length")) return false;
@@ -2766,35 +3753,44 @@ function fillsStubGap(key, headers, response) {
2766
3753
  }
2767
3754
  function commitEventResponse(response, event = getRequestEvent()) {
2768
3755
  const stub = event && event.response;
2769
- if (!stub || !stub.headers || stub.committed) return response;
2770
- const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
2771
- commitResponseStub(stub);
2772
- let hasGaps = false;
2773
- stub.headers.forEach((value, key) => {
2774
- if (fillsStubGap(key, response.headers, response)) hasGaps = true;
2775
- });
2776
- if (!cookies.length && !hasGaps) return response;
2777
- try {
2778
- for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
2779
- stub.headers.forEach((value, key) => {
2780
- if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
2781
- });
2782
- return response;
2783
- } catch {
3756
+ if (!stub || !stub.headers || stub.committed) {
3757
+ if (!event || stub) return response;
3758
+ const trace = traceForEvent(event);
3759
+ if (!hasServerTiming(trace)) return response;
2784
3760
  const headers = copyInitHeaders(response.headers);
2785
- for (const cookie of cookies) headers.append("Set-Cookie", cookie);
2786
- stub.headers.forEach((value, key) => {
2787
- if (fillsStubGap(key, headers, response)) headers.set(key, value);
2788
- });
3761
+ appendTraceServerTiming(headers, trace);
2789
3762
  return new Response(response.body, {
2790
3763
  status: response.status,
2791
3764
  statusText: response.statusText,
2792
3765
  headers
2793
3766
  });
2794
3767
  }
3768
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
3769
+ commitResponseStub(stub, {
3770
+ event
3771
+ });
3772
+ let hasGaps = false;
3773
+ stub.headers.forEach((value, key) => {
3774
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
3775
+ });
3776
+ const timing = stub.headers.get("server-timing");
3777
+ const mergesTiming = timing !== null && response.headers.has("server-timing");
3778
+ if (!cookies.length && !hasGaps && !mergesTiming) return response;
3779
+ const headers = copyInitHeaders(response.headers);
3780
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
3781
+ stub.headers.forEach((value, key) => {
3782
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
3783
+ });
3784
+ if (mergesTiming) mergeServerTiming(headers, timing);
3785
+ return new Response(response.body, {
3786
+ status: response.status,
3787
+ statusText: response.statusText,
3788
+ headers
3789
+ });
2795
3790
  }
2796
3791
  function deriveHead(stub, responseInit = {}) {
2797
3792
  const headers = mergeStubHeaders(copyInitHeaders(responseInit.headers), stub);
3793
+ for (const header of COMPOSED_BODY_FRAMING) headers.delete(header);
2798
3794
  const status = stub && stub.status || responseInit.status || 200;
2799
3795
  const statusText = stub && stub.statusText || responseInit.statusText || undefined;
2800
3796
  return {
@@ -2803,18 +3799,17 @@ function deriveHead(stub, responseInit = {}) {
2803
3799
  headers
2804
3800
  };
2805
3801
  }
2806
- function escapeAttribute(value) {
2807
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2808
- }
2809
3802
  function createSSRResponse(result, event, options = {}) {
2810
3803
  const stub = event && event.response;
2811
3804
  const {
2812
3805
  responseInit,
2813
- nonce,
2814
3806
  transformChunk
2815
3807
  } = options;
3808
+ const nonce = normalizeNonce(options.nonce);
2816
3809
  if (typeof result === "string") {
2817
- if (stub) commitResponseStub(stub);
3810
+ if (stub) commitResponseStub(stub, {
3811
+ event
3812
+ });
2818
3813
  const head = deriveHead(stub, responseInit);
2819
3814
  if (stub && stub.headers.get("Location")) {
2820
3815
  return new Response(null, {
@@ -2849,7 +3844,8 @@ function createSSRResponse(result, event, options = {}) {
2849
3844
  if (!flushed) {
2850
3845
  flushed = true;
2851
3846
  if (stub) commitResponseStub(stub, {
2852
- allowLateLocation: true
3847
+ allowLateLocation: true,
3848
+ event
2853
3849
  });
2854
3850
  const head = deriveHead(stub, responseInit);
2855
3851
  if (stub && stub.headers.get("Location")) {
@@ -2881,8 +3877,8 @@ function createSSRResponse(result, event, options = {}) {
2881
3877
  end() {
2882
3878
  if (closed || !controller) return;
2883
3879
  const location = stub && stub.headers.get("Location");
2884
- if (location) {
2885
- const attr = nonce ? ` nonce="${escapeAttribute(nonce)}"` : "";
3880
+ if (location && isHttpNavigationTarget(location)) {
3881
+ const attr = nonceAttr(nonce, "script");
2886
3882
  enqueue(`<script${attr}>window.location=${JSON.stringify(location).replace(/</g, "\\u003c")}</script>`);
2887
3883
  }
2888
3884
  closed = true;
@@ -2920,15 +3916,57 @@ function notSup() {
2920
3916
  }
2921
3917
 
2922
3918
  setContainerTraceResolver(getProjectionTrace);
3919
+ setAsyncIterableSharer(shareAsyncIterable);
2923
3920
  const isServer = true;
2924
3921
  const isDev = false;
2925
- function dynamic(source) {
2926
- const cached = createMemo(source, {
2927
- serialize: false
3922
+ function dynamic(source, options) {
3923
+ if (options?.static) {
3924
+ const component = untrack(source);
3925
+ if (typeof component === "function") return props => component(props);
3926
+ if (typeof component === "string") return props => ssrElement(component, props, undefined, true);
3927
+ return () => undefined;
3928
+ }
3929
+ const cached = createMemo(() => {
3930
+ const next = source();
3931
+ if (!next || typeof next.then !== "function") return next;
3932
+ return {
3933
+ [FLIGHT]: next
3934
+ };
2928
3935
  });
3936
+ const deferStream = !!options?.deferStream;
2929
3937
  return props => {
3938
+ const ctx = sharedConfig.context;
3939
+ let gated = !deferStream || !ctx?.async;
3940
+ const value = createMemo(() => {
3941
+ let c;
3942
+ try {
3943
+ c = cached();
3944
+ } catch (err) {
3945
+ if (!gated && err instanceof NotReadyError && !err.source?.$clientHole) {
3946
+ gated = true;
3947
+ ctx.block(Promise.resolve(err.source).then(() => {}, () => {}));
3948
+ }
3949
+ throw err;
3950
+ }
3951
+ if (!c || !c[FLIGHT]) return c;
3952
+ const next = c[FLIGHT];
3953
+ return {
3954
+ then: (onFulfilled, onRejected) => next.then(resolved => {
3955
+ let landed;
3956
+ try {
3957
+ landed = classifyLanding(resolved);
3958
+ } catch (err) {
3959
+ if (onRejected) return onRejected(err);
3960
+ throw err;
3961
+ }
3962
+ return onFulfilled ? onFulfilled(landed) : landed;
3963
+ }, onRejected)
3964
+ };
3965
+ }, {
3966
+ deferStream
3967
+ });
2930
3968
  return createMemo(() => {
2931
- const c = cached();
3969
+ const c = value();
2932
3970
  if (c) {
2933
3971
  if (typeof c === "function") return c(props);
2934
3972
  if (typeof c === "string") {
@@ -2940,6 +3978,13 @@ function dynamic(source) {
2940
3978
  });
2941
3979
  };
2942
3980
  }
3981
+ const FLIGHT = Symbol("solid.dynamic-flight");
3982
+ const SERVER_COMPONENT = Symbol.for("solid.server-component");
3983
+ function classifyLanding(resolved) {
3984
+ if (typeof resolved !== "function" || SERVER_COMPONENT in resolved) return resolved;
3985
+ const message = "[DYNAMIC_ASYNC_COMPONENT] An async dynamic() source resolved to a client component function";
3986
+ throw new Error(message);
3987
+ }
2943
3988
  function Dynamic(props) {
2944
3989
  const Comp = dynamic(() => props.component);
2945
3990
  return createComponent(Comp, omit(props, "component"));
@@ -2960,6 +4005,11 @@ function registerClientOnlyPreload(moduleUrl) {
2960
4005
  const css = assets.css[i];
2961
4006
  if (typeof css === "string") registerAsset("style", css);else registerAsset("inline-style", css);
2962
4007
  }
4008
+ if (assets.preloads) {
4009
+ for (let i = 0; i < assets.preloads.length; i++) {
4010
+ registerAsset("preload", assets.preloads[i]);
4011
+ }
4012
+ }
2963
4013
  for (let i = 0; i < assets.js.length; i++) registerAsset("module", assets.js[i]);
2964
4014
  };
2965
4015
  const assets = resolve(moduleUrl);
@@ -3063,4 +4113,4 @@ function httpHeader(name, value, options) {
3063
4113
  }
3064
4114
  }
3065
4115
 
3066
- export { 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, serializeCookie, notSup as setAttribute, notSup as setAttributeNS, notSup as setProperty, notSup as setStyleProperty, notSup as spread, ssr, ssrAttribute, ssrClassName, ssrElement, ssrGroup, ssrHydrationKey, ssrStyle, ssrStyleProperty, notSup as style, notSup as template, notSup as unregisterDelegatedContainer, notSup as unregisterDelegatedRoot, useHead };
4116
+ export { CLAIMS_DOCUMENT, CLAIMS_STREAM, CLAIM_PROP, 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, dynamic, notSup as dynamicProperty, effect, escape, generateHydrationScript, notSup as getDelegatedRoot, getExpectedRedirectStatus, getHydrationKey, notSup as getNextElement, notSup as getNextMarker, notSup as getNextMatch, getRequestEvent, getServerFunctionMetadata, getServerFunctionRPC, getTraceContext, hasFlashCookie, 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, resolveSSRNode, 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, ssrElementAttribute, ssrGroup, ssrHydrationKey, ssrSelectValues, ssrStyle, ssrStyleProperty, notSup as style, styleNonce, notSup as template, notSup as unregisterDelegatedContainer, notSup as unregisterDelegatedRoot, useHead };