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

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 (60) hide show
  1. package/dist/server.dev.js +705 -151
  2. package/dist/server.js +604 -123
  3. package/dist/server.observe.js +617 -124
  4. package/dist/web.dev.js +102 -41
  5. package/dist/web.js +75 -37
  6. package/dist/web.observe.js +75 -39
  7. package/frames/dist/assets.js +92 -0
  8. package/frames/dist/bind.dev.js +326 -0
  9. package/frames/dist/bind.js +295 -0
  10. package/frames/dist/client.dev.js +693 -919
  11. package/frames/dist/client.js +636 -917
  12. package/frames/dist/client.observe.js +637 -917
  13. package/frames/dist/regions.js +130 -0
  14. package/frames/dist/server.dev.js +607 -212
  15. package/frames/dist/server.js +554 -212
  16. package/frames/dist/server.observe.js +554 -212
  17. package/frames/dist/trace.js +42 -0
  18. package/frames/dist/wire.js +133 -0
  19. package/package.json +30 -3
  20. package/performance-tracks/dist/performance-tracks.dev.js +2 -1
  21. package/performance-tracks/dist/performance-tracks.observe.js +2 -1
  22. package/performance-tracks/types/index.d.ts +8 -6
  23. package/serialization/dist/decode.js +37 -8
  24. package/serialization/dist/serialization.js +39 -10
  25. package/serialization/types/serializer-decode.d.ts +24 -2
  26. package/server-functions/dist/client.dev.js +178 -72
  27. package/server-functions/dist/client.js +99 -61
  28. package/server-functions/dist/client.observe.js +178 -72
  29. package/server-functions/dist/server.dev.js +117 -56
  30. package/server-functions/dist/server.js +117 -56
  31. package/server-functions/dist/server.observe.js +117 -56
  32. package/skills/server-components/SKILL.md +228 -0
  33. package/types/client.d.ts +37 -2
  34. package/types/constants.d.ts +2 -1
  35. package/types/diagnostics.d.ts +8 -0
  36. package/types/frames/assets-tier.d.ts +78 -0
  37. package/types/frames/bind-tier.d.ts +60 -0
  38. package/types/frames/client.d.ts +37 -3
  39. package/types/frames/frame-client.d.ts +249 -96
  40. package/types/frames/frame-container-plugin.d.ts +2 -10
  41. package/types/frames/frame-sink.d.ts +33 -0
  42. package/types/frames/frame-transport.d.ts +66 -18
  43. package/types/frames/regions-tier.d.ts +45 -0
  44. package/types/frames/serializer-decode.d.ts +24 -2
  45. package/types/frames/server.d.ts +53 -1
  46. package/types/frames/trace-tier.d.ts +2 -0
  47. package/types/frames/tree-rewrite.d.ts +39 -0
  48. package/types/frames/wire-tier.d.ts +116 -0
  49. package/types/index.d.ts +38 -0
  50. package/types/index.server.d.ts +10 -1
  51. package/types/jsx.d.ts +11 -1
  52. package/types/observe.d.ts +182 -12
  53. package/types/request-error-hook.d.ts +5 -0
  54. package/types/serializer-decode.d.ts +24 -2
  55. package/types/server-functions/client.d.ts +26 -0
  56. package/types/server-functions/registry.d.ts +4 -1
  57. package/types/server-functions/shared.d.ts +12 -8
  58. package/types/server-mock.d.ts +13 -1
  59. package/types/server-observe.d.ts +8 -0
  60. package/types/server.d.ts +125 -12
@@ -1,7 +1,7 @@
1
- import { DEV, OBSERVE, getOwner, onCleanup, createMemo, runWithOwner, createSignal, createRenderEffect, createLoadingBoundary, createOwner, sharedConfig } from 'solid-js';
2
- import { delegateEvents, insert } from '@solidjs/web';
3
- import { frameAddress, SINGLE_FLIGHT_HEADER, LIVE_WIRE, deserializeStream, getServerFunctionsCodec, createChunk, deliverFlightData, ERROR_HEADER, hasFlightMetadata, isEventStream, ChunkReader, configureServerFunctionsClient } from '@solidjs/web/server-functions/client';
4
- import { materializeContainerTrace } from 'solid-js/internal';
1
+ import { DEV, OBSERVE, getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, createSignal, createOwner } from 'solid-js';
2
+ import { insert } from '@solidjs/web';
3
+ import { frameAddress, SINGLE_FLIGHT_HEADER, LIVE_WIRE, deserializeStream, getServerFunctionsCodec, createChunk, deliverFlightData, ERROR_HEADER, hasFlightMetadata, ChunkReader, configureServerFunctionsClient } from '@solidjs/web/server-functions/client';
4
+ import { sharedConfig, createLoadingBoundary } from 'solid-js/internal';
5
5
 
6
6
  const ELEMENT_NODE = 1;
7
7
  const TEXT_NODE = 3;
@@ -16,74 +16,6 @@ function claimNode(handlers, el) {
16
16
  for (let i = 0; i < handlers.length; i++) handlers[i](el);
17
17
  }
18
18
  const claimedAttr = name => name === "href" || name === "action";
19
- const BOUND_SEAM = Symbol.for("solid.bnd");
20
- const boundSeam = globalThis[BOUND_SEAM] || (globalThis[BOUND_SEAM] = {});
21
- const BND_ATTR = "_bnd";
22
- const BND_SELECTOR = "[_bnd]";
23
- function bndMap(el) {
24
- const s = el.getAttribute(BND_ATTR);
25
- if (!s) return undefined;
26
- const map = {};
27
- for (const entry of s.split(",")) {
28
- const eq = entry.indexOf("=");
29
- if (eq < 1) continue;
30
- const pos = entry.slice(0, eq);
31
- const prop = decodeURIComponent(entry.slice(eq + 1));
32
- const prev = map[pos];
33
- if (prev === undefined) map[pos] = prop;else if (Array.isArray(prev)) prev.push(prop);else map[pos] = [prev, prop];
34
- }
35
- return map;
36
- }
37
- boundSeam.resolve = (el, type) => {
38
- const frame = el._$bndFrame;
39
- if (!frame) return undefined;
40
- const map = bndMap(el);
41
- const prop = map && map[type];
42
- if (typeof prop !== "string") return undefined;
43
- return claimFn(frame, type, prop);
44
- };
45
- function claimFn(frame, pos, prop) {
46
- const fn = frame.clientProp(prop);
47
- if (typeof fn === "function") return fn;
48
- if (fn !== undefined) {
49
- console.warn(`A server element claims \`${pos}\` from client prop \`${prop}\`, but the mounted ` + `frame's prop is not a function.`);
50
- }
51
- return undefined;
52
- }
53
- function sweepBound(root, frame, delegate, scope) {
54
- const isElement = root.nodeType === ELEMENT_NODE;
55
- if (!isElement && root.nodeType !== 11 ) return;
56
- let els;
57
- if (isElement && root.hasAttribute(BND_ATTR)) (els = []).push(root);
58
- const found = root.querySelectorAll(BND_SELECTOR);
59
- if (found.length) {
60
- els || (els = []);
61
- for (let i = 0; i < found.length; i++) els.push(found[i]);
62
- }
63
- if (!els) return;
64
- const run = () => {
65
- let types;
66
- for (const el of els) {
67
- el._$bndFrame = frame;
68
- const map = bndMap(el);
69
- if (!map) continue;
70
- for (const pos in map) {
71
- if (pos === "ref") fireRefs(frame, el, map.ref);else (types || (types = [])).push(pos);
72
- }
73
- }
74
- if (types && delegate) delegate(types);
75
- };
76
- scope ? scope(run) : run();
77
- }
78
- function fireRefs(frame, el, prop) {
79
- const fired = el._$bndFired || (el._$bndFired = new Set());
80
- for (const p of Array.isArray(prop) ? prop : [prop]) {
81
- if (fired.has(p)) continue;
82
- fired.add(p);
83
- const fn = claimFn(frame, "ref", p);
84
- if (fn) fn(el);
85
- }
86
- }
87
19
  function claimTree(handlers, root) {
88
20
  const isElement = root.nodeType === ELEMENT_NODE;
89
21
  if (!isElement && root.nodeType !== 11 ) return;
@@ -95,6 +27,27 @@ const placeholderId = name => `pl-${name}`;
95
27
  const SLOT_START = /^slot:(.+):start$/;
96
28
  const SLOT_END = /^slot:(.+):end$/;
97
29
  const slotEnd = id => `slot:${id}:end`;
30
+ const SLOT_MARKER = "_s:";
31
+ const SLOT_TEXT = SLOT_MARKER + "t=";
32
+ const SLOT_TEXT_END = "/" + SLOT_MARKER + "t";
33
+ const isTextStart = n => n.nodeType === COMMENT_NODE && n.data.startsWith(SLOT_TEXT);
34
+ function hasSlotMarker(el) {
35
+ const attrs = el.attributes;
36
+ for (let i = 0; i < attrs.length; i++) if (attrs[i].name.startsWith(SLOT_MARKER)) return true;
37
+ return false;
38
+ }
39
+ function isAsyncValue(v) {
40
+ return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
41
+ }
42
+ function slotShapeFinding(data, message) {
43
+ DEV.report(OBSERVE.diagnostics.emit({
44
+ code: "BINDING_SLOT_POSITION",
45
+ kind: "render",
46
+ severity: "warn",
47
+ message,
48
+ data
49
+ }, null));
50
+ }
98
51
  function chunkToRecords(chunk) {
99
52
  switch (chunk.type) {
100
53
  case "start":
@@ -154,9 +107,12 @@ function chunkToRecords(chunk) {
154
107
  digest: chunk.digest
155
108
  }
156
109
  };
110
+ case "ops":
111
+ return Object.assign({}, ...chunk.ops.map(chunkToRecords));
157
112
  case "complete":
158
113
  return {
159
- ":complete": true
114
+ ":complete": true,
115
+ ":bound": chunk.bound
160
116
  };
161
117
  case "error":
162
118
  if (!chunk.key) return {
@@ -180,11 +136,20 @@ function createFrameHost(options = {}) {
180
136
  });
181
137
  return store;
182
138
  };
139
+ const landings = new Map();
140
+ const lands = records => "" in records || ":error" in records || ":complete" in records;
141
+ const applyTo = (id, version, r) => {
142
+ const set = frames.get(id);
143
+ if (set) for (const frame of set) frame.apply({
144
+ version,
145
+ r
146
+ });
147
+ };
183
148
  const write = (store, version, records) => {
184
149
  if (store.version !== undefined && version < store.version) return false;
185
150
  if (store.version === undefined || version > store.version) {
186
151
  store.version = version;
187
- clearStreamRecords(store.records);
152
+ store.records = {};
188
153
  }
189
154
  const assets = records["seg::assets"];
190
155
  const previous = assets && store.records["seg::assets"];
@@ -200,19 +165,47 @@ function createFrameHost(options = {}) {
200
165
  }
201
166
  return true;
202
167
  };
168
+ const settleArgs = (store, recordKey, record, chunk) => {
169
+ const args = record.args;
170
+ const out = {};
171
+ let regions, decoded;
172
+ const settle = () => {
173
+ if (! --record.pending && store.records[recordKey] === record) applyTo(chunk.id, store.version, {
174
+ [recordKey]: record
175
+ });
176
+ };
177
+ for (const key in args) {
178
+ const value = args[key];
179
+ if (value && typeof value.$ref === "string") {
180
+ const resolved = out[key] = options.resolve && options.resolve(value, chunk.id, chunk.version, store.version);
181
+ (decoded ??= {})[key] = true;
182
+ if (resolved instanceof Promise && resolved.s === 0) {
183
+ record.pending = (record.pending || 0) + 1;
184
+ resolved.c.push(settle);
185
+ }
186
+ } else {
187
+ if (value && typeof value.$frame === "string") (regions ??= {})[key] = value.$frame;
188
+ out[key] = value;
189
+ }
190
+ }
191
+ record.args = out;
192
+ record.regions = regions;
193
+ record.decoded = decoded;
194
+ };
203
195
  return {
204
- delegate: options.delegate,
205
196
  register(id, frame) {
206
197
  let set = frames.get(id);
207
198
  if (!set) frames.set(id, set = new Set());
208
199
  set.add(frame);
209
200
  const store = stores.get(id);
210
201
  if (store && store.version !== undefined) {
211
- frame.apply({
202
+ if (!store.open) frame.apply({
212
203
  version: store.version,
213
204
  r: store.records
205
+ });else if (store.shown) frame.apply({
206
+ version: store.shownVersion,
207
+ r: store.shown
214
208
  });
215
- frame.rebase && frame.rebase();
216
209
  }
217
210
  },
218
211
  unregister(id, frame) {
@@ -230,26 +223,68 @@ function createFrameHost(options = {}) {
230
223
  value: html
231
224
  };
232
225
  if (store.version === undefined) store.version = 0;
226
+ store.shown = store.records;
227
+ store.shownVersion = store.version;
233
228
  }
234
229
  }
235
230
  }
236
231
  }
237
- if (!frame) stores.delete(id);
232
+ if (!frame) {
233
+ stores.delete(id);
234
+ landings.delete(id);
235
+ }
238
236
  },
239
237
  apply(chunk) {
240
238
  if (chunk.type === "data") {
241
- options.applyData && options.applyData(chunk);
239
+ const store = stores.get(chunk.id);
240
+ const current = store && store.version;
241
+ if (store && chunk.version < current) return;
242
+ options.applyData && options.applyData(chunk, current);
242
243
  return;
243
244
  }
244
245
  const records = chunkToRecords(chunk);
245
- if (!write(storeFor(chunk.id), chunk.version, records)) return;
246
- const set = frames.get(chunk.id);
247
- if (set) {
248
- for (const frame of set) frame.apply({
249
- version: chunk.version,
250
- r: records
251
- });
246
+ const store = storeFor(chunk.id);
247
+ if (!write(store, chunk.version, records)) return;
248
+ if (chunk.type === "slot") {
249
+ const key = `slot:${chunk.key}`;
250
+ settleArgs(store, key, records[key], chunk);
251
+ }
252
+ if (chunk.type === "complete" && chunk.bound) {
253
+ console.warn(`Server component "${chunk.id}" kept streaming past the server's ${chunk.bound} ` + `bound and was cut off (complete.bound: "${chunk.bound}"); its content is the last ` + `value the server sent, not a settled one. A source meant to keep streaming is ` + `declared with live(): wrap the server function (live(fn)) so the client holds a ` + `standing connection instead.`);
252
254
  }
255
+ let r = records;
256
+ if (chunk.type === "start") store.open = true;else if (lands(records)) {
257
+ store.open = false;
258
+ store.shown = r = store.records;
259
+ store.shownVersion = chunk.version;
260
+ const landed = landings.get(chunk.id);
261
+ if (landed && !(":complete" in records && ":error" in r)) {
262
+ landings.delete(chunk.id);
263
+ ":error" in records ? landed.j(records[":error"]) : landed.r();
264
+ }
265
+ }
266
+ applyTo(chunk.id, chunk.version, r);
267
+ if (":complete" in records || ":error" in records) options.closeData && options.closeData(chunk.id, chunk.version, records[":error"]);
268
+ },
269
+ landing(id) {
270
+ const store = stores.get(id);
271
+ if (!store || !store.open && !store.shown) return undefined;
272
+ if (store.shown && !(":error" in store.shown)) return undefined;
273
+ let wait = landings.get(id);
274
+ if (!wait) {
275
+ landings.set(id, wait = {});
276
+ wait.p = new Promise((r, j) => (wait.r = r, wait.j = j));
277
+ }
278
+ return wait.p;
279
+ },
280
+ preview(chunk) {
281
+ if (chunk.type !== "slot") return;
282
+ const set = frames.get(chunk.id);
283
+ if (!set) return;
284
+ const records = chunkToRecords(chunk);
285
+ const key = `slot:${chunk.key}`;
286
+ settleArgs(storeFor(chunk.id), key, records[key], chunk);
287
+ for (const frame of set) frame.preview && frame.preview(records);
253
288
  },
254
289
  get(id) {
255
290
  const set = frames.get(id);
@@ -259,66 +294,66 @@ function createFrameHost(options = {}) {
259
294
  if (!options.serialize) throw new Error("host has no serializer");
260
295
  return options.serialize(value);
261
296
  },
262
- resolve(ref, frameId) {
263
- return options.resolve ? options.resolve(ref, frameId) : undefined;
264
- },
265
297
  revive: options.revive,
266
- isContainer: options.isContainer,
267
298
  prepareData: options.prepareData
268
299
  };
269
300
  }
270
301
  const FRAME_APPLIED_EVENT = "frame:applied";
302
+ const tierLoaders = {};
303
+ const tierLoads = {};
304
+ const liveFrames = new Set();
305
+ function prepareTier(name) {
306
+ let load = tierLoads[name];
307
+ if (!load) {
308
+ const loader = tierLoaders[name];
309
+ tierLoads[name] = load = loader ? loader().then(module => {
310
+ load.r = module;
311
+ module.install?.();
312
+ for (const frame of liveFrames) frame.apply({
313
+ version: frame.version,
314
+ r: {}
315
+ });
316
+ }) : Promise.resolve();
317
+ }
318
+ return load;
319
+ }
320
+ const tierReady = name => !tierLoaders[name] || prepareTier(name).r;
321
+ const needsRegions = record => record.regions && !tierReady("regions");
322
+ const carriesTrace = value => value != null && typeof value === "object" && (value.$tr != null || Object.values(value).some(carriesTrace));
323
+ const needsTrace = args => !tierLoads.trace?.r && carriesTrace(args) && !tierReady("trace");
271
324
  class FrameImpl {
272
325
  #element;
273
- #start;
274
- #end;
275
326
  #options;
327
+ #outer;
276
328
  #version;
277
329
  #store = Object.create(null);
278
- #appliedRootValue;
330
+ #appliedRoot;
331
+ #appliedError;
279
332
  #hasContent = false;
280
- #errorNotified = false;
281
- #revealed = new Set();
282
- #fallbackShown = new Set();
283
333
  #appliedHoles = new Map();
284
- #have;
285
334
  #slots;
286
335
  #mountedSlots = new Set();
287
336
  #slotCleanups = new Map();
288
337
  #slotArgs = new Map();
289
338
  #slotUpdaters = new Map();
290
- #slotRegions = new Map();
291
- #slotResolvedRefs = new Map();
292
- #slotNodes = new Map();
293
- #processedAssets = new WeakSet();
294
- #recordRefresh = null;
339
+ #hold;
340
+ #heldRecords = new Map();
295
341
  #disposed = false;
296
- #styleFlush = () => {
297
- if (!this.#disposed) this.#flush();
298
- };
299
342
  #claimTree = (node, direct) => {
300
- if (!direct && node.nodeType !== TEXT_NODE && node.nodeType !== COMMENT_NODE) {
301
- const o = this.#options;
302
- sweepBound(node, this, o.delegate || o.host && o.host.delegate, o.ownerScope);
303
- }
304
343
  const handlers = claimHandlers();
305
344
  if (!handlers) return;
306
345
  this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node));
307
346
  };
308
- clientProp(name) {
309
- const props = this.#options.props;
310
- return props ? props[name] : undefined;
311
- }
312
347
  #scoped(fn) {
313
348
  const scope = this.#options.ownerScope;
314
349
  return scope ? scope(fn) : fn();
315
350
  }
316
- constructor(element, start, end, options = {}) {
351
+ constructor(element, options = {}) {
317
352
  this.#element = element;
318
- this.#start = start;
319
- this.#end = end;
320
353
  this.#options = options;
321
354
  this.#slots = options.slots;
355
+ this.#outer = options.parent;
356
+ liveFrames.add(this);
322
357
  if (options.adopt) {
323
358
  this.#hasContent = true;
324
359
  this.#claimContent();
@@ -328,15 +363,12 @@ class FrameImpl {
328
363
  }
329
364
  if (options.adopt && this.#version === undefined) this.#syncSlots();
330
365
  }
331
- #parent() {
332
- return this.#element ?? this.#start.parentNode;
333
- }
334
366
  #applied(version, reason) {
335
367
  this.#options.onApply?.({
336
368
  version,
337
369
  reason
338
370
  });
339
- const parent = this.#parent();
371
+ const parent = this.#element;
340
372
  const Ev = parent && (parent.ownerDocument || parent).defaultView?.CustomEvent;
341
373
  if (Ev) {
342
374
  parent.dispatchEvent(new Ev(FRAME_APPLIED_EVENT, {
@@ -349,18 +381,12 @@ class FrameImpl {
349
381
  }));
350
382
  }
351
383
  }
352
- #firstContent() {
353
- return this.#start ? this.#start.nextSibling : this.#parent().firstChild;
354
- }
355
384
  get version() {
356
385
  return this.#version;
357
386
  }
358
387
  get store() {
359
388
  return this.#store;
360
389
  }
361
- isRevealed(segment) {
362
- return this.#revealed.has(segment);
363
- }
364
390
  get error() {
365
391
  return this.#store[":error"];
366
392
  }
@@ -375,68 +401,59 @@ class FrameImpl {
375
401
  this.#version = v;
376
402
  this.#resetStreamState();
377
403
  }
378
- for (const key in write.r) {
379
- const incoming = write.r[key];
380
- if (incoming && incoming.kind === "slot" && key.charCodeAt(0) === 115 && key.startsWith("slot:")) {
381
- const existing = this.#store[key];
382
- if (existing && existing.kind === "slot" && argsEquivalent(existing.args, incoming.args)) {
383
- continue;
384
- }
385
- }
386
- this.#store[key] = incoming;
387
- }
404
+ for (const key in write.r) this.#store[key] = write.r[key];
388
405
  this.#flush();
389
406
  }
390
- #resetStreamState(root) {
391
- this.#revealed.clear();
392
- this.#fallbackShown.clear();
407
+ preview(records, inherited) {
408
+ const adopted = new Set();
409
+ if (this.#disposed) return adopted;
410
+ const R = tierLoads.regions?.r;
411
+ for (const key in records) {
412
+ const record = records[key];
413
+ if (!record || record.kind !== "slot" || !key.startsWith("slot:")) continue;
414
+ if (inherited && key in this.#store) continue;
415
+ const occurrence = key.slice(5);
416
+ const update = this.#mountedSlots.has(occurrence) && this.#slotUpdaters.get(occurrence);
417
+ if (!update || (R ? R.changed(this, occurrence, record) : record.regions)) continue;
418
+ this.#slotArgs.set(occurrence, record);
419
+ adopted.add(key);
420
+ update(this.#resolveArgs(occurrence, record));
421
+ }
422
+ if (R) for (const frame of R.frames(this)) for (const key of frame.preview(records, true)) adopted.add(key);
423
+ if (!inherited) for (const key of adopted) this.#store[key] = records[key];
424
+ return adopted;
425
+ }
426
+ #resetStreamState() {
427
+ this.#store = Object.create(null);
428
+ this.#appliedRoot = this.#appliedError = undefined;
393
429
  this.#appliedHoles.clear();
394
- this.#processedAssets = new WeakSet();
395
- this.#errorNotified = false;
396
- clearStreamRecords(this.#store, root);
397
430
  }
398
431
  #flush() {
399
432
  if (this.#disposed) return;
400
433
  const version = this.#version;
401
434
  const root = this.#store[""];
402
- if (root && root.kind === "html" && root.value !== this.#appliedRootValue) {
435
+ if (root && root.kind === "html" && root !== this.#appliedRoot) {
403
436
  const reason = this.#hasContent ? "morph" : "materialize";
404
437
  this.#applyRoot(root.value);
405
- this.#appliedRootValue = root.value;
406
- this.#have = root.digest === undefined ? undefined : {
407
- "": root.digest,
408
- ...root.holes
409
- };
438
+ this.#appliedRoot = root;
439
+ this.#recordHave("", root);
410
440
  this.#applied(version, reason);
411
441
  }
412
- if (this.#store[":error"] && !this.#errorNotified) {
413
- this.#errorNotified = true;
442
+ const error = this.#store[":error"];
443
+ if (error && error !== this.#appliedError) {
444
+ this.#appliedError = error;
414
445
  this.#applied(version, "error");
415
446
  }
416
- let progressed = true;
417
- while (progressed) {
418
- progressed = false;
419
- for (const key in this.#store) {
420
- const name = segmentName(key);
421
- if (name === null || this.#revealed.has(name)) continue;
422
- if (this.#segmentReady(name)) {
423
- this.#revealSegment(name);
424
- this.#applied(version, "reveal");
425
- progressed = true;
426
- }
427
- }
428
- for (const key in this.#store) {
429
- const m = /^seg:([^:]+):fallback$/.exec(key);
430
- if (!m) continue;
431
- const name = m[1];
432
- if (this.#revealed.has(name) || this.#fallbackShown.has(name)) continue;
433
- if (this.#showFallback(name)) {
434
- this.#fallbackShown.add(name);
435
- this.#applied(version, "reveal");
436
- progressed = true;
437
- }
438
- }
439
- }
447
+ for (const key in this.#store) {
448
+ const record = this.#store[key];
449
+ if (!key.endsWith(":assets") || !record || this.#appliedHoles.get(key) === record) continue;
450
+ const tier = tierReady("assets");
451
+ if (!tier) break;
452
+ this.#appliedHoles.set(key, record);
453
+ tier.apply(record);
454
+ }
455
+ this.#revealSegments();
456
+ let morphed = false;
440
457
  for (const key in this.#store) {
441
458
  const record = this.#store[key];
442
459
  if (!record || this.#appliedHoles.get(key) === record) continue;
@@ -447,110 +464,104 @@ class FrameImpl {
447
464
  } else if (this.#applyHole(key.slice(5), record.value)) {
448
465
  this.#appliedHoles.set(key, record);
449
466
  this.#recordHave(key.slice(5), record);
450
- this.#applied(version, "morph");
467
+ morphed = true;
451
468
  }
452
469
  } else if (key.startsWith("attr:")) {
453
470
  if (this.#applyAttrs(key.slice(5), record.value, record.removed)) {
454
471
  this.#appliedHoles.set(key, record);
455
472
  this.#recordHave("lha:" + key.slice(5), record);
456
- this.#applied(version, "morph");
473
+ morphed = true;
457
474
  }
458
475
  }
459
476
  }
460
- for (const key in this.#store) {
461
- const record = this.#store[key];
462
- if (!key.endsWith(":assets") || !record || this.#processedAssets.has(record)) {
463
- continue;
464
- }
465
- this.#processedAssets.add(record);
466
- if (record.modules) {
467
- for (const href of record.modules) ensureModulePreload(href);
468
- }
469
- if (record.preloads) {
470
- for (const entry of record.preloads) ensurePreload(entry);
471
- }
472
- }
477
+ if (morphed) this.#applied(version, "morph");
473
478
  this.#syncSlots();
474
479
  }
475
480
  #resolveSlot(prop) {
476
- return this.#slots?.[prop] ?? this.#options.resolveSlot?.(prop);
481
+ return this.#slots?.[prop] ?? (this.#outer && this.#outer.#resolveSlot(prop));
477
482
  }
478
483
  #resolveSlotRecord(occurrence) {
479
484
  const record = this.#store[`slot:${occurrence}`];
480
485
  if (record !== undefined) return record;
481
- return this.#options.resolveSlotRecord?.(occurrence);
486
+ return this.#outer && this.#outer.#resolveSlotRecord(occurrence);
482
487
  }
483
488
  #removeSlotRecord(occurrence) {
484
489
  const key = `slot:${occurrence}`;
485
490
  if (key in this.#store) {
486
491
  if (!this.#mountedSlots.has(occurrence)) delete this.#store[key];
487
- } else this.#options.removeSlotRecord?.(occurrence);
492
+ } else this.#outer && this.#outer.#removeSlotRecord(occurrence);
488
493
  }
489
494
  #syncSlots(root) {
490
- if (!this.#slots && !this.#options.resolveSlot) return;
495
+ if (!this.#slots && !this.#outer) return;
491
496
  const found = new Map();
492
- if (root) collectSlots(root.firstChild, null, found);else this.#collectSlots(found);
497
+ if (root) collectSlots(root.firstChild, null, found, found);else this.#collectSlots(found, found);
498
+ let waiting = false;
499
+ const R = tierLoads.regions?.r;
500
+ const B = tierLoads.bind?.r;
493
501
  for (const [occurrence, start] of found) {
494
502
  const callback = this.#resolveSlot(propOf(occurrence));
495
- if (!callback) continue;
503
+ const consumers = Array.isArray(start) ? start : null;
504
+ if (!callback) {
505
+ if (consumers) devSlotOrphan(this, occurrence, consumers, "fill");
506
+ continue;
507
+ }
496
508
  const record = this.#resolveSlotRecord(occurrence);
497
- if (record && record.kind === "slot" && this.#refsUnresolved(record.args)) continue;
498
- const prev = this.#slotNodes.get(occurrence);
499
- const prevFirst = Array.isArray(prev) ? prev[0] : prev;
500
- const zombie = this.#mountedSlots.has(occurrence) && prevFirst && !prevFirst.parentNode;
501
- if (zombie) {
502
- this.#mountedSlots.delete(occurrence);
503
- this.#runSlotCleanups(occurrence);
509
+ const mounted = this.#mountedSlots.has(occurrence);
510
+ if (record === undefined && isCalled(occurrence)) {
511
+ waiting ||= !mounted;
512
+ if (consumers && !mounted && !this.#options.adopt) devSlotOrphan(this, occurrence, consumers, "record");
513
+ continue;
504
514
  }
505
- if (!this.#mountedSlots.has(occurrence)) {
506
- if (record === undefined && !root && this.#options.adopt && this.#options.recordsPending?.()) {
507
- this.#recordRefresh ??= setTimeout(() => {
508
- this.#recordRefresh = null;
509
- if (this.#disposed) return;
510
- this.#options.drainRecords?.();
511
- this.#syncSlots();
512
- });
513
- continue;
514
- }
515
- if (this.#options.adopt) this.#discoverRegions(occurrence, start);
516
- const nodes = this.#invokeSlot(occurrence, callback, record, start, this.#options.adopt);
517
- if (nodes) this.#replaceRange(occurrence, start, nodes);
518
- this.#slotNodes.set(occurrence, nodes);
515
+ if (!mounted && record && (record.pending || needsRegions(record) || needsTrace(record.args))) {
516
+ waiting = true;
517
+ if (this.#options.adopt && !consumers) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
518
+ continue;
519
+ }
520
+ if (!mounted) {
521
+ const held = this.#heldRecords.get(occurrence);
522
+ this.#heldRecords.delete(occurrence);
523
+ const mountRecord = held || record;
524
+ this.#invokeSlot(occurrence, callback, mountRecord, start, this.#options.adopt);
525
+ if (consumers) B.sync(this, occurrence, consumers);
519
526
  this.#mountedSlots.add(occurrence);
520
- if (!this.#options.adopt || nodes) this.#discoverRegions(occurrence, start);
521
- this.#bindRegions(occurrence);
522
- } else if (record !== this.#slotArgs.get(occurrence)) {
523
- if (this.#refArgsUnchanged(occurrence, record)) {
524
- this.#slotArgs.set(occurrence, record);
525
- this.#reconcileRegions(occurrence, record);
526
- continue;
527
- }
527
+ R?.bind(this, occurrence);
528
+ if (mountRecord === record || !record || record.kind !== "slot") continue;
529
+ }
530
+ if (consumers) B.sync(this, occurrence, consumers);
531
+ if (record !== this.#slotArgs.get(occurrence)) {
532
+ if (needsRegions(record) || needsTrace(record.args)) continue;
528
533
  const update = this.#slotUpdaters.get(occurrence);
529
534
  if (update) {
530
- const props = this.#resolveArgs(occurrence, record.args);
535
+ const props = this.#resolveArgs(occurrence, record);
531
536
  this.#slotArgs.set(occurrence, record);
532
537
  update(props);
533
- this.#bindRegions(occurrence);
538
+ R?.bind(this, occurrence);
534
539
  continue;
535
540
  }
536
- const nodes = this.#invokeSlot(occurrence, callback, record, start);
537
- if (nodes) this.#replaceRange(occurrence, start, nodes);
538
- this.#slotNodes.set(occurrence, nodes);
539
- this.#bindRegions(occurrence);
541
+ this.#invokeSlot(occurrence, callback, record, start);
542
+ R?.bind(this, occurrence);
540
543
  }
541
544
  }
545
+ if (found.b && !tierReady("bind")) waiting = true;
542
546
  if (!root) {
543
547
  for (const occurrence of [...this.#mountedSlots]) {
544
548
  if (!found.has(occurrence)) this.#unmountSlot(occurrence);
545
549
  }
550
+ if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
546
551
  }
547
552
  }
553
+ #releaseHold() {
554
+ const release = this.#hold;
555
+ this.#hold = undefined;
556
+ release && release();
557
+ }
548
558
  #invokeSlot(occurrence, callback, record, start, adopted) {
549
559
  this.#slotUpdaters.delete(occurrence);
550
560
  const cleanups = this.#slotCleanups.get(occurrence) ?? [];
551
561
  let existing = [];
552
562
  let end = null;
553
- if (start) end = eachInRange(start, occurrence, n => existing.push(n));
563
+ const positions = Array.isArray(start) ? start : undefined;
564
+ if (start && !positions) end = eachInRange(start, occurrence, n => existing.push(n));
554
565
  const ctx = {
555
566
  frame: this.#options.claimScope ?? this.#options.id,
556
567
  key: occurrence,
@@ -562,33 +573,24 @@ class FrameImpl {
562
573
  range: end ? {
563
574
  start,
564
575
  end
565
- } : undefined
576
+ } : undefined,
577
+ positions,
578
+ onRebind: positions ? fn => tierLoads.bind.r.rebinder(this, occurrence, fn) : undefined
566
579
  };
567
- const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record.args) : {};
568
- const content = this.#scoped(() => callback(props, ctx));
580
+ const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record, adopted, start) : {};
581
+ this.#scoped(() => callback(props, ctx));
569
582
  this.#slotArgs.set(occurrence, record);
570
583
  if (cleanups.length) this.#slotCleanups.set(occurrence, cleanups);
571
- if (content == null) return null;
572
- return Array.isArray(content) ? content : [content];
573
- }
574
- #replaceRange(key, start, nodes) {
575
- const parent = start.parentNode;
576
- const end = eachInRange(start, key, n => parent.removeChild(n));
577
- for (const node of nodes) parent.insertBefore(node, end);
578
584
  }
579
585
  #unmountSlot(key) {
580
586
  this.#mountedSlots.delete(key);
581
- this.#slotNodes.delete(key);
582
587
  this.#slotArgs.delete(key);
583
588
  this.#slotUpdaters.delete(key);
584
- this.#slotResolvedRefs.delete(key);
589
+ this.#heldRecords.delete(key);
585
590
  this.#removeSlotRecord(key);
586
591
  this.#runSlotCleanups(key);
587
- const regions = this.#slotRegions.get(key);
588
- if (regions) {
589
- disposeRegions(regions);
590
- this.#slotRegions.delete(key);
591
- }
592
+ tierLoads.regions?.r?.unmount(this, key);
593
+ tierLoads.bind?.r?.unmount(this, key);
592
594
  }
593
595
  #runSlotCleanups(key) {
594
596
  const cleanups = this.#slotCleanups.get(key);
@@ -596,129 +598,33 @@ class FrameImpl {
596
598
  this.#slotCleanups.delete(key);
597
599
  for (const fn of cleanups) fn();
598
600
  }
599
- #refsUnresolved(args) {
600
- const {
601
- host,
602
- id
603
- } = this.#options;
604
- if (host) for (const key in args) {
605
- if (isDataRef(args[key]) && host.resolve(args[key], id) === undefined) return true;
606
- }
607
- return false;
601
+ get options() {
602
+ return this.#options;
608
603
  }
609
- #regionsFor(slotKey) {
610
- let regions = this.#slotRegions.get(slotKey);
611
- if (!regions) this.#slotRegions.set(slotKey, regions = new Map());
612
- return regions;
613
- }
614
- #resolveArgs(slotKey, args) {
615
- const host = this.#options.host;
616
- const regions = this.#regionsFor(slotKey);
604
+ #resolveArgs(slotKey, record, claiming, start) {
605
+ const {
606
+ args,
607
+ regions,
608
+ decoded
609
+ } = record;
610
+ const revive = this.#options.host && this.#options.host.revive;
617
611
  const props = {};
618
612
  for (const key in args) {
613
+ if (regions && key in regions) continue;
619
614
  const value = args[key];
620
- if (isDataRef(value)) {
621
- const resolved = host ? host.resolve(value, this.#options.id) : undefined;
622
- let cache = this.#slotResolvedRefs.get(slotKey);
623
- if (!cache) this.#slotResolvedRefs.set(slotKey, cache = {});
624
- cache[key] = resolved;
625
- props[key] = resolved;
626
- } else if (isFrameRef(value)) {
627
- let entry = regions.get(key);
628
- if (!entry) {
629
- const element = makeFrameElement(value.$frame);
630
- entry = {
631
- childId: value.$frame,
632
- element,
633
- frame: undefined
634
- };
635
- regions.set(key, entry);
636
- } else if (entry.childId !== value.$frame) {
637
- renameRegion(entry, value.$frame);
638
- }
639
- props[key] = entry.element;
640
- } else {
641
- props[key] = host && host.revive ? host.revive(value) : value;
642
- }
615
+ props[key] = revive && !(decoded && key in decoded) ? revive(value, claiming) : value;
643
616
  }
617
+ if (regions) tierLoads.regions.r.resolve(this, slotKey, regions, props, claiming && start);
644
618
  return props;
645
619
  }
646
- #discoverRegions(slotKey, start) {
647
- if (!start) return;
648
- const regions = this.#regionsFor(slotKey);
649
- eachInRange(start, slotKey, n => collectRegionElements(n, regions));
650
- }
651
- #refArgsUnchanged(occurrence, record) {
652
- const old = this.#slotArgs.get(occurrence);
653
- if (!record || record.kind !== "slot") return false;
654
- if (old && old.kind !== "slot") return false;
655
- const a = old && old.args || {};
656
- const b = record.args || {};
657
- const ka = Object.keys(a);
658
- const kb = Object.keys(b);
659
- if (kb.length !== ka.length) return false;
660
- const cache = this.#slotResolvedRefs.get(occurrence);
661
- for (const key of ka) {
662
- const va = a[key];
663
- const vb = b[key];
664
- if (va === vb) continue;
665
- if (isFrameRef(va) && isFrameRef(vb)) continue;
666
- if (isDataRef(va) && isDataRef(vb) && cache && key in cache) {
667
- const host = this.#options.host;
668
- const next = host ? host.resolve(vb, this.#options.id) : undefined;
669
- if (host && host.isContainer && (host.isContainer(next) || host.isContainer(cache[key]))) {
670
- if (next === cache[key]) continue;
671
- return false;
672
- }
673
- if (isAsyncLike(next) || isAsyncLike(cache[key])) return false;
674
- try {
675
- if (JSON.stringify(next) === JSON.stringify(cache[key])) continue;
676
- } catch (e) {
677
- return false;
678
- }
679
- }
680
- return false;
681
- }
682
- return true;
620
+ #collectSlots(found, elements) {
621
+ collectSlots(this.#element.firstChild, null, found, elements);
683
622
  }
684
- #reconcileRegions(occurrence, record) {
685
- const args = record && record.args;
686
- if (!args) return;
687
- const regions = this.#slotRegions.get(occurrence);
688
- if (!regions) return;
689
- for (const key in args) {
690
- const value = args[key];
691
- if (!isFrameRef(value)) continue;
692
- const entry = regions.get(key);
693
- if (entry && entry.childId !== value.$frame) renameRegion(entry, value.$frame);
694
- }
695
- }
696
- #bindRegions(slotKey) {
697
- const regions = this.#slotRegions.get(slotKey);
698
- if (!regions) return;
699
- for (const entry of regions.values()) {
700
- if (!entry.frame) {
701
- entry.frame = new FrameImpl(entry.element, null, null, {
702
- id: entry.childId,
703
- host: this.#options.host,
704
- adopt: entry.adopt,
705
- claimScope: this.#options.claimScope ?? this.#options.id,
706
- ownerScope: this.#options.ownerScope,
707
- resolveSlot: prop => this.#resolveSlot(prop),
708
- resolveSlotRecord: occurrence => this.#resolveSlotRecord(occurrence),
709
- removeSlotRecord: occurrence => this.#removeSlotRecord(occurrence)
710
- });
711
- }
712
- }
713
- }
714
- #collectSlots(found) {
715
- collectSlots(this.#firstContent(), this.#end, found);
716
- }
717
- #findPlaceholder(name) {
718
- return findPlaceholder(this.#firstContent(), this.#end, placeholderId(name));
623
+ #findPlaceholder(name, root) {
624
+ return findPlaceholder((root || this.#element).firstChild, null, placeholderId(name));
719
625
  }
720
626
  contentHTML() {
721
- if (this.#disposed || !this.#element || !this.#hasContent) return null;
627
+ if (this.#disposed || !this.#hasContent) return null;
722
628
  return this.#element.innerHTML;
723
629
  }
724
630
  rebind(id) {
@@ -736,20 +642,11 @@ class FrameImpl {
736
642
  this.#element.setAttribute(FRAME_ID_ATTR, id);
737
643
  }
738
644
  this.#version = undefined;
739
- this.#appliedRootValue = undefined;
740
- this.#resetStreamState(true);
645
+ this.#resetStreamState();
741
646
  if (host) host.register(id, this);
742
647
  }
743
- rebase() {
744
- this.#version = undefined;
745
- }
746
- have() {
747
- return this.#have;
748
- }
749
648
  #recordHave(key, record) {
750
- if (!this.#have || !record || record.digest === undefined) return;
751
- this.#have[key] = record.digest;
752
- if (record.holes) Object.assign(this.#have, record.holes);
649
+ tierLoads.wire?.r?.have(this, key, record);
753
650
  }
754
651
  dispose() {
755
652
  if (this.#disposed) return;
@@ -759,36 +656,33 @@ class FrameImpl {
759
656
  } = this.#options;
760
657
  if (host && id !== undefined) host.unregister(id, this);
761
658
  this.#disposed = true;
762
- if (this.#recordRefresh) {
763
- clearTimeout(this.#recordRefresh);
764
- this.#recordRefresh = null;
765
- }
659
+ liveFrames.delete(this);
660
+ this.#releaseHold();
766
661
  for (const key of [...this.#slotCleanups.keys()]) this.#runSlotCleanups(key);
767
662
  for (const key of this.#mountedSlots) this.#removeSlotRecord(key);
768
- for (const regions of this.#slotRegions.values()) disposeRegions(regions);
769
- this.#slotRegions.clear();
663
+ tierLoads.regions?.r?.unmount(this);
770
664
  this.#mountedSlots.clear();
771
665
  }
772
666
  #applyRoot(html) {
773
667
  const fragment = parseFragment(html);
774
- const parent = this.#parent();
668
+ const parent = this.#element;
775
669
  if (!this.#hasContent) {
776
- this.#clearContent();
670
+ parent.textContent = "";
777
671
  this.#claimTree(fragment);
778
- parent.insertBefore(fragment, this.#end);
672
+ parent.appendChild(fragment);
779
673
  this.#hasContent = true;
780
674
  } else {
781
675
  const claim = this.#claimTree;
782
676
  const ranges = new Map();
783
677
  this.#collectSlots(ranges);
784
678
  const grafts = [];
785
- reconcileChildren(parent, fragment, this.#start, this.#end, claim, ranges, grafts);
679
+ reconcileChildren(parent, fragment, null, null, claim, ranges, grafts);
786
680
  if (ranges.size) for (const root of grafts) flushGrafts(root, ranges);
787
681
  }
788
682
  }
789
683
  #applyHole(marker, html) {
790
684
  if (!this.#hasContent) return false;
791
- const open = findLiveTarget(this.#firstContent(), this.#end, n => n.nodeType === COMMENT_NODE && n.data === marker);
685
+ const open = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === COMMENT_NODE && n.data === marker);
792
686
  if (!open) return false;
793
687
  const close = rangeClose(open, "lh:/" + marker.slice(3));
794
688
  if (!close) {
@@ -802,15 +696,19 @@ class FrameImpl {
802
696
  }
803
697
  #applyAttrs(addr, text, removed) {
804
698
  if (!this.#hasContent) return false;
805
- const el = findLiveTarget(this.#firstContent(), this.#end, n => n.nodeType === ELEMENT_NODE && n.getAttribute("data-lha") === addr);
699
+ const el = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === ELEMENT_NODE && n.getAttribute("data-lha") === addr);
806
700
  if (!el) return false;
807
701
  const parsed = parseFragment(`<i${text}></i>`).firstChild;
808
702
  const keepOpen = preservesOpen(el);
703
+ const owned = parsed ? ownedPositions(parsed) : null;
809
704
  const current = el.attributes;
810
705
  for (let i = current.length - 1; i >= 0; i--) {
811
706
  const name = current[i].name;
812
707
  if (name === "data-lha" || keepOpen && name === "open") continue;
813
- if (!parsed || !parsed.hasAttribute(name)) el.removeAttribute(name);
708
+ if (!parsed || !parsed.hasAttribute(name)) {
709
+ if (applyOwned(el, name, "", owned) !== undefined) continue;
710
+ el.removeAttribute(name);
711
+ }
814
712
  }
815
713
  if (parsed) {
816
714
  for (let i = 0; i < parsed.attributes.length; i++) {
@@ -819,75 +717,77 @@ class FrameImpl {
819
717
  value
820
718
  } = parsed.attributes[i];
821
719
  if (keepOpen && name === "open") continue;
720
+ if (applyOwned(el, name, value, owned) !== undefined) continue;
822
721
  if (el.getAttribute(name) !== value) el.setAttribute(name, value);
823
722
  }
824
723
  }
825
- if (removed) for (const name of removed) if (!(keepOpen && name === "open")) el.removeAttribute(name);
724
+ if (removed) for (const name of removed) {
725
+ if (keepOpen && name === "open") continue;
726
+ if (applyOwned(el, name, "", owned) !== undefined) continue;
727
+ el.removeAttribute(name);
728
+ }
826
729
  return true;
827
730
  }
828
- #clearContent() {
829
- removeUntil(this.#parent(), this.#firstContent(), this.#end);
830
- }
831
731
  #claimContent() {
832
- let n = this.#firstContent();
833
- while (n && n !== this.#end) {
834
- this.#claimTree(n);
835
- n = n.nextSibling;
732
+ for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n);
733
+ }
734
+ #revealSegments(root) {
735
+ const version = this.#version;
736
+ for (const key in this.#store) {
737
+ const record = this.#store[key];
738
+ const name = segmentName(key);
739
+ if (name === null || !record || this.#appliedHoles.get(key) === record) continue;
740
+ if (this.#segmentReady(name, root)) {
741
+ this.#appliedHoles.set(key, record);
742
+ this.#revealSegment(name, root);
743
+ this.#applied(version, "reveal");
744
+ }
745
+ }
746
+ for (const key in this.#store) {
747
+ const m = /^seg:([^:]+):fallback$/.exec(key);
748
+ if (!m || this.#appliedHoles.has(key) || this.#appliedHoles.has(`seg:${m[1]}`)) continue;
749
+ if (this.#showFallback(m[1], root)) {
750
+ this.#appliedHoles.set(key, this.#store[key]);
751
+ this.#applied(version, "reveal");
752
+ }
836
753
  }
837
754
  }
838
- #segmentReady(name) {
755
+ #segmentReady(name, root) {
839
756
  const content = this.#store[`seg:${name}`];
840
757
  if (!content || content.kind !== "html") return false;
841
758
  if (!this.#store[`seg:${name}:reveal`]) return false;
842
759
  const assets = this.#store[`seg:${name}:assets`];
843
- if (assets && assets.styles) {
844
- let ready = true;
845
- for (const entry of assets.styles) ready = ensureStylesheet(entry, this.#styleFlush) && ready;
846
- if (!ready) return false;
847
- }
848
- if (!this.#findPlaceholder(name)) return false;
849
- return true;
760
+ if (assets && (assets.styles || assets.inlineStyles) && !tierReady("assets")?.gate(assets.styles || [], this)) return false;
761
+ return !!this.#findPlaceholder(name, root);
850
762
  }
851
- #revealSegment(name) {
852
- const tpl = this.#findPlaceholder(name);
763
+ #revealSegment(name, root) {
764
+ const tpl = this.#findPlaceholder(name, root);
853
765
  if (!tpl) return;
854
- const assets = this.#store[`seg:${name}:assets`];
855
- if (assets && assets.inlineStyles) applyInlineStyles(assets.inlineStyles);
856
766
  const content = this.#store[`seg:${name}`];
857
767
  const closing = rangeClose(tpl, placeholderId(name));
858
768
  if (!closing) {
859
- console.error(`Frame fragment placeholder "${name}" is missing its closing comment ` + `(<!--${placeholderId(name)}-->); revealed content will be appended at the end of ` + `its parent instead of in place. Likely an HTML-rewriting layer stripped the ` + `comment, or invalid nesting split the placeholder range.`, tpl);
860
- }
861
- const parent = tpl.parentNode;
862
- removeUntil(parent, tpl.nextSibling, closing);
863
- if (this.#options.reveal) {
864
- const fallbackFrag = tpl.content.cloneNode(true);
865
- this.#claimTree(fallbackFrag);
866
- this.#options.reveal({
867
- before: closing,
868
- fallback: [...fallbackFrag.childNodes],
869
- content: () => {
870
- const materialized = this.#materialize(content);
871
- this.#syncSlots(materialized);
872
- this.#claimTree(materialized);
873
- return materialized;
874
- }
875
- });
876
- tpl.remove();
877
- this.#revealed.add(name);
878
- this.#recordHave(name, content);
769
+ console.error(`Frame fragment placeholder "${name}" is missing its closing comment ` + `(<!--${placeholderId(name)}-->); the segment is not revealed. Likely an ` + `HTML-rewriting layer stripped the comment, or invalid nesting split the ` + `placeholder range.`, tpl);
879
770
  return;
880
771
  }
881
- const materialized = this.#materialize(content);
882
- this.#claimTree(materialized);
883
- parent.insertBefore(materialized, closing);
772
+ removeUntil(tpl.parentNode, tpl.nextSibling, closing);
773
+ const fallbackFrag = tpl.content.cloneNode(true);
774
+ this.#claimTree(fallbackFrag);
775
+ (this.#options.reveal || revealAtOnce)({
776
+ before: closing,
777
+ fallback: [...fallbackFrag.childNodes],
778
+ content: () => {
779
+ const materialized = this.#materialize(content);
780
+ this.#syncSlots(materialized);
781
+ this.#claimTree(materialized);
782
+ this.#revealSegments(materialized);
783
+ return materialized;
784
+ }
785
+ });
884
786
  tpl.remove();
885
- closing && closing.remove();
886
- this.#revealed.add(name);
887
787
  this.#recordHave(name, content);
888
788
  }
889
- #showFallback(name) {
890
- const tpl = this.#findPlaceholder(name);
789
+ #showFallback(name, root) {
790
+ const tpl = this.#findPlaceholder(name, root);
891
791
  if (!tpl) return false;
892
792
  const closing = rangeClose(tpl, placeholderId(name));
893
793
  if (!closing) return false;
@@ -901,13 +801,13 @@ class FrameImpl {
901
801
  }
902
802
  }
903
803
  function createFrame(boundary, options) {
904
- return new FrameImpl(boundary, null, null, options);
804
+ return new FrameImpl(boundary, options);
905
805
  }
906
806
  const FRAME_TAG = "solid-frame";
907
807
  const FRAME_ID_ATTR = "data-fid";
908
808
  function createFrameElement(options) {
909
809
  const el = makeFrameElement(options.id);
910
- const frame = new FrameImpl(el, null, null, options);
810
+ const frame = new FrameImpl(el, options);
911
811
  return {
912
812
  element: el,
913
813
  frame,
@@ -930,23 +830,16 @@ function segmentName(key) {
930
830
  const m = /^seg:([^:]+)$/.exec(key);
931
831
  return m ? m[1] : null;
932
832
  }
933
- function isAsyncLike(v) {
934
- return !!v && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
935
- }
936
833
  function propOf(occurrence) {
937
834
  const hash = occurrence.indexOf("#");
938
835
  return hash === -1 ? occurrence : occurrence.slice(0, hash);
939
836
  }
940
- function isDataRef(value) {
941
- return !!value && typeof value.$ref === "string";
942
- }
943
- function isFrameRef(value) {
944
- return !!value && typeof value.$frame === "string";
837
+ function isCalled(occurrence) {
838
+ return occurrence.indexOf("#") !== -1;
945
839
  }
946
- function disposeRegions(regions) {
947
- for (const {
948
- frame
949
- } of regions.values()) frame?.dispose();
840
+ function revealAtOnce(seam) {
841
+ seam.before.parentNode.insertBefore(seam.content(), seam.before);
842
+ seam.before.remove();
950
843
  }
951
844
  function removeUntil(parent, n, stop) {
952
845
  while (n && n !== stop) {
@@ -960,80 +853,6 @@ function parseFragment(html) {
960
853
  template.innerHTML = html;
961
854
  return template.content;
962
855
  }
963
- const PRELOAD_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
964
- function qualifierValue(name, value) {
965
- if (value == null) return null;
966
- if (name === "imagesrcset" || name === "imagesizes") return value === "" ? null : value;
967
- if (name === "as") return value.replace(/[A-Z]/g, c => String.fromCharCode(c.charCodeAt(0) + 32));
968
- if (name !== "crossorigin") return value;
969
- return value.length === 15 && value.toLowerCase() === "use-credentials" ? "use-credentials" : "anonymous";
970
- }
971
- function findHeadElement(selector, attr, value, qualifiers) {
972
- candidate: for (const node of document.head.querySelectorAll(selector)) {
973
- if (node.getAttribute(attr) !== value) continue;
974
- if (!qualifiers) return node;
975
- for (let i = 0; i < PRELOAD_QUALIFIERS.length; i++) {
976
- const name = PRELOAD_QUALIFIERS[i];
977
- if (qualifierValue(name, node.getAttribute(name)) !== qualifierValue(name, qualifiers[name] ?? null)) continue candidate;
978
- }
979
- return node;
980
- }
981
- return null;
982
- }
983
- function ensurePreload(entry) {
984
- const attrs = entry.attrs;
985
- const href = entry.href;
986
- if (findHeadElement('link[rel="preload"]', "href", href || null, attrs)) return;
987
- const link = document.createElement("link");
988
- link.rel = "preload";
989
- for (const name in attrs) link.setAttribute(name, attrs[name]);
990
- if (href) link.setAttribute("href", href);
991
- document.head.appendChild(link);
992
- }
993
- function ensureStylesheet(entry, onSettle) {
994
- const href = typeof entry === "string" ? entry : entry.href;
995
- let link = findHeadElement('link[rel="stylesheet"]', "href", href);
996
- if (!link) {
997
- link = document.createElement("link");
998
- link.rel = "stylesheet";
999
- if (typeof entry !== "string" && entry.attrs) {
1000
- for (const name in entry.attrs) link.setAttribute(name, entry.attrs[name]);
1001
- }
1002
- link.href = href;
1003
- const waiters = new Set();
1004
- link._$frWaiters = waiters;
1005
- const settle = () => {
1006
- link._$frWaiters = null;
1007
- for (const fn of waiters) fn();
1008
- };
1009
- link.addEventListener("load", settle);
1010
- link.addEventListener("error", settle);
1011
- document.head.appendChild(link);
1012
- }
1013
- const waiters = link._$frWaiters;
1014
- if (waiters == null) return true;
1015
- waiters.add(onSettle);
1016
- return false;
1017
- }
1018
- function ensureModulePreload(href) {
1019
- if (findHeadElement('link[rel="modulepreload"]', "href", href)) return;
1020
- const link = document.createElement("link");
1021
- link.rel = "modulepreload";
1022
- link.href = href;
1023
- document.head.appendChild(link);
1024
- }
1025
- function applyInlineStyles(inlineStyles) {
1026
- for (const entry of inlineStyles) {
1027
- if (findHeadElement("style[data-asset]", "data-asset", entry.id)) continue;
1028
- const el = document.createElement("style");
1029
- el.setAttribute("data-asset", entry.id);
1030
- if (entry.attrs) {
1031
- for (const name in entry.attrs) el.setAttribute(name, entry.attrs[name]);
1032
- }
1033
- el.textContent = entry.content || "";
1034
- document.head.appendChild(el);
1035
- }
1036
- }
1037
856
  function isPlaceholderStart(node, id) {
1038
857
  return node.tagName === "TEMPLATE" && node.id === id;
1039
858
  }
@@ -1070,7 +889,7 @@ function findPlaceholder(n, end, id) {
1070
889
  }
1071
890
  return null;
1072
891
  }
1073
- function collectSlots(n, end, out) {
892
+ function collectSlots(n, end, out, elements) {
1074
893
  while (n && n !== end) {
1075
894
  const id = slotStartId(n);
1076
895
  if (id !== null) {
@@ -1079,32 +898,19 @@ function collectSlots(n, end, out) {
1079
898
  n = afterRange(n, id);
1080
899
  continue;
1081
900
  }
1082
- if (n.nodeType === ELEMENT_NODE && !isFrameElement(n)) collectSlots(n.firstChild, null, out);
1083
- n = n.nextSibling;
1084
- }
1085
- }
1086
- function collectRegionElements(node, regions) {
1087
- if (node.nodeType !== ELEMENT_NODE) return;
1088
- if (isFrameElement(node)) {
1089
- const childId = node.getAttribute(FRAME_ID_ATTR);
1090
- if (childId && childId.includes(".")) {
1091
- const argKey = childId.slice(childId.lastIndexOf(".") + 1);
1092
- if (!regions.has(argKey)) {
1093
- regions.set(argKey, {
1094
- childId,
1095
- element: node,
1096
- frame: undefined,
1097
- adopt: true
1098
- });
901
+ if (elements !== undefined && isTextStart(n)) {
902
+ const B = tierLoads.bind?.r;
903
+ B ? B.text(n, elements) : elements.b = true;
904
+ }
905
+ if (n.nodeType === ELEMENT_NODE && !isFrameElement(n)) {
906
+ if (elements !== undefined && n.hasAttributes()) {
907
+ const B = tierLoads.bind?.r;
908
+ B ? B.positions(n, elements) : hasSlotMarker(n) && (elements.b = true);
1099
909
  }
910
+ collectSlots(n.firstChild, null, out, elements);
1100
911
  }
1101
- return;
912
+ n = n.nextSibling;
1102
913
  }
1103
- for (let c = node.firstChild; c; c = c.nextSibling) collectRegionElements(c, regions);
1104
- }
1105
- function renameRegion(entry, childId) {
1106
- entry.childId = childId;
1107
- if (entry.frame) entry.frame.rebind(childId);else entry.element.setAttribute(FRAME_ID_ATTR, childId);
1108
914
  }
1109
915
  function eachInRange(start, key, cb) {
1110
916
  const end = slotEnd(key);
@@ -1116,28 +922,6 @@ function eachInRange(start, key, cb) {
1116
922
  }
1117
923
  return n;
1118
924
  }
1119
- function clearStreamRecords(records, root) {
1120
- for (const key in records) {
1121
- if (/^(seg|hole|attr):/.test(key) || key === ":error" || root && key === "") {
1122
- delete records[key];
1123
- }
1124
- }
1125
- }
1126
- function argsEquivalent(a, b) {
1127
- if (a === b) return true;
1128
- if (!a || !b) return false;
1129
- const ka = Object.keys(a);
1130
- const kb = Object.keys(b);
1131
- if (ka.length !== kb.length) return false;
1132
- for (const key of ka) {
1133
- const va = a[key];
1134
- const vb = b[key];
1135
- if (va === vb) continue;
1136
- if (isFrameRef(va) && va.$frame === vb?.$frame) continue;
1137
- return false;
1138
- }
1139
- return true;
1140
- }
1141
925
  function slotStartId(node) {
1142
926
  if (node.nodeType !== COMMENT_NODE) return null;
1143
927
  const m = SLOT_START.exec(node.data);
@@ -1157,15 +941,26 @@ function preservesOpen(el) {
1157
941
  const t = el.tagName;
1158
942
  return t === "DETAILS" || t === "DIALOG";
1159
943
  }
944
+ const ownedPositions = el => {
945
+ const B = tierLoads.bind?.r;
946
+ return B ? B.owned(el) : null;
947
+ };
948
+ const applyOwned = (oldEl, name, value, owned) => owned === null ? undefined : tierLoads.bind.r.apply(oldEl, name, value, owned);
1160
949
  function morphAttributes(oldEl, newEl, claim) {
1161
950
  let reclaim = false;
1162
951
  let changed = false;
1163
952
  const keepOpen = preservesOpen(oldEl);
953
+ const owned = ownedPositions(newEl);
1164
954
  const oldAttrs = oldEl.attributes;
1165
955
  for (let i = oldAttrs.length - 1; i >= 0; i--) {
1166
956
  const name = oldAttrs[i].name;
1167
957
  if (keepOpen && name === "open") continue;
1168
958
  if (!newEl.hasAttribute(name)) {
959
+ const handled = applyOwned(oldEl, name, "", owned);
960
+ if (handled !== undefined) {
961
+ changed = handled || changed;
962
+ continue;
963
+ }
1169
964
  oldEl.removeAttribute(name);
1170
965
  changed = true;
1171
966
  reclaim ||= claimedAttr(name);
@@ -1174,11 +969,17 @@ function morphAttributes(oldEl, newEl, claim) {
1174
969
  const newAttrs = newEl.attributes;
1175
970
  for (let i = 0; i < newAttrs.length; i++) {
1176
971
  const attr = newAttrs[i];
1177
- if (keepOpen && attr.name === "open") continue;
1178
- if (oldEl.getAttribute(attr.name) !== attr.value) {
1179
- oldEl.setAttribute(attr.name, attr.value);
972
+ const name = attr.name;
973
+ if (keepOpen && name === "open") continue;
974
+ const handled = applyOwned(oldEl, name, attr.value, owned);
975
+ if (handled !== undefined) {
976
+ changed = handled || changed;
977
+ continue;
978
+ }
979
+ if (oldEl.getAttribute(name) !== attr.value) {
980
+ oldEl.setAttribute(name, attr.value);
1180
981
  changed = true;
1181
- reclaim ||= claimedAttr(attr.name);
982
+ reclaim ||= claimedAttr(name);
1182
983
  }
1183
984
  }
1184
985
  if (claim && (reclaim || changed && oldEl.matches(CLAIMED_ELEMENTS))) claim(oldEl, true);
@@ -1192,8 +993,9 @@ function morphNode(oldNode, newNode, claim, ranges, grafts) {
1192
993
  oldNode.data = newNode.data;
1193
994
  }
1194
995
  }
1195
- function afterRange(start, id) {
1196
- const end = slotEnd(id);
996
+ const afterRange = (start, id) => afterMarker(start, slotEnd(id));
997
+ const afterText = start => afterMarker(start, SLOT_TEXT_END);
998
+ function afterMarker(start, end) {
1197
999
  let n = start.nextSibling;
1198
1000
  while (n) {
1199
1001
  if (n.nodeType === COMMENT_NODE && n.data === end) return n.nextSibling;
@@ -1201,6 +1003,29 @@ function afterRange(start, id) {
1201
1003
  }
1202
1004
  return null;
1203
1005
  }
1006
+ let slotOrphans;
1007
+ function devSlotOrphan(frame, occurrence, consumers, why) {
1008
+ let seen = (slotOrphans ??= new WeakMap()).get(frame);
1009
+ if (!seen) slotOrphans.set(frame, seen = new Set());
1010
+ if (seen.has(occurrence)) return;
1011
+ seen.add(occurrence);
1012
+ const prop = propOf(occurrence);
1013
+ const positions = new Set();
1014
+ for (const c of consumers) for (const p of c.positions) positions.add(p.pos);
1015
+ const where = `${consumers.length} element${consumers.length === 1 ? "" : "s"} (positions: ${[...positions].join(", ")})`;
1016
+ DEV.report(OBSERVE.diagnostics.emit({
1017
+ code: "BINDING_SLOT_POSITION",
1018
+ kind: "render",
1019
+ severity: "warn",
1020
+ message: why === "fill" ? `[BINDING_SLOT_POSITION] Server markup binds \`${occurrence}\` at ${where}, but no client fill ` + `resolves for slot \`${prop}\` — those positions never bind and the elements are inert. ` + `Pass \`${prop}\` to the server component on the client (a function returning the object the ` + `markup reads), or check that the prop name matches on both sides.` : `[BINDING_SLOT_POSITION] Server markup binds \`${occurrence}\` at ${where}, but no args record ` + `for it arrived and none can — the fill mounts with empty args. A called slot always emits its ` + `record ahead of the markup that reads it, so this is the frame protocol out of step, not the fill: ` + `a client and server from different builds (a stale dev prebundle, a cached asset), or a runtime ` + `bug minting the marker and the record under different ids.`,
1021
+ data: {
1022
+ reason: "orphan",
1023
+ why,
1024
+ occurrence,
1025
+ elements: consumers.map(c => c.element)
1026
+ }
1027
+ }, null));
1028
+ }
1204
1029
  function devCheckRange(start, id) {
1205
1030
  const end = slotEnd(id);
1206
1031
  let n = start.nextSibling;
@@ -1270,6 +1095,11 @@ function reconcileChildren(parent, source, boundStart = null, boundEnd = null, c
1270
1095
  const nextNew = newChild.nextSibling;
1271
1096
  const pid = slotStartId(newChild);
1272
1097
  const old = oldChild === boundEnd ? null : oldChild;
1098
+ if (old && isTextStart(newChild) && old.nodeType === COMMENT_NODE && old.data === newChild.data) {
1099
+ oldChild = afterText(old);
1100
+ newChild = afterText(newChild);
1101
+ continue;
1102
+ }
1273
1103
  if (pid !== null) {
1274
1104
  if (old && slotStartId(old) === pid) {
1275
1105
  oldChild = afterRange(old, pid);
@@ -1446,18 +1276,7 @@ function observeFrameApply(response) {
1446
1276
  }
1447
1277
 
1448
1278
  const FRAME_STREAM_HEADER = "X-Frame-Stream";
1449
- const FRAME_HAVE_HEADER = "X-Frame-Have";
1450
- const FRAME_HAVE_BUDGET = 4096;
1451
- function encodeHaveList(have) {
1452
- let out = "";
1453
- for (const key in have) {
1454
- const digest = have[key];
1455
- if (typeof digest !== "string") continue;
1456
- out += (out ? "," : "") + key + "=" + digest;
1457
- if (out.length > FRAME_HAVE_BUDGET) return undefined;
1458
- }
1459
- return out || undefined;
1460
- }
1279
+ const FRAME_TIERS_HEADER = "X-Frame-Tiers";
1461
1280
  function isFrameStreamResponse(response) {
1462
1281
  return response.headers.has(FRAME_STREAM_HEADER);
1463
1282
  }
@@ -1477,26 +1296,12 @@ async function observedApplyFrameResponse(response, host, options = {}) {
1477
1296
  }
1478
1297
  function applyFrames(response, host, options = {}, observation) {
1479
1298
  const rootId = response.headers.get(FRAME_STREAM_HEADER) ?? "";
1299
+ response.headers.get(FRAME_TIERS_HEADER)?.split(",").forEach(prepareTier);
1480
1300
  const as = options.as;
1481
1301
  const version = options.version;
1482
1302
  const perFrame = typeof version === "function" ? new Map() : null;
1483
- const wire = options[LIVE_WIRE];
1484
- const connection = wire && wire.connection;
1485
- const reader = wire && isEventStream(response) ? wire.open(response.body) : new ChunkReader(response.body);
1303
+ const reader = options[LIVE_WIRE] || new ChunkReader(response.body);
1486
1304
  const open = new Map();
1487
- let cancelled;
1488
- let resolveEnd;
1489
- if (connection) {
1490
- connection.ended = new Promise(resolve => resolveEnd = resolve);
1491
- connection.cancel = reason => {
1492
- if (cancelled !== undefined) return;
1493
- cancelled = reason;
1494
- try {
1495
- const r = reader.cancel && reader.cancel(reason);
1496
- if (r && typeof r.then === "function") r.then(undefined, () => {});
1497
- } catch {}
1498
- };
1499
- }
1500
1305
  const errorRecord = (id, error) => ({
1501
1306
  type: "error",
1502
1307
  id,
@@ -1521,26 +1326,15 @@ function applyFrames(response, host, options = {}, observation) {
1521
1326
  } else if (version !== undefined) chunk.version = version;
1522
1327
  if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (chunk.type === "complete" || chunk.type === "error" && !chunk.key) open.delete(chunk.id);
1523
1328
  if (observation) observation.chunk(chunk, wireId);
1524
- if (chunk.type === "data" && host.prepareData) await host.prepareData();
1329
+ const needs = chunk.tiers?.map(prepareTier) || [];
1330
+ if (chunk.type === "data" || chunk.type === "slot" && Object.values(chunk.args).some(v => v && v.$ref)) await Promise.all([host.prepareData?.(), ...needs]);
1525
1331
  host.apply(chunk);
1526
1332
  }
1527
1333
  result = await reader.next();
1528
1334
  }
1529
1335
  };
1530
1336
  const end = error => {
1531
- const dead = error || cancelled || new Error("Frame stream ended before the frame completed.");
1532
- const sweep = () => {
1533
- for (const id of open.keys()) host.apply(errorRecord(id, dead));
1534
- };
1535
- if (connection) {
1536
- connection.done = true;
1537
- resolveEnd({
1538
- open: open.size,
1539
- error: dead,
1540
- sweep,
1541
- close: () => {}
1542
- });
1543
- } else if (error === undefined) sweep();
1337
+ if (error === undefined) for (const id of open.keys()) host.apply(errorRecord(id, new Error("Frame stream ended before the frame completed.")));
1544
1338
  };
1545
1339
  return drain().then(() => {
1546
1340
  end(undefined);
@@ -1553,7 +1347,19 @@ function applyFrames(response, host, options = {}, observation) {
1553
1347
  const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("solid.server-component");
1554
1348
  const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("solid.server-component-address");
1555
1349
  const COMPONENT_BINDING = /*#__PURE__*/Symbol.for("solid.component-binding");
1350
+ const CONTENT_TOKEN = "\u0000";
1351
+ function contentAddress(token) {
1352
+ return token.split(CONTENT_TOKEN)[0];
1353
+ }
1354
+ const stagedContent = {
1355
+ preview() {},
1356
+ commit() {}
1357
+ };
1556
1358
  let resolveServerComponent;
1359
+ const calls = new Map();
1360
+ function callFor(address) {
1361
+ return calls.get(address);
1362
+ }
1557
1363
  function parseServerComponent(value, ctx) {
1558
1364
  return {
1559
1365
  id: ctx.parse(value[SERVER_COMPONENT]),
@@ -1599,7 +1405,6 @@ function flightCodec(codec) {
1599
1405
  function createServerComponentHandler({
1600
1406
  host,
1601
1407
  component,
1602
- onStream,
1603
1408
  intercept
1604
1409
  }) {
1605
1410
  const byFn = new Map();
@@ -1622,46 +1427,78 @@ function createServerComponentHandler({
1622
1427
  }
1623
1428
  return binding;
1624
1429
  };
1625
- resolveServerComponent = (id, address) => bindingFor(address, id);
1430
+ const staged = new Map();
1431
+ const latest = new Map();
1432
+ const stage = (address, base, version) => {
1433
+ if (!base) return undefined;
1434
+ let committed = false;
1435
+ const chunks = [];
1436
+ const token = address + CONTENT_TOKEN + version;
1437
+ const entry = {
1438
+ token,
1439
+ prepareData: host.prepareData,
1440
+ apply(chunk) {
1441
+ if (committed || chunk.type === "data") host.apply(chunk);else chunks.push(chunk);
1442
+ },
1443
+ preview() {
1444
+ if (host.preview) for (const chunk of chunks) host.preview(chunk);
1445
+ },
1446
+ commit() {
1447
+ committed = true;
1448
+ staged.delete(address);
1449
+ for (const chunk of chunks) host.apply(chunk);
1450
+ }
1451
+ };
1452
+ staged.set(address, entry);
1453
+ const comp = base[COMPONENT_BINDING].component;
1454
+ const binding = props => comp(props, () => token);
1455
+ binding[COMPONENT_BINDING] = {
1456
+ component: comp,
1457
+ address: token
1458
+ };
1459
+ latest.set(address, binding);
1460
+ return entry;
1461
+ };
1462
+ const settled = (address, binding) => latest.get(address) || binding;
1463
+ const showing = address => {
1464
+ const frame = host.get(address);
1465
+ return frame !== undefined && frame.error === undefined;
1466
+ };
1467
+ const named = (token, half) => {
1468
+ const entry = staged.get(contentAddress(token));
1469
+ if (entry && entry.token === token) entry[half]();
1470
+ };
1471
+ stagedContent.preview = token => named(token, "preview");
1472
+ stagedContent.commit = token => named(token, "commit");
1473
+ resolveServerComponent = (id, address) => settled(address, bindingFor(address, id));
1626
1474
  const versions = new Map();
1627
- const connections = new Map();
1628
1475
  const bump = address => {
1629
1476
  const version = (versions.get(address) || 0) + 1;
1630
1477
  versions.set(address, version);
1631
- const connection = connections.get(address);
1632
- if (connection) {
1633
- connections.delete(address);
1634
- connection.cancel(new Error("Superseded by a newer response for the address."));
1635
- }
1478
+ staged.delete(address);
1479
+ tierLoads.wire?.r?.cancel(host, address);
1636
1480
  return version;
1637
1481
  };
1638
- const hold = (address, connection) => {
1639
- connections.set(address, connection);
1640
- connection.ended.then(() => {
1641
- if (connections.get(address) === connection) connections.delete(address);
1642
- });
1643
- };
1482
+ const begin = (address, version) => host.apply({
1483
+ type: "start",
1484
+ id: address,
1485
+ version
1486
+ });
1644
1487
  return {
1645
1488
  intercept: intercept && (info => {
1646
1489
  const hit = intercept(info);
1647
1490
  if (hit === undefined) return undefined;
1648
- const binding = () => bindingFor(frameAddress(info.id, info.args), info.id);
1491
+ const address = frameAddress(info.id, info.args);
1492
+ if (!info.meta?.live) calls.set(address, info);
1493
+ const binding = () => bindingFor(address, info.id);
1649
1494
  if (typeof hit.then === "function") return hit.then(landed => landed ? binding() : undefined);
1650
1495
  return binding();
1651
1496
  }),
1497
+ onLive() {
1498
+ prepareTier("wire");
1499
+ },
1652
1500
  resume(info) {
1653
- const address = frameAddress(info.id, info.args);
1654
- const version = versions.get(address);
1655
- const frame = host.get(address);
1656
- const have = frame && frame.have ? frame.have() : undefined;
1657
- if (version === undefined && !have) return undefined;
1658
- const encoded = have && encodeHaveList(have);
1659
- return {
1660
- position: String(version || 0),
1661
- headers: encoded ? {
1662
- [FRAME_HAVE_HEADER]: encoded
1663
- } : undefined
1664
- };
1501
+ return tierLoads.wire?.r?.resume(host, info, versions);
1665
1502
  },
1666
1503
  handle(response, ctx) {
1667
1504
  if (!isFrameStreamResponse(response)) return undefined;
@@ -1671,31 +1508,16 @@ function createServerComponentHandler({
1671
1508
  return applyFlightResponse(response, address, binding);
1672
1509
  }
1673
1510
  const wire = ctx[LIVE_WIRE];
1674
- const connection = wire && wire.connection;
1675
- if (connection) {
1676
- const current = connections.get(address);
1677
- if (current && !current.done) {
1678
- connection.ended = current.ended;
1679
- const body = response.body;
1680
- if (body) body.cancel().catch(() => {});
1681
- return binding;
1682
- }
1683
- const version = bump(address);
1684
- if (onStream) onStream(address, version, response);
1685
- applyFrameResponse(response, host, {
1686
- as: address,
1687
- version,
1688
- [LIVE_WIRE]: wire
1689
- }).catch(() => {});
1690
- hold(address, connection);
1691
- return binding;
1692
- }
1511
+ if (wire) return prepareTier("wire").then(() => tierLoads.wire.r.connect(response, wire, address, binding, host, bump, begin));
1512
+ calls.set(address, ctx);
1693
1513
  const version = bump(address);
1694
- if (onStream) onStream(address, version, response);
1695
- applyFrameResponse(response, host, {
1514
+ const entry = showing(address) ? stage(address, binding, version) : undefined;
1515
+ if (!entry) begin(address, version);
1516
+ const target = entry || host;
1517
+ const applied = applyFrameResponse(response, target, {
1696
1518
  as: address,
1697
1519
  version
1698
- }).catch(err => host.apply({
1520
+ }).catch(err => target.apply({
1699
1521
  type: "error",
1700
1522
  id: address,
1701
1523
  version,
@@ -1703,17 +1525,10 @@ function createServerComponentHandler({
1703
1525
  message: String(err && err.message)
1704
1526
  }
1705
1527
  }));
1706
- return binding;
1528
+ return entry ? applied.then(() => settled(address, binding)) : binding;
1707
1529
  },
1708
1530
  showing(address, functionId) {
1709
1531
  bindingFor(address, functionId);
1710
- const comp = componentFor(functionId);
1711
- if (comp && (typeof comp === "function" || typeof comp === "object") && !comp[COMPONENT_BINDING]) {
1712
- comp[COMPONENT_BINDING] = {
1713
- component: comp,
1714
- address
1715
- };
1716
- }
1717
1532
  }
1718
1533
  };
1719
1534
  async function applyFlightResponse(response, address, binding) {
@@ -1727,11 +1542,26 @@ function createServerComponentHandler({
1727
1542
  });
1728
1543
  const payload = deserializeStream(new Response(source), flightCodec(getServerFunctionsCodec()));
1729
1544
  let carried = false;
1730
- await applyFrameResponse(response, host, {
1545
+ const regions = new Map();
1546
+ const regionOf = id => {
1547
+ for (const [root, entry] of regions) if (id === root || id.startsWith(root + ".")) return entry;
1548
+ };
1549
+ const target = {
1550
+ apply: chunk => {
1551
+ const entry = regionOf(chunk.id);
1552
+ if (entry) entry.apply(chunk);else host.apply(chunk);
1553
+ },
1554
+ prepareData: host.prepareData
1555
+ };
1556
+ await applyFrameResponse(response, target, {
1731
1557
  as,
1732
1558
  version: frameId => {
1733
1559
  const version = bump(frameId);
1734
- if (onStream) onStream(frameId, version, response);
1560
+ let entry = regionOf(frameId);
1561
+ if (!entry && showing(frameId)) {
1562
+ entry = stage(frameId, frameId === as ? binding : byAddress.get(frameId), version);
1563
+ if (entry) regions.set(frameId, entry);
1564
+ }
1735
1565
  return version;
1736
1566
  },
1737
1567
  onOutcome: text => {
@@ -1746,47 +1576,16 @@ function createServerComponentHandler({
1746
1576
  if (response.headers.has(ERROR_HEADER) && !hasFlightMetadata(response)) {
1747
1577
  throw envelope.value;
1748
1578
  }
1749
- return rootId ? binding : envelope.value;
1579
+ return rootId ? settled(address, binding) : envelope.value;
1750
1580
  }
1751
1581
  }
1752
1582
 
1753
- const STATE = Symbol.for("solid.container-trace-state");
1754
- const state = globalThis[STATE] || (globalThis[STATE] = {
1755
- materialized: new WeakMap(),
1756
- materializedValues: new WeakSet()
1757
- });
1758
- function setContainerTraceMaterializer(fn) {
1759
- state.materializeTrace = fn;
1760
- }
1761
- function materialize(marker) {
1762
- let value = state.materialized.get(marker.$tr);
1763
- if (value === undefined) {
1764
- value = state.materializeTrace(marker);
1765
- state.materialized.set(marker.$tr, value);
1766
- if (value !== null && typeof value === "object") state.materializedValues.add(value);
1767
- }
1768
- return value;
1769
- }
1770
- function isMaterializedContainer(value) {
1771
- return value !== null && typeof value === "object" && state.materializedValues.has(value);
1772
- }
1773
- function isContainerTraceMarker(value) {
1774
- if (value == null || typeof value !== "object" || value.$tr == null) return false;
1775
- const tr = value.$tr;
1776
- return tr.__SEROVAL_STREAM__ === true || typeof tr[Symbol.asyncIterator] === "function";
1777
- }
1778
- function reviveContainerTraces(value) {
1779
- if (!state.materializeTrace || value == null || typeof value !== "object") return value;
1780
- if (isContainerTraceMarker(value)) return materialize(value);
1781
- if (Array.isArray(value)) {
1782
- for (let i = 0; i < value.length; i++) value[i] = reviveContainerTraces(value[i]);
1783
- } else if (Object.getPrototypeOf(value) === Object.prototype) {
1784
- for (const key of Object.keys(value)) value[key] = reviveContainerTraces(value[key]);
1785
- }
1786
- return value;
1787
- }
1788
-
1789
- setContainerTraceMaterializer(materializeContainerTrace);
1583
+ const TRACE_STATE = Symbol.for("solid.container-trace-state");
1584
+ tierLoaders.trace = () => import('@solidjs/web/frames/trace');
1585
+ tierLoaders.regions = () => import('@solidjs/web/frames/regions');
1586
+ tierLoaders.assets = () => import('@solidjs/web/frames/assets');
1587
+ tierLoaders.bind = () => import('@solidjs/web/frames/bind');
1588
+ tierLoaders.wire = () => import('@solidjs/web/frames/wire');
1790
1589
  function asyncArg(value) {
1791
1590
  return value;
1792
1591
  }
@@ -1799,117 +1598,121 @@ function loadCodec() {
1799
1598
  });
1800
1599
  }
1801
1600
  const tables = new Map();
1802
- function ensureTable(root) {
1803
- let table = tables.get(root);
1804
- if (!table && codec) tables.set(root, table = codec.createJSONDataTable());
1805
- return table;
1601
+ function tableFor(id, version, current) {
1602
+ let byVersion = tables.get(id);
1603
+ if (!byVersion) tables.set(id, byVersion = new Map());else for (const v of byVersion.keys()) if (v < current) byVersion.delete(v);
1604
+ let t = byVersion.get(version);
1605
+ if (!t && codec) byVersion.set(version, t = codec.createJSONDataTable());
1606
+ return t;
1607
+ }
1608
+ function followAddress(host, frame, binding) {
1609
+ createRenderEffect(() => {
1610
+ const token = binding();
1611
+ stagedContent.preview(token);
1612
+ return token;
1613
+ }, token => {
1614
+ stagedContent.commit(token);
1615
+ frame.rebind(contentAddress(token));
1616
+ });
1617
+ }
1618
+ function landing(host, address, value, failed) {
1619
+ let thrown = host.get(address)?.error;
1620
+ return createMemo(() => {
1621
+ failed();
1622
+ const error = host.get(address)?.error;
1623
+ if (error !== undefined && error !== thrown) {
1624
+ thrown = error;
1625
+ throw error;
1626
+ }
1627
+ const wait = host.landing(address);
1628
+ if (!wait) return value;
1629
+ const asked = error !== undefined ? reask(address) : undefined;
1630
+ return (asked ? asked.then(() => wait) : wait).then(() => value);
1631
+ });
1806
1632
  }
1807
- function tableFor(id) {
1808
- if (tables.has(id)) return ensureTable(id);
1809
- for (const root of tables.keys()) if (id.startsWith(root + ".")) return ensureTable(root);
1810
- return undefined;
1633
+ function reask(address) {
1634
+ const call = callFor(address);
1635
+ if (!call) console.error(`Server component boundary "${address}" errored, but no call is recorded for it; ` + `reset() cannot re-ask the server. (The address was written by hand, not by a call.)`);
1636
+ return call && call.retry();
1811
1637
  }
1812
- function beginStream(frameId) {
1813
- tables.set(frameId, undefined);
1638
+ function failing() {
1639
+ const [failed, setFailed] = createSignal(0, {
1640
+ ownedWrite: true
1641
+ });
1642
+ return [failed, info => info.reason === "error" && setFailed(n => n + 1)];
1814
1643
  }
1815
1644
  function getFrameHost() {
1816
1645
  if (!sharedHost) {
1817
1646
  sharedHost = createFrameHost({
1818
1647
  prepareData: loadCodec,
1819
- applyData: c => tableFor(c.id)?.apply(c),
1820
- resolve: (ref, id) => tableFor(id)?.resolve(ref),
1821
- revive: reviveContainerTraces,
1822
- isContainer: isMaterializedContainer,
1823
- delegate: delegateEvents
1648
+ applyData: (c, current) => tableFor(c.id, c.version, current)?.apply(c),
1649
+ resolve: (ref, id, version, current) => tableFor(id, version, current)?.resolve(ref),
1650
+ closeData: (id, version, error) => tables.get(id)?.get(version)?.close(error)
1824
1651
  });
1825
1652
  }
1826
1653
  return sharedHost;
1827
1654
  }
1828
- function normalizeSlotContent(value) {
1829
- while (typeof value === "function") value = value();
1830
- if (Array.isArray(value)) {
1831
- const out = [];
1832
- for (const v of value) {
1833
- const n = normalizeSlotContent(v);
1834
- Array.isArray(n) ? out.push(...n) : out.push(n);
1835
- }
1836
- return out;
1837
- }
1838
- if (value == null || typeof value === "boolean") return document.createTextNode("");
1839
- return value instanceof Node ? value : document.createTextNode(String(value));
1840
- }
1841
- function gatherClaims(el, registry) {
1842
- if (el.hasAttribute("_hk")) registry.set(el.getAttribute("_hk"), el);
1843
- if (el.hasAttribute(FRAME_ID_ATTR)) return;
1844
- for (let c = el.firstElementChild; c; c = c.nextElementSibling) gatherClaims(c, registry);
1845
- }
1846
- function hasPendingFragment(existing) {
1847
- for (const n of existing) {
1848
- if (n.nodeType !== 1) continue;
1849
- const el = n;
1850
- if (el.tagName === "TEMPLATE" && el.id.startsWith("pl-")) return true;
1851
- if (el.querySelector?.('template[id^="pl-"]')) return true;
1852
- }
1853
- return false;
1854
- }
1855
- function claimRender(prefix, existing, render) {
1655
+ function claimRender(prefix, existing, render, scope, bound) {
1856
1656
  const sc = sharedConfig;
1857
- if (!sc.getNextContextId) return render();
1858
- const registry = new Map();
1859
- for (const n of existing) {
1860
- if (n.nodeType !== 1) continue;
1861
- gatherClaims(n, registry);
1862
- }
1863
- if (!registry.size && !hasPendingFragment(existing)) return render();
1864
- const prevRegistry = sc.registry;
1865
- const prevHydrating = sc.hydrating;
1866
- const prevClaimRoots = sc.claimRoots;
1867
- if (prevRegistry) for (const key of registry.keys()) prevRegistry.delete(key);
1868
- sc.registry = registry;
1869
- sc.hydrating = true;
1657
+ if (!sc.hydrateWindow || !sc.registry) return render();
1658
+ const prevRoots = sc.claimRoots;
1870
1659
  sc.claimRoots = existing;
1871
1660
  try {
1872
1661
  return runWithOwner(createOwner({
1873
1662
  id: prefix
1874
- }), render);
1663
+ }), () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1875
1664
  } finally {
1876
- sc.registry = prevRegistry;
1877
- sc.hydrating = prevHydrating;
1878
- sc.claimRoots = prevClaimRoots;
1665
+ sc.claimRoots = prevRoots;
1879
1666
  }
1880
1667
  }
1881
1668
  function liveSlotProps(initial, ctx) {
1882
- const [args, setArgs] = createSignal(initial);
1669
+ const [args, setArgs] = createSignal(initial, {
1670
+ ownedWrite: true
1671
+ });
1883
1672
  ctx.onUpdate(next => setArgs(() => next));
1884
1673
  return slotArgsProxy(args);
1885
1674
  }
1886
- function isAsyncValue(v) {
1887
- return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
1675
+ function sameArg(a, b) {
1676
+ if (a === b) return true;
1677
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
1678
+ if (a instanceof Boxed || b instanceof Boxed) return a instanceof Boxed && b instanceof Boxed && a.c === b.c;
1679
+ if (isAsyncValue(a) || isAsyncValue(b) || a instanceof Node || b instanceof Node) return false;
1680
+ try {
1681
+ return JSON.stringify(a) === JSON.stringify(b);
1682
+ } catch {
1683
+ return false;
1684
+ }
1685
+ }
1686
+ class Boxed {
1687
+ constructor(c) {
1688
+ this.c = c;
1689
+ }
1888
1690
  }
1889
1691
  function slotArgsProxy(args) {
1890
1692
  const owner = getOwner();
1891
- const asyncReads = new Map();
1693
+ const reads = new Map();
1892
1694
  return new Proxy({}, {
1893
1695
  get: (_, key) => {
1894
- const v = args()[key];
1895
- if (isMaterializedContainer(v)) return v;
1896
- if (!isAsyncValue(v)) return v;
1897
- let read = asyncReads.get(key);
1696
+ let read = reads.get(key);
1898
1697
  if (!read) {
1899
1698
  const make = () => createMemo(() => {
1900
1699
  const raw = args()[key];
1700
+ if (globalThis[TRACE_STATE]?.materializedValues.has(raw)) return new Boxed(raw);
1901
1701
  if (raw != null && typeof raw.then === "function") {
1902
1702
  if (raw.s === 1) return raw.v;
1903
1703
  if (raw.s === 2) throw raw.v;
1904
1704
  }
1905
1705
  return raw;
1906
1706
  }, {
1907
- transparent: true
1908
- });
1707
+ transparent: true,
1708
+ equals: sameArg,
1709
+ _supersedes: true
1710
+ } );
1909
1711
  read = owner ? runWithOwner(owner, make) : make();
1910
- asyncReads.set(key, read);
1712
+ reads.set(key, read);
1911
1713
  }
1912
- return read();
1714
+ const v = read();
1715
+ return v instanceof Boxed ? v.c : v;
1913
1716
  },
1914
1717
  has: (_, key) => key in args(),
1915
1718
  ownKeys: () => Reflect.ownKeys(args()),
@@ -1919,31 +1722,44 @@ function slotArgsProxy(args) {
1919
1722
  } : undefined
1920
1723
  });
1921
1724
  }
1922
- function isReactiveContent(value) {
1923
- if (typeof value === "function") return true;
1924
- if (Array.isArray(value)) {
1925
- for (const v of value) if (isReactiveContent(v)) return true;
1926
- }
1927
- return false;
1928
- }
1929
- function slotsFor(props) {
1930
- const bindings = new Map();
1725
+ function slotsFor(props, scope) {
1931
1726
  const fillScopes = new Map();
1932
1727
  return new Proxy({}, {
1933
1728
  get(_, prop) {
1934
1729
  if (typeof prop !== "string" || !(prop in props)) return undefined;
1935
1730
  return (slotProps, ctx) => {
1936
1731
  const key = ctx && ctx.key;
1937
- const prev = key !== undefined && bindings.get(key);
1938
- if (prev) {
1939
- bindings.delete(key);
1940
- prev.dispose();
1941
- }
1942
1732
  const prevFill = key !== undefined && fillScopes.get(key);
1943
1733
  if (prevFill) {
1944
1734
  fillScopes.delete(key);
1945
1735
  prevFill.dispose();
1946
1736
  }
1737
+ if (ctx && ctx.positions) {
1738
+ const fill = props[prop];
1739
+ if (typeof fill !== "function") {
1740
+ {
1741
+ slotShapeFinding({
1742
+ reason: "fill-shape",
1743
+ occurrence: key,
1744
+ shape: typeof fill
1745
+ }, `[BINDING_SLOT_POSITION] Server markup reads slot \`${prop}\` as data (\`${key}\`), ` + `but the client prop is ${typeof fill === "object" ? "an object" : `a ${typeof fill}`}, ` + `not a function. The fill is a function of the occurrence's args returning the object ` + `the markup reads: \`${prop}={args => ({ … })}\`. Nothing binds until it is.`);
1746
+ }
1747
+ return undefined;
1748
+ }
1749
+ const owner = createOwner();
1750
+ fillScopes.set(key, owner);
1751
+ ctx.onCleanup(() => {
1752
+ if (fillScopes.get(key) === owner) fillScopes.delete(key);
1753
+ owner.dispose();
1754
+ });
1755
+ runWithOwner(owner, () => {
1756
+ const args = ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps);
1757
+ tierLoads.bind.r.bind(fill, args, ctx, `the \`${prop}\` binding-slot fill` );
1758
+ });
1759
+ return undefined;
1760
+ }
1761
+ const range = ctx && ctx.range;
1762
+ if (!range) return undefined;
1947
1763
  const fillOwner = streamInvoke ? createOwner() : null;
1948
1764
  if (fillOwner && key !== undefined && ctx) {
1949
1765
  fillScopes.set(key, fillOwner);
@@ -1952,42 +1768,31 @@ function slotsFor(props) {
1952
1768
  fillOwner.dispose();
1953
1769
  });
1954
1770
  }
1955
- const settle = out => {
1956
- const existing = ctx && ctx.existing || [];
1957
- if (existing.length) {
1958
- const list = Array.isArray(out) ? out : [out];
1959
- const inPlace = list.every(n => existing.some(e => e === n || e.nodeType === 1 && e.contains(n)));
1960
- if (inPlace) return undefined;
1961
- }
1962
- return out;
1963
- };
1964
1771
  const evaluate = () => {
1965
1772
  const v = props[prop];
1966
1773
  if (typeof v === "function" && ctx && ctx.invoked) {
1967
- return v(ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps));
1774
+ const fillProps = ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps);
1775
+ return untrack(() => v(fillProps), `the \`${prop}\` template-slot fill` );
1968
1776
  }
1969
1777
  return v;
1970
1778
  };
1971
1779
  const adopted = !!(ctx && ctx.frame && ctx.adopted && ctx.existing && ctx.existing.length);
1972
1780
  const prefix = ctx && ctx.frame ? `sc-${ctx.frame}-${ctx.key}-` : "";
1973
- const value = fillOwner ? runWithOwner(fillOwner, () => adopted ? claimRender(prefix, ctx.existing, evaluate) : evaluate()) : adopted ? claimRender(prefix, ctx.existing, evaluate) : evaluate();
1974
- if (!isReactiveContent(value)) {
1975
- return settle(normalizeSlotContent(value));
1976
- }
1977
- if (ctx && ctx.range) {
1978
- const source = value;
1979
- const owner = createOwner();
1980
- bindings.set(key, owner);
1781
+ const value = fillOwner ? runWithOwner(fillOwner, () => adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate()) : adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate();
1782
+ const owner = fillOwner || createOwner({
1783
+ transparent: true
1784
+ });
1785
+ if (!fillOwner) {
1786
+ fillScopes.set(key, owner);
1981
1787
  ctx.onCleanup(() => {
1982
- if (bindings.get(key) === owner) bindings.delete(key);
1788
+ if (fillScopes.get(key) === owner) fillScopes.delete(key);
1983
1789
  owner.dispose();
1984
1790
  });
1985
- const end = ctx.range.end;
1986
- const bind = () => insert(end.parentNode, () => typeof source === "function" ? source() : source, end, [...ctx.existing]);
1987
- runWithOwner(owner, () => adopted ? claimRender(prefix, ctx.existing, bind) : bind());
1988
- return undefined;
1989
1791
  }
1990
- return settle(normalizeSlotContent(value));
1792
+ const end = range.end;
1793
+ const bind = () => insert(end.parentNode, value, end, [...ctx.existing]);
1794
+ runWithOwner(owner, () => adopted ? claimRender(prefix, ctx.existing, bind, scope, true) : bind());
1795
+ return undefined;
1991
1796
  };
1992
1797
  }
1993
1798
  });
@@ -2010,12 +1815,8 @@ function boundaryScope(owner) {
2010
1815
  function boundaryComponent(host, fnId) {
2011
1816
  return (props, binding) => {
2012
1817
  const owner = getOwner();
2013
- const id = binding ? binding() : fnId;
2014
- let applied = !tables.has(id);
2015
- let release;
2016
- const arm = () => new Promise(r => release = r);
2017
- const mountGate = applied ? undefined : arm();
2018
- let setGate;
1818
+ const id = binding ? contentAddress(binding()) : fnId;
1819
+ const [failed, onApply] = failing();
2019
1820
  const {
2020
1821
  element,
2021
1822
  frame,
@@ -2024,33 +1825,14 @@ function boundaryComponent(host, fnId) {
2024
1825
  host,
2025
1826
  id,
2026
1827
  slots: slotsFor(props),
2027
- props,
2028
1828
  ownerScope: boundaryScope(owner),
2029
1829
  reveal: revealSeam(owner),
2030
- onApply: () => {
2031
- applied = true;
2032
- if (release) {
2033
- release();
2034
- release = undefined;
2035
- }
2036
- setGate && setGate(undefined);
2037
- }
1830
+ onApply
2038
1831
  });
2039
- const [gatePromise, setGatePromise] = createSignal(applied ? undefined : mountGate);
2040
- setGate = setGatePromise;
2041
- if (binding) {
2042
- createRenderEffect(binding, (address, prev) => {
2043
- if (prev !== undefined && address !== prev && tables.has(address)) {
2044
- applied = false;
2045
- setGatePromise(arm());
2046
- }
2047
- frame.rebind(address);
2048
- });
2049
- }
2050
1832
  onCleanup(dispose);
2051
- if (applied && !binding) return element;
2052
- const gate = createMemo(() => gatePromise());
2053
- return createMemo(() => (gate(), element));
1833
+ if (!binding) return landing(host, id, element, failed);
1834
+ followAddress(host, frame, binding);
1835
+ return createMemo(() => landing(host, contentAddress(binding()), element, failed));
2054
1836
  };
2055
1837
  }
2056
1838
  const claimedBoundaries = new Set();
@@ -2065,7 +1847,7 @@ function pumpLiveChannel() {
2065
1847
  const pump = () => reader.read().then(r => {
2066
1848
  if (r.done) return;
2067
1849
  const op = r.value;
2068
- liveOps.set(`${op.type}:${op.fid || ""}:${op.key || ""}`, op);
1850
+ for (const m of op.type === "ops" ? op.ops : [op]) liveOps.set(`${m.type}:${m.fid || ""}:${m.key || ""}`, m);
2069
1851
  for (const apply of liveAppliers) apply(op);
2070
1852
  return pump();
2071
1853
  });
@@ -2075,7 +1857,7 @@ function pumpLiveChannel() {
2075
1857
  let boundaryIndex = null;
2076
1858
  const isBoundaryId = id => !id.includes(".");
2077
1859
  function indexBoundaries(root) {
2078
- root.querySelectorAll(`[${FRAME_ID_ATTR}]`).forEach(el => {
1860
+ root.querySelectorAll(FRAME_SELECTOR).forEach(el => {
2079
1861
  const key = el.getAttribute(FRAME_ID_ATTR);
2080
1862
  if (key && isBoundaryId(key) && !boundaryIndex.has(key)) boundaryIndex.set(key, el);
2081
1863
  });
@@ -2087,8 +1869,9 @@ function findBoundaryElement(id) {
2087
1869
  }
2088
1870
  return boundaryIndex.get(id);
2089
1871
  }
2090
- const boundaryWaiters = new Map();
2091
1872
  const arrivals = new Map();
1873
+ const FRAME_SELECTOR = `[${FRAME_ID_ATTR}]`;
1874
+ const disposedFrames = new WeakSet();
2092
1875
  function awaitBoundary(id) {
2093
1876
  let arrival = arrivals.get(id);
2094
1877
  if (!arrival) {
@@ -2110,18 +1893,16 @@ function installRevealHook() {
2110
1893
  const hy = globalThis._$HY;
2111
1894
  if (!hy || hy.$sc || !hy.fr) return;
2112
1895
  hy.$sc = true;
1896
+ hy.fa = pl => {
1897
+ const el = pl.closest(FRAME_SELECTOR);
1898
+ return !!el && !disposedFrames.has(el);
1899
+ };
2113
1900
  hy.fr.subscribe((_id, parent) => {
2114
1901
  if (!boundaryIndex) return;
2115
1902
  const root = parent || (typeof document !== "undefined" ? document.body : null);
2116
1903
  if (root) indexBoundaries(root);
2117
- if (!boundaryWaiters.size && !arrivals.size) return;
1904
+ if (!arrivals.size) return;
2118
1905
  const exhausted = hy.done && !hy.fr.pending();
2119
- for (const [id, notify] of boundaryWaiters) {
2120
- const el = boundaryIndex && boundaryIndex.get(id);
2121
- if (!el && !exhausted) continue;
2122
- boundaryWaiters.delete(id);
2123
- notify(el);
2124
- }
2125
1906
  for (const [id, arrival] of arrivals) {
2126
1907
  const el = boundaryIndex && boundaryIndex.get(id);
2127
1908
  if (!el && !exhausted) continue;
@@ -2135,35 +1916,31 @@ function documentBoundary(host, id, props, binding) {
2135
1916
  const claimed = claimedBoundaries.has(id);
2136
1917
  const el = !claimed ? findBoundaryElement(id) : undefined;
2137
1918
  if (el) return adoptBoundary(host, id, el, props, binding);
2138
- if (!claimed && !boundaryWaiters.has(id) && boundaryMayArrive()) {
1919
+ if (!claimed && boundaryMayArrive()) {
2139
1920
  const owner = getOwner();
2140
- const arrival = new Promise(resolve => boundaryWaiters.set(id, resolve));
2141
- onCleanup(() => boundaryWaiters.delete(id));
2142
- return createMemo(() => arrival.then(node => runWithOwner(owner, () =>
2143
- node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding))));
1921
+ let live = true;
1922
+ onCleanup(() => live = false);
1923
+ return createMemo(() => awaitBoundary(id).then(() => live && runWithOwner(owner, () => {
1924
+ const node = claimedBoundaries.has(id) ? undefined : findBoundaryElement(id);
1925
+ return node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding);
1926
+ })));
2144
1927
  }
2145
1928
  return boundaryComponent(host, id)(props, binding);
2146
1929
  }
2147
- function documentAddress(id) {
2148
- const records = globalThis._$SC?.a;
2149
- if (records) {
2150
- for (const address in records) if (records[address] === id) return address;
2151
- }
2152
- return id;
2153
- }
2154
1930
  function adoptBoundary(host, id, el, props, binding) {
2155
1931
  claimedBoundaries.add(id);
2156
- const address = binding ? binding() : documentAddress(id);
1932
+ const address = binding ? contentAddress(binding()) : id;
2157
1933
  const appliedRecords = new Set();
2158
- const claimedFragments = new Set();
2159
- const claimRegionFragments = root => {
2160
- const fr = globalThis._$HY?.fr;
2161
- if (!fr || !fr.claim) return;
1934
+ const reportedFragments = new Set();
1935
+ const reportRegionFragments = root => {
1936
+ const hy = globalThis._$HY;
1937
+ if (!hy || !hy.r) return;
2162
1938
  root.querySelectorAll('template[id^="pl-"]').forEach(tpl => {
2163
1939
  const fragId = tpl.id.slice(3);
2164
- if (claimedFragments.has(fragId)) return;
2165
- claimedFragments.add(fragId);
2166
- fr.claim(fragId);
1940
+ if (reportedFragments.has(fragId)) return;
1941
+ reportedFragments.add(fragId);
1942
+ const ref = hy.r[fragId + "_fr"];
1943
+ ref && typeof ref.then === "function" && ref.then(undefined, error => console.error(`Server <Loading> fragment "${fragId}" inside server component "${id}" rejected on ` + `the server; the frame shows what the server rendered for that outcome.`, error));
2167
1944
  });
2168
1945
  };
2169
1946
  const drainRecords = () => {
@@ -2175,13 +1952,17 @@ function adoptBoundary(host, id, el, props, binding) {
2175
1952
  if (appliedRecords.has(key)) continue;
2176
1953
  if (key.startsWith(slotPrefix)) {
2177
1954
  appliedRecords.add(key);
2178
- host.apply({
1955
+ const apply = args => host.apply({
2179
1956
  type: "slot",
2180
1957
  id: address,
2181
1958
  version: 0,
2182
1959
  key: key.slice(slotPrefix.length),
2183
- args: hy.r[key]
1960
+ args
2184
1961
  });
1962
+ const value = hy.r[key];
1963
+ if (value && typeof value.then === "function") {
1964
+ if (value.s === 1) apply(value.v);else if (value.s === 2) value.then(undefined, () => {});else value.then(apply, () => {});
1965
+ } else apply(value);
2185
1966
  } else if (key.startsWith("sc:region:")) {
2186
1967
  const childId = key.slice("sc:region:".length);
2187
1968
  if (childId.startsWith(id + ".")) {
@@ -2198,14 +1979,20 @@ function adoptBoundary(host, id, el, props, binding) {
2198
1979
  }
2199
1980
  }
2200
1981
  };
2201
- claimRegionFragments(el);
1982
+ reportRegionFragments(el);
2202
1983
  const fr = globalThis._$HY?.fr;
1984
+ let frame;
2203
1985
  const unsubscribe = fr ? fr.subscribe((_fragId, parent) => {
2204
- if (fr.claim && parent && el.contains(parent)) claimRegionFragments(parent);
1986
+ const inside = !!parent && el.contains(parent);
1987
+ inside && reportRegionFragments(parent);
2205
1988
  drainRecords();
1989
+ if (inside && frame) frame.apply({
1990
+ version: frame.version ?? 0,
1991
+ r: {}
1992
+ });
2206
1993
  }) : undefined;
2207
1994
  const applyLiveOp = op => {
2208
- if (op.type === "slot" && op.fid !== id) return;
1995
+ if (op.fid && op.fid !== id) return;
2209
1996
  host.apply({
2210
1997
  ...op,
2211
1998
  id: address,
@@ -2216,56 +2003,44 @@ function adoptBoundary(host, id, el, props, binding) {
2216
2003
  onCleanup(() => {
2217
2004
  liveAppliers.delete(applyLiveOp);
2218
2005
  unsubscribe && unsubscribe();
2219
- if (fr && fr.release) for (const fragId of claimedFragments) fr.release(fragId);
2220
2006
  });
2221
2007
  drainRecords();
2222
2008
  for (const op of liveOps.values()) applyLiveOp(op);
2223
2009
  const owner = getOwner();
2224
- let release;
2225
- let setGate;
2226
- const frame = createFrame(el, {
2010
+ const sc = sharedConfig;
2011
+ const [failed, onApply] = failing();
2012
+ frame = createFrame(el, {
2227
2013
  adopt: true,
2228
2014
  host,
2229
2015
  id: address,
2230
- slots: slotsFor(props),
2231
- props,
2016
+ slots: slotsFor(props, {
2017
+ registry: sc.registry,
2018
+ gather: sc.gather
2019
+ }),
2232
2020
  ownerScope: boundaryScope(owner),
2233
2021
  reveal: revealSeam(owner),
2234
- onApply: () => {
2235
- if (release) {
2236
- release();
2237
- release = undefined;
2238
- }
2239
- setGate && setGate(undefined);
2240
- },
2022
+ onApply,
2023
+ hold: () => sc.isHydrationInProgress?.() ? runWithOwner(owner, () => untrack(() => sc.holdBoundary("sc:" + id))) : () => {},
2241
2024
  ...{
2242
- recordsPending: () => {
2243
- if (document.readyState === "loading") return true;
2244
- const hy = globalThis._$HY;
2245
- return !!(hy && hy.fr && hy.fr.pending());
2246
- },
2247
- drainRecords,
2248
2025
  claimScope: id
2249
2026
  }
2250
2027
  });
2251
2028
  if (binding) {
2252
- const arm = () => new Promise(r => release = r);
2253
- const [gatePromise, setGatePromise] = createSignal(undefined);
2254
- setGate = setGatePromise;
2255
- const gate = createMemo(() => gatePromise());
2256
- createRenderEffect(binding, (address, prev) => {
2257
- if (prev !== undefined && address !== prev && tables.has(address)) {
2258
- setGatePromise(arm());
2259
- }
2260
- frame.rebind(address);
2261
- });
2262
- createRenderEffect(() => (gate(), undefined), () => {});
2029
+ followAddress(host, frame, binding);
2030
+ const source = createMemo(() => landing(host, contentAddress(binding()), true, failed));
2031
+ createRenderEffect(() => source()(), () => {});
2263
2032
  }
2264
- onCleanup(() => frame.dispose());
2033
+ onCleanup(() => {
2034
+ frame.dispose();
2035
+ disposedFrames.add(el);
2036
+ el.querySelectorAll(FRAME_SELECTOR).forEach(e => disposedFrames.add(e));
2037
+ });
2265
2038
  return el;
2266
2039
  }
2267
- function installServerComponents(host = getFrameHost()) {
2040
+ function installServerComponents(host = getFrameHost(), options) {
2268
2041
  const g = globalThis;
2042
+ Object.assign(tierLoaders, options?.tiers);
2043
+ g._$HY?.r?.["sc:tiers"]?.forEach(prepareTier);
2269
2044
  if (!g._$SC) {
2270
2045
  g._$SC = {
2271
2046
  c: {},
@@ -2290,7 +2065,6 @@ function installServerComponents(host = getFrameHost()) {
2290
2065
  const handler = createServerComponentHandler({
2291
2066
  host,
2292
2067
  component: fnId => g._$SC.r(fnId),
2293
- onStream: address => beginStream(address),
2294
2068
  intercept: ({
2295
2069
  id
2296
2070
  }) => {
@@ -2310,4 +2084,4 @@ function installServerComponents(host = getFrameHost()) {
2310
2084
  });
2311
2085
  }
2312
2086
 
2313
- export { FRAME_APPLIED_EVENT, FRAME_HAVE_BUDGET, FRAME_HAVE_HEADER, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isFrameStreamResponse };
2087
+ export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isAsyncValue, isFrameStreamResponse };