@solidjs/web 2.0.0-rc.15 → 2.0.0-rc.16

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 (53) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +358 -479
  3. package/dist/server.js +343 -387
  4. package/dist/server.observe.js +343 -387
  5. package/dist/web.dev.js +57 -54
  6. package/dist/web.js +47 -49
  7. package/dist/web.observe.js +57 -54
  8. package/frames/dist/client.dev.js +610 -621
  9. package/frames/dist/client.js +540 -566
  10. package/frames/dist/client.observe.js +571 -573
  11. package/frames/dist/regions.js +43 -2
  12. package/frames/dist/server.dev.js +514 -423
  13. package/frames/dist/server.js +514 -370
  14. package/frames/dist/server.observe.js +514 -370
  15. package/frames/dist/wire.js +371 -6
  16. package/package.json +11 -11
  17. package/serialization/dist/decode.js +9 -7
  18. package/serialization/dist/serialization.js +9 -7
  19. package/serialization/types/serializer-decode.d.ts +2 -2
  20. package/server-functions/dist/client.dev.js +3 -1
  21. package/server-functions/dist/client.js +1 -1
  22. package/server-functions/dist/client.observe.js +3 -1
  23. package/server-functions/dist/rich-args.js +33 -1
  24. package/server-functions/dist/server.dev.js +127 -18
  25. package/server-functions/dist/server.js +127 -18
  26. package/server-functions/dist/server.observe.js +127 -18
  27. package/skills/server-components/SKILL.md +74 -185
  28. package/types/client.d.ts +15 -5
  29. package/types/frames/assets-tier.d.ts +2 -2
  30. package/types/frames/client.d.ts +8 -3
  31. package/types/frames/frame-client.d.ts +121 -157
  32. package/types/frames/frame-morph.d.ts +28 -0
  33. package/types/frames/frame-sink.d.ts +13 -9
  34. package/types/frames/frame-transport.d.ts +30 -1
  35. package/types/frames/regions-tier.d.ts +15 -0
  36. package/types/frames/serializer-decode.d.ts +2 -2
  37. package/types/frames/server.d.ts +0 -52
  38. package/types/frames/wire-tier.d.ts +54 -1
  39. package/types/index.d.ts +2 -2
  40. package/types/jsx.d.ts +11 -5
  41. package/types/observe.d.ts +14 -7
  42. package/types/render.d.ts +3 -1
  43. package/types/response.d.ts +5 -4
  44. package/types/serializer-decode.d.ts +2 -2
  45. package/types/server-functions/argument-codec.d.ts +21 -0
  46. package/types/server-functions/client.d.ts +14 -5
  47. package/types/server-functions/server.d.ts +6 -2
  48. package/types/server-functions/shared.d.ts +19 -0
  49. package/types/server-observe.d.ts +3 -2
  50. package/types/server.d.ts +57 -76
  51. package/frames/dist/bind.dev.js +0 -326
  52. package/frames/dist/bind.js +0 -295
  53. package/types/frames/bind-tier.d.ts +0 -60
@@ -1,10 +1,9 @@
1
- import { DEV, OBSERVE, getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, createSignal, createOwner } from 'solid-js';
1
+ import { OBSERVE, DEV, getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, onHydrationEnd, createSignal, createOwner } from 'solid-js';
2
2
  import { installServerComponentHydration, insert } from '@solidjs/web';
3
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';
4
+ import { setSignalIdentities, sharedConfig, createLoadingBoundary, setWriteHook, setReadWatch, signalName, storeName } from 'solid-js/internal';
5
5
 
6
6
  const ELEMENT_NODE = 1;
7
- const TEXT_NODE = 3;
8
7
  const COMMENT_NODE = 8;
9
8
  const CLAIM_SEAM = Symbol.for("solid.element-claims");
10
9
  const CLAIMED_ELEMENTS = "a[href], form[action]";
@@ -12,119 +11,29 @@ function claimHandlers() {
12
11
  const handlers = globalThis[CLAIM_SEAM];
13
12
  return handlers !== undefined && handlers.length !== 0 ? handlers : undefined;
14
13
  }
15
- function claimNode(handlers, el) {
14
+ function claimNode(handlers, el, adopter) {
15
+ if (adopter) {
16
+ const by = adoptedBy.get(el);
17
+ if (by && liveFrames.has(by)) return;
18
+ adoptedBy.set(el, adopter);
19
+ }
16
20
  for (let i = 0; i < handlers.length; i++) handlers[i](el);
17
21
  }
18
- const claimedAttr = name => name === "href" || name === "action";
19
- function claimTree(handlers, root) {
22
+ function claimTree(handlers, root, adopter) {
20
23
  const isElement = root.nodeType === ELEMENT_NODE;
21
24
  if (!isElement && root.nodeType !== 11 ) return;
22
- if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root);
25
+ if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root, adopter);
23
26
  const found = root.querySelectorAll(CLAIMED_ELEMENTS);
24
- for (let i = 0; i < found.length; i++) claimNode(handlers, found[i]);
27
+ for (let i = 0; i < found.length; i++) claimNode(handlers, found[i], adopter);
25
28
  }
29
+ const adoptedBy = new WeakMap();
26
30
  const placeholderId = name => `pl-${name}`;
27
31
  const SLOT_START = /^slot:(.+):start$/;
28
32
  const SLOT_END = /^slot:(.+):end$/;
29
33
  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
34
  function isAsyncValue(v) {
40
35
  return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
41
36
  }
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
- }
51
- function chunkToRecords(chunk) {
52
- switch (chunk.type) {
53
- case "start":
54
- case "data":
55
- return {};
56
- case "html":
57
- return {
58
- "": {
59
- kind: "html",
60
- value: chunk.html,
61
- digest: chunk.digest,
62
- holes: chunk.holes
63
- }
64
- };
65
- case "fragment":
66
- return {
67
- [`seg:${chunk.key}`]: {
68
- kind: "html",
69
- value: chunk.html,
70
- digest: chunk.digest,
71
- holes: chunk.holes
72
- }
73
- };
74
- case "reveal":
75
- {
76
- const records = {};
77
- const gate = chunk.fallback ? "fallback" : "reveal";
78
- for (const key of chunk.keys) records[`seg:${key}:${gate}`] = true;
79
- return records;
80
- }
81
- case "assets":
82
- return {
83
- [`seg:${chunk.key}:assets`]: chunk
84
- };
85
- case "slot":
86
- return {
87
- [`slot:${chunk.key}`]: {
88
- kind: "slot",
89
- args: chunk.args
90
- }
91
- };
92
- case "hole":
93
- return {
94
- [`hole:${chunk.key}`]: {
95
- kind: "html",
96
- value: chunk.html,
97
- digest: chunk.digest,
98
- holes: chunk.holes
99
- }
100
- };
101
- case "attr":
102
- return {
103
- [`attr:${chunk.key}`]: {
104
- kind: "attrs",
105
- value: chunk.attrs,
106
- removed: chunk.removed,
107
- digest: chunk.digest
108
- }
109
- };
110
- case "ops":
111
- return Object.assign({}, ...chunk.ops.map(chunkToRecords));
112
- case "complete":
113
- return {
114
- ":complete": true,
115
- ":bound": chunk.bound
116
- };
117
- case "error":
118
- if (!chunk.key) return {
119
- ":error": chunk.error
120
- };
121
- return {
122
- [`${/^lha?:/.test(chunk.key) ? "hole" : "seg"}:${chunk.key}:error`]: chunk.error
123
- };
124
- default:
125
- return {};
126
- }
127
- }
128
37
  function createFrameHost(options = {}) {
129
38
  const frames = new Map();
130
39
  const stores = new Map();
@@ -153,15 +62,16 @@ function createFrameHost(options = {}) {
153
62
  }
154
63
  const assets = records["seg::assets"];
155
64
  const previous = assets && store.records["seg::assets"];
156
- if (!previous || previous === assets) {
157
- Object.assign(store.records, records);
158
- } else {
65
+ Object.assign(store.records, records);
66
+ if (previous && previous !== assets) {
67
+ const merged = {
68
+ ...previous
69
+ };
159
70
  for (const name in assets) {
160
71
  const values = assets[name];
161
- if (Array.isArray(values)) {
162
- previous[name] ? previous[name].push(...values) : previous[name] = values;
163
- }
72
+ if (Array.isArray(values)) merged[name] = previous[name] ? previous[name].concat(values) : values;
164
73
  }
74
+ store.records["seg::assets"] = merged;
165
75
  }
166
76
  return true;
167
77
  };
@@ -234,37 +144,51 @@ function createFrameHost(options = {}) {
234
144
  landings.delete(id);
235
145
  }
236
146
  },
237
- apply(chunk) {
238
- if (chunk.type === "data") {
239
- const store = stores.get(chunk.id);
147
+ apply(msg) {
148
+ if (msg.type === "data") {
149
+ const store = stores.get(msg.id);
240
150
  const current = store && store.version;
241
- if (store && chunk.version < current) return;
242
- options.applyData && options.applyData(chunk, current);
151
+ if (store && msg.version < current) return;
152
+ options.applyData && options.applyData(msg, current);
243
153
  return;
244
154
  }
245
- const records = chunkToRecords(chunk);
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);
155
+ let records = msg.r || {};
156
+ let slots;
157
+ for (const key in records) if (key.startsWith("slot:")) {
158
+ if (!slots) records = {
159
+ ...records
160
+ };
161
+ (slots ??= []).push(key);
162
+ records[key] = {
163
+ ...records[key]
164
+ };
251
165
  }
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.`);
166
+ const store = storeFor(msg.id);
167
+ if (!write(store, msg.version, records)) return;
168
+ if (slots) for (const key of slots) settleArgs(store, key, records[key], msg);
169
+ if (records[":bound"]) {
170
+ const bound = records[":bound"];
171
+ console.warn(`Server component "${msg.id}" kept streaming past the server's ${bound} ` + `bound and was cut off (:bound: "${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.`);
254
172
  }
255
173
  let r = records;
256
- if (chunk.type === "start") store.open = true;else if (lands(records)) {
174
+ if (msg.type === "start") {
175
+ store.open = true;
176
+ if (store.startedVersion !== msg.version) {
177
+ store.startedVersion = msg.version;
178
+ store.startedAt = msg.startedAt ?? performance.now();
179
+ }
180
+ } else if (lands(records)) {
257
181
  store.open = false;
258
182
  store.shown = r = store.records;
259
- store.shownVersion = chunk.version;
260
- const landed = landings.get(chunk.id);
183
+ store.shownVersion = msg.version;
184
+ const landed = landings.get(msg.id);
261
185
  if (landed && !(":complete" in records && ":error" in r)) {
262
- landings.delete(chunk.id);
186
+ landings.delete(msg.id);
263
187
  ":error" in records ? landed.j(records[":error"]) : landed.r();
264
188
  }
265
189
  }
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"]);
190
+ applyTo(msg.id, msg.version, r);
191
+ if (":complete" in records || ":error" in records) options.closeData && options.closeData(msg.id, msg.version, records[":error"]);
268
192
  },
269
193
  landing(id) {
270
194
  const store = stores.get(id);
@@ -274,17 +198,21 @@ function createFrameHost(options = {}) {
274
198
  if (!wait) {
275
199
  landings.set(id, wait = {});
276
200
  wait.p = new Promise((r, j) => (wait.r = r, wait.j = j));
201
+ if (store.open) OBSERVE.attribution.markFlight(wait.p, store.startedAt);
277
202
  }
278
203
  return wait.p;
279
204
  },
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);
205
+ preview(msg) {
206
+ const set = frames.get(msg.id);
207
+ if (!set || !msg.r) return;
208
+ let records;
209
+ for (const key in msg.r) if (key.startsWith("slot:")) {
210
+ const record = (records ??= {})[key] = {
211
+ ...msg.r[key]
212
+ };
213
+ settleArgs(storeFor(msg.id), key, record, msg);
214
+ }
215
+ if (records) for (const frame of set) frame.preview && frame.preview(records);
288
216
  },
289
217
  get(id) {
290
218
  const set = frames.get(id);
@@ -302,6 +230,30 @@ const FRAME_APPLIED_EVENT = "frame:applied";
302
230
  const tierLoaders = {};
303
231
  const tierLoads = {};
304
232
  const liveFrames = new Set();
233
+ let deferDriver = null;
234
+ function setDeferDriver(driver) {
235
+ deferDriver = driver;
236
+ }
237
+ let deferMountWatch = null;
238
+ function setDeferMountWatch(watch) {
239
+ deferMountWatch = watch;
240
+ }
241
+ function deferredFrames() {
242
+ return [...liveFrames].filter(f => f.deferred);
243
+ }
244
+ function releaseDeferHolds() {
245
+ for (const f of liveFrames) f.releaseDeferHold();
246
+ }
247
+ function hasSlotRange(root) {
248
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
249
+ for (let n; n = w.nextNode();) if (n.data.startsWith("slot:")) return true;
250
+ return false;
251
+ }
252
+ function liveFrameAt(node) {
253
+ let hit;
254
+ for (const f of liveFrames) if (f.el.contains(node) && (!hit || hit.el.contains(f.el))) hit = f;
255
+ return hit;
256
+ }
305
257
  function prepareTier(name) {
306
258
  let load = tierLoads[name];
307
259
  if (!load) {
@@ -317,6 +269,7 @@ function prepareTier(name) {
317
269
  }
318
270
  return load;
319
271
  }
272
+ const prepareMorph = () => liveFrames.size && prepareTier("wire");
320
273
  const tierReady = name => !tierLoaders[name] || prepareTier(name).r;
321
274
  const needsRegions = record => record.regions && !tierReady("regions");
322
275
  const carriesTrace = value => value != null && typeof value === "object" && (value.$tr != null || Object.values(value).some(carriesTrace));
@@ -327,10 +280,14 @@ class FrameImpl {
327
280
  #outer;
328
281
  #version;
329
282
  #store = Object.create(null);
283
+ #content = new Set();
330
284
  #appliedRoot;
331
285
  #appliedError;
332
286
  #hasContent = false;
333
287
  #appliedHoles = new Map();
288
+ #liveTargets = new Map();
289
+ #shows = {};
290
+ #liveMount;
334
291
  #slots;
335
292
  #mountedSlots = new Set();
336
293
  #slotCleanups = new Map();
@@ -338,11 +295,19 @@ class FrameImpl {
338
295
  #slotUpdaters = new Map();
339
296
  #hold;
340
297
  #heldRecords = new Map();
298
+ #found;
299
+ #waiting = new Set();
341
300
  #disposed = false;
342
- #claimTree = (node, direct) => {
301
+ #defers = false;
302
+ #deferred = false;
303
+ #deferFound;
304
+ #deferWaiting = false;
305
+ #deferMounted = new Map();
306
+ #deferHold;
307
+ #claimTree = (node, direct, adopter) => {
343
308
  const handlers = claimHandlers();
344
309
  if (!handlers) return;
345
- this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node));
310
+ this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node, adopter));
346
311
  };
347
312
  #scoped(fn) {
348
313
  const scope = this.#options.ownerScope;
@@ -357,11 +322,16 @@ class FrameImpl {
357
322
  if (options.adopt) {
358
323
  this.#hasContent = true;
359
324
  this.#claimContent();
325
+ this.#defers = !!deferDriver && !!(options.defer || this.#outer?.defers);
326
+ this.#deferred = this.#defers && !!(this.#slots || this.#outer) && hasSlotRange(element);
360
327
  }
361
328
  if (options.host && options.id !== undefined) {
362
329
  options.host.register(options.id, this);
363
330
  }
364
- if (options.adopt && this.#version === undefined) this.#syncSlots();
331
+ if (this.#deferred) {
332
+ this.#deferHold = options.hold?.();
333
+ deferDriver(this);
334
+ } else if (options.adopt && this.#version === undefined) this.#syncSlots();
365
335
  }
366
336
  #applied(version, reason) {
367
337
  this.#options.onApply?.({
@@ -401,8 +371,15 @@ class FrameImpl {
401
371
  this.#version = v;
402
372
  this.#resetStreamState();
403
373
  }
404
- for (const key in write.r) this.#store[key] = write.r[key];
405
- this.#flush();
374
+ let only = [];
375
+ for (const key in write.r) {
376
+ const prev = this.#store[key];
377
+ const occurrence = key.slice(5);
378
+ if (this.#deferred && prev?.kind === "slot" && !prev.pending && !this.#mountedSlots.has(occurrence)) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, prev);
379
+ this.#store[key] = write.r[key];
380
+ if (key.startsWith("slot:")) only?.push(occurrence);else this.#content.add(key), only = undefined;
381
+ }
382
+ this.#flush(only?.length ? only : undefined);
406
383
  }
407
384
  preview(records, inherited) {
408
385
  const adopted = new Set();
@@ -424,17 +401,25 @@ class FrameImpl {
424
401
  return adopted;
425
402
  }
426
403
  #resetStreamState() {
404
+ if (this.#hasContent) prepareTier("wire");
405
+ this.#found = undefined;
427
406
  this.#store = Object.create(null);
407
+ this.#content.clear();
428
408
  this.#appliedRoot = this.#appliedError = undefined;
429
409
  this.#appliedHoles.clear();
410
+ this.#liveTargets.clear();
411
+ this.#shows = {};
430
412
  }
431
- #flush() {
413
+ #flush(only) {
432
414
  if (this.#disposed) return;
433
415
  const version = this.#version;
434
416
  const root = this.#store[""];
417
+ const applied = this.#appliedRoot;
435
418
  if (root && root.kind === "html" && root !== this.#appliedRoot) {
436
- const reason = this.#hasContent ? "morph" : "materialize";
437
- this.#applyRoot(root.value);
419
+ const wire = this.#hasContent ? tierReady("wire") : null;
420
+ if (wire === undefined) return;
421
+ const reason = wire ? "morph" : "materialize";
422
+ this.#applyRoot(root.value, wire);
438
423
  this.#appliedRoot = root;
439
424
  this.#recordHave("", root);
440
425
  this.#applied(version, reason);
@@ -444,7 +429,7 @@ class FrameImpl {
444
429
  this.#appliedError = error;
445
430
  this.#applied(version, "error");
446
431
  }
447
- for (const key in this.#store) {
432
+ for (const key of this.#content) {
448
433
  const record = this.#store[key];
449
434
  if (!key.endsWith(":assets") || !record || this.#appliedHoles.get(key) === record) continue;
450
435
  const tier = tierReady("assets");
@@ -452,29 +437,58 @@ class FrameImpl {
452
437
  this.#appliedHoles.set(key, record);
453
438
  tier.apply(record);
454
439
  }
455
- this.#revealSegments();
440
+ const revealed = this.#revealSegments();
456
441
  let morphed = false;
457
- for (const key in this.#store) {
442
+ const index = {};
443
+ let wire;
444
+ for (const key of this.#content) {
458
445
  const record = this.#store[key];
459
446
  if (!record || this.#appliedHoles.get(key) === record) continue;
460
447
  if (key.startsWith("hole:")) {
461
448
  if (key.endsWith(":error")) {
462
449
  this.#appliedHoles.set(key, record);
463
450
  console.error(`Live hole ${key.slice(5, -6)} failed on the server; latched:`, record);
464
- } else if (this.#applyHole(key.slice(5), record.value)) {
465
- this.#appliedHoles.set(key, record);
466
- this.#recordHave(key.slice(5), record);
467
- morphed = true;
468
- }
469
- } else if (key.startsWith("attr:")) {
470
- if (this.#applyAttrs(key.slice(5), record.value, record.removed)) {
471
- this.#appliedHoles.set(key, record);
472
- this.#recordHave("lha:" + key.slice(5), record);
473
- morphed = true;
451
+ continue;
474
452
  }
453
+ } else if (!key.startsWith("attr:")) continue;
454
+ if (!this.#hasContent || !(wire ??= tierReady("wire"))) continue;
455
+ const name = key.slice(5);
456
+ const attr = key[0] === "a";
457
+ if (!attr) this.#found = undefined;
458
+ if (attr ? wire.attrs(this.#live, name, record) : wire.hole(this.#live, name, record, index)) {
459
+ this.#appliedHoles.set(key, record);
460
+ this.#recordHave(attr ? "lha:" + name : name, record);
461
+ morphed = true;
475
462
  }
476
463
  }
464
+ if (index.r?.size) wire.graft(index.g, index.r);
477
465
  if (morphed) this.#applied(version, "morph");
466
+ if (this.#deferred) {
467
+ if (!morphed && this.#appliedRoot === applied) {
468
+ if (revealed || !only) this.#deferFound = undefined;
469
+ const mounted = only ? new Map() : new Map(this.#deferMounted);
470
+ if (only) for (const id of only) {
471
+ const start = this.#deferMounted.get(id);
472
+ if (start) mounted.set(id, start);else if (!this.#deferFound?.has(id)) this.#deferFound = undefined;
473
+ }
474
+ if (mounted.size) this.#deferWaiting = this.#mountFound(mounted) || this.#deferWaiting;
475
+ return;
476
+ }
477
+ this.#deferred = false;
478
+ this.#deferFound = undefined;
479
+ this.#deferMounted.clear();
480
+ }
481
+ const found = this.#found;
482
+ if (only && found && this.#appliedRoot === applied) {
483
+ const sub = new Map();
484
+ for (const id of only) {
485
+ const start = found.get(id);
486
+ if (!start?.isConnected) return this.#syncSlots();
487
+ sub.set(id, start);
488
+ }
489
+ this.#mountFound(sub);
490
+ return this.#holdIf(this.#waiting.size);
491
+ }
478
492
  this.#syncSlots();
479
493
  }
480
494
  #resolveSlot(prop) {
@@ -494,27 +508,36 @@ class FrameImpl {
494
508
  #syncSlots(root) {
495
509
  if (!this.#slots && !this.#outer) return;
496
510
  const found = new Map();
497
- if (root) collectSlots(root, found, found);else this.#collectSlots(found, found);
511
+ this.#collectSlots(found, root);
512
+ if (root) this.#found = undefined;else this.#found = found, this.#waiting.clear();
513
+ const waiting = this.#mountFound(found);
514
+ if (!root) {
515
+ for (const occurrence of [...this.#mountedSlots]) {
516
+ if (!found.has(occurrence)) this.#unmountSlot(occurrence);
517
+ }
518
+ this.#holdIf(waiting);
519
+ }
520
+ }
521
+ #holdIf(waiting) {
522
+ if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
523
+ }
524
+ #mountFound(found) {
498
525
  let waiting = false;
499
526
  const R = tierLoads.regions?.r;
500
- const B = tierLoads.bind?.r;
501
527
  for (const [occurrence, start] of found) {
528
+ this.#waiting.delete(occurrence);
502
529
  const callback = this.#resolveSlot(propOf(occurrence));
503
- const consumers = Array.isArray(start) ? start : null;
504
- if (!callback) {
505
- if (consumers) devSlotOrphan(this, occurrence, consumers, "fill");
506
- continue;
507
- }
530
+ if (!callback) continue;
508
531
  const record = this.#resolveSlotRecord(occurrence);
509
532
  const mounted = this.#mountedSlots.has(occurrence);
510
533
  if (record === undefined && isCalled(occurrence)) {
511
- waiting ||= !mounted;
512
- if (consumers && !mounted && !this.#options.adopt) devSlotOrphan(this, occurrence, consumers, "record");
534
+ if (!mounted) waiting = true, this.#waiting.add(occurrence);
513
535
  continue;
514
536
  }
515
537
  if (!mounted && record && (record.pending || needsRegions(record) || needsTrace(record.args))) {
516
538
  waiting = true;
517
- if (this.#options.adopt && !consumers) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
539
+ this.#waiting.add(occurrence);
540
+ if (this.#options.adopt) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
518
541
  continue;
519
542
  }
520
543
  if (!mounted) {
@@ -522,12 +545,10 @@ class FrameImpl {
522
545
  this.#heldRecords.delete(occurrence);
523
546
  const mountRecord = held || record;
524
547
  this.#invokeSlot(occurrence, callback, mountRecord, start, this.#options.adopt);
525
- if (consumers) B.sync(this, occurrence, consumers);
526
548
  this.#mountedSlots.add(occurrence);
527
549
  R?.bind(this, occurrence);
528
550
  if (mountRecord === record || !record || record.kind !== "slot") continue;
529
551
  }
530
- if (consumers) B.sync(this, occurrence, consumers);
531
552
  if (record !== this.#slotArgs.get(occurrence)) {
532
553
  if (needsRegions(record) || needsTrace(record.args)) continue;
533
554
  const update = this.#slotUpdaters.get(occurrence);
@@ -542,13 +563,77 @@ class FrameImpl {
542
563
  R?.bind(this, occurrence);
543
564
  }
544
565
  }
545
- if (found.b && !tierReady("bind")) waiting = true;
546
- if (!root) {
547
- for (const occurrence of [...this.#mountedSlots]) {
548
- if (!found.has(occurrence)) this.#unmountSlot(occurrence);
566
+ return waiting;
567
+ }
568
+ get el() {
569
+ return this.#element;
570
+ }
571
+ get defers() {
572
+ return this.#defers;
573
+ }
574
+ get deferred() {
575
+ return this.#deferred;
576
+ }
577
+ mountEnclosing(target) {
578
+ if (!this.#deferred) return false;
579
+ const root = this.#element;
580
+ let outer;
581
+ for (let node = target; node && node !== root; node = node.parentNode) {
582
+ let depth = 0;
583
+ for (let s = node.previousSibling; s; s = s.previousSibling) {
584
+ if (s.nodeType !== COMMENT_NODE || !s.data.startsWith("slot:")) continue;
585
+ if (SLOT_END.test(s.data)) depth++;else if (depth) depth--;else outer = s;
549
586
  }
550
- if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
551
587
  }
588
+ const id = outer && slotStartId(outer);
589
+ if (!id || this.#mountedSlots.has(id)) return false;
590
+ return this.#mountOne(id, outer);
591
+ }
592
+ #mountOne(id, start) {
593
+ const mount = () => {
594
+ this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;
595
+ };
596
+ if (deferMountWatch) deferMountWatch(this.#options.claimScope ?? this.#options.id, id, mount);else mount();
597
+ if (!this.#mountedSlots.has(id)) return false;
598
+ this.#deferMounted.set(id, start);
599
+ return true;
600
+ }
601
+ mountDeferred(deadline) {
602
+ if (!this.#deferred) return true;
603
+ let found = this.#deferFound;
604
+ if (!found) {
605
+ found = this.#deferFound = new Map();
606
+ this.#collectSlots(found);
607
+ }
608
+ for (const [id, start] of found) {
609
+ found.delete(id);
610
+ if (this.#mountedSlots.has(id)) this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;else this.#mountOne(id, start);
611
+ if (deadline !== undefined && found.size && performance.now() > deadline) return false;
612
+ }
613
+ this.#deferred = false;
614
+ this.#deferFound = undefined;
615
+ this.#deferMounted.clear();
616
+ if (this.#deferWaiting && !this.#hold) this.#hold = this.#options.hold?.();
617
+ return true;
618
+ }
619
+ mountOccurrence(id) {
620
+ if (!this.#deferred) return false;
621
+ if (this.#mountedSlots.has(id)) return true;
622
+ let found = this.#deferFound;
623
+ if (!found) {
624
+ found = this.#deferFound = new Map();
625
+ this.#collectSlots(found);
626
+ }
627
+ const start = found.get(id);
628
+ if (!start) return false;
629
+ found.delete(id);
630
+ this.#mountOne(id, start);
631
+ return true;
632
+ }
633
+ releaseDeferHold() {
634
+ const release = this.#deferHold;
635
+ this.#deferHold = undefined;
636
+ release && release();
552
637
  }
553
638
  #releaseHold() {
554
639
  const release = this.#hold;
@@ -560,8 +645,7 @@ class FrameImpl {
560
645
  const cleanups = this.#slotCleanups.get(occurrence) ?? [];
561
646
  let existing = [];
562
647
  let end = null;
563
- const positions = Array.isArray(start) ? start : undefined;
564
- if (start && !positions) end = eachInRange(start, occurrence, n => existing.push(n));
648
+ if (start) end = eachInRange(start, occurrence, n => existing.push(n));
565
649
  const ctx = {
566
650
  frame: this.#options.claimScope ?? this.#options.id,
567
651
  key: occurrence,
@@ -573,9 +657,7 @@ class FrameImpl {
573
657
  range: end ? {
574
658
  start,
575
659
  end
576
- } : undefined,
577
- positions,
578
- onRebind: positions ? fn => tierLoads.bind.r.rebinder(this, occurrence, fn) : undefined
660
+ } : undefined
579
661
  };
580
662
  const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record, adopted, start) : {};
581
663
  this.#scoped(() => callback(props, ctx));
@@ -590,7 +672,6 @@ class FrameImpl {
590
672
  this.#removeSlotRecord(key);
591
673
  this.#runSlotCleanups(key);
592
674
  tierLoads.regions?.r?.unmount(this, key);
593
- tierLoads.bind?.r?.unmount(this, key);
594
675
  }
595
676
  #runSlotCleanups(key) {
596
677
  const cleanups = this.#slotCleanups.get(key);
@@ -617,8 +698,8 @@ class FrameImpl {
617
698
  if (regions) tierLoads.regions.r.resolve(this, slotKey, regions, props, claiming && start);
618
699
  return props;
619
700
  }
620
- #collectSlots(found, elements) {
621
- collectSlots(this.#element, found, elements);
701
+ #collectSlots(found, root) {
702
+ collectSlots(root || this.#element, found);
622
703
  }
623
704
  #findPlaceholder(name, root) {
624
705
  return findPlaceholder((root || this.#element).firstChild, null, placeholderId(name));
@@ -645,7 +726,23 @@ class FrameImpl {
645
726
  this.#resetStreamState();
646
727
  if (host) host.register(id, this);
647
728
  }
729
+ get #live() {
730
+ return this.#liveMount ??= {
731
+ e: this.#element,
732
+ t: this.#liveTargets,
733
+ c: this.#claimTree,
734
+ k: found => this.#collectSlots(found),
735
+ s: () => this.#shows,
736
+ x: (key, record) => (this.#appliedHoles.set(key, record), tierLoads.wire.r.cancel(this.#options.host, this.#options.id)),
737
+ w: ((marker, open) => console.error(`Live hole "${marker}" is missing its closing comment; update dropped. ` + `Likely an HTML-rewriting layer stripped it.`, open))
738
+ };
739
+ }
648
740
  #recordHave(key, record) {
741
+ this.#shows = key ? Object.assign(this.#shows, {
742
+ [key]: record.digest
743
+ }, record.holes) : {
744
+ ...record.holes
745
+ };
649
746
  tierLoads.wire?.r?.have(this, key, record);
650
747
  }
651
748
  dispose() {
@@ -658,12 +755,16 @@ class FrameImpl {
658
755
  this.#disposed = true;
659
756
  liveFrames.delete(this);
660
757
  this.#releaseHold();
758
+ this.releaseDeferHold();
661
759
  for (const key of [...this.#slotCleanups.keys()]) this.#runSlotCleanups(key);
662
760
  for (const key of this.#mountedSlots) this.#removeSlotRecord(key);
663
761
  tierLoads.regions?.r?.unmount(this);
664
762
  this.#mountedSlots.clear();
665
763
  }
666
- #applyRoot(html) {
764
+ #applyRoot(html, wire) {
765
+ this.#found = undefined;
766
+ this.#liveTargets.clear();
767
+ this.#shows = {};
667
768
  const fragment = parseFragment(html);
668
769
  const parent = this.#element;
669
770
  if (!this.#hasContent) {
@@ -675,65 +776,16 @@ class FrameImpl {
675
776
  const claim = this.#claimTree;
676
777
  const ranges = new Map();
677
778
  this.#collectSlots(ranges);
678
- const grafts = [];
679
- reconcileChildren(parent, fragment, null, null, claim, ranges, grafts);
680
- if (ranges.size) for (const root of grafts) flushGrafts(root, ranges);
681
- }
682
- }
683
- #applyHole(marker, html) {
684
- if (!this.#hasContent) return false;
685
- const open = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === COMMENT_NODE && n.data === marker);
686
- if (!open) return false;
687
- const close = rangeClose(open, "lh:/" + marker.slice(3));
688
- if (!close) {
689
- {
690
- console.error(`Live hole "${marker}" is missing its closing comment; update dropped. ` + `Likely an HTML-rewriting layer stripped it.`, open);
691
- }
692
- return false;
693
- }
694
- reconcileChildren(open.parentNode, parseFragment(html), open, close, this.#claimTree);
695
- return true;
696
- }
697
- #applyAttrs(addr, text, removed) {
698
- if (!this.#hasContent) return false;
699
- const el = findLiveTarget(this.#element.firstChild, null, n => n.nodeType === ELEMENT_NODE && n.getAttribute("data-lha") === addr);
700
- if (!el) return false;
701
- const parsed = parseFragment(`<i${text}></i>`).firstChild;
702
- const keepOpen = preservesOpen(el);
703
- const owned = parsed ? ownedPositions(parsed) : null;
704
- const current = el.attributes;
705
- for (let i = current.length - 1; i >= 0; i--) {
706
- const name = current[i].name;
707
- if (name === "data-lha" || keepOpen && name === "open") continue;
708
- if (!parsed || !parsed.hasAttribute(name)) {
709
- if (applyOwned(el, name, "", owned) !== undefined) continue;
710
- el.removeAttribute(name);
711
- }
712
- }
713
- if (parsed) {
714
- for (let i = 0; i < parsed.attributes.length; i++) {
715
- const {
716
- name,
717
- value
718
- } = parsed.attributes[i];
719
- if (keepOpen && name === "open") continue;
720
- if (applyOwned(el, name, value, owned) !== undefined) continue;
721
- if (el.getAttribute(name) !== value) el.setAttribute(name, value);
722
- }
779
+ wire.morph(parent, fragment, claim, ranges);
723
780
  }
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
- }
729
- return true;
730
781
  }
731
782
  #claimContent() {
732
- for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n);
783
+ for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n, false, this);
733
784
  }
734
785
  #revealSegments(root) {
735
786
  const version = this.#version;
736
- for (const key in this.#store) {
787
+ let revealed = false;
788
+ for (const key of this.#content) {
737
789
  const record = this.#store[key];
738
790
  const name = segmentName(key);
739
791
  if (name === null || !record || this.#appliedHoles.get(key) === record) continue;
@@ -741,9 +793,10 @@ class FrameImpl {
741
793
  this.#appliedHoles.set(key, record);
742
794
  this.#revealSegment(name, root);
743
795
  this.#applied(version, "reveal");
796
+ revealed = true;
744
797
  }
745
798
  }
746
- for (const key in this.#store) {
799
+ for (const key of this.#content) {
747
800
  const m = /^seg:([^:]+):fallback$/.exec(key);
748
801
  if (!m || this.#appliedHoles.has(key) || this.#appliedHoles.has(`seg:${m[1]}`)) continue;
749
802
  if (this.#showFallback(m[1], root)) {
@@ -751,6 +804,7 @@ class FrameImpl {
751
804
  this.#applied(version, "reveal");
752
805
  }
753
806
  }
807
+ return revealed;
754
808
  }
755
809
  #segmentReady(name, root) {
756
810
  const content = this.#store[`seg:${name}`];
@@ -763,6 +817,7 @@ class FrameImpl {
763
817
  #revealSegment(name, root) {
764
818
  const tpl = this.#findPlaceholder(name, root);
765
819
  if (!tpl) return;
820
+ this.#found = undefined;
766
821
  const content = this.#store[`seg:${name}`];
767
822
  const closing = rangeClose(tpl, placeholderId(name));
768
823
  if (!closing) {
@@ -823,9 +878,6 @@ function makeFrameElement(id) {
823
878
  if (id !== undefined) el.setAttribute(FRAME_ID_ATTR, id);
824
879
  return el;
825
880
  }
826
- function isFrameElement(node) {
827
- return node.nodeType === ELEMENT_NODE && node.hasAttribute(FRAME_ID_ATTR);
828
- }
829
881
  function segmentName(key) {
830
882
  const m = /^seg:([^:]+)$/.exec(key);
831
883
  return m ? m[1] : null;
@@ -864,20 +916,6 @@ function rangeClose(start, id) {
864
916
  }
865
917
  return null;
866
918
  }
867
- function findLiveTarget(n, end, test) {
868
- while (n && n !== end) {
869
- if (n.nodeType === ELEMENT_NODE) {
870
- const fid = isFrameElement(n) ? n.getAttribute(FRAME_ID_ATTR) : null;
871
- if (fid === null || fid.includes(".")) {
872
- if (test(n)) return n;
873
- const found = findLiveTarget(n.firstChild, null, test);
874
- if (found) return found;
875
- }
876
- } else if (test(n)) return n;
877
- n = n.nextSibling;
878
- }
879
- return null;
880
- }
881
919
  function findPlaceholder(n, end, id) {
882
920
  while (n && n !== end) {
883
921
  if (isPlaceholderStart(n, id)) return n;
@@ -889,39 +927,24 @@ function findPlaceholder(n, end, id) {
889
927
  }
890
928
  return null;
891
929
  }
892
- function collectSlots(root, out, elements) {
893
- let announced;
894
- const bind = elements && (tierLoads.bind || !(announced = globalThis._$HY?.r?.["sc:tiers"]) || announced.includes("bind"));
895
- const B = bind && tierLoads.bind?.r;
896
- const w = root.ownerDocument.createTreeWalker(root, bind ? 0x81 : 0x80);
930
+ function collectSlots(root, out) {
931
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
897
932
  let n, p;
898
933
  while (n = w.nextNode()) {
899
- if (n.nodeType !== COMMENT_NODE) {
900
- if (!n.hasAttribute(FRAME_ID_ATTR)) {
901
- if (n.hasAttributes()) B ? B.positions(n, elements) : hasSlotMarker(n) && (elements.b = true);
902
- continue;
903
- }
904
- p = n;
905
- } else if (n.data.startsWith("slot:")) {
906
- const id = slotStartId(n);
907
- if (!id) continue;
908
- if (!bind) {
909
- for (p = n.parentNode; p !== root; p = p.parentNode) if (p.hasAttribute(FRAME_ID_ATTR)) break;
910
- if (p !== root) continue;
911
- }
912
- if (!out.has(id)) out.set(id, n);
913
- const end = findMarker(n, slotEnd(id));
914
- if (end) {
915
- w.currentNode = end;
916
- continue;
917
- }
918
- devReportRange(id);
919
- p = n.parentNode;
920
- if (p === root) return;
921
- } else {
922
- if (bind && n.data.startsWith(SLOT_TEXT)) B ? B.text(n, elements) : elements.b = true;
934
+ if (!n.data.startsWith("slot:")) continue;
935
+ const id = slotStartId(n);
936
+ if (!id) continue;
937
+ for (p = n.parentNode; p !== root; p = p.parentNode) if (p.hasAttribute(FRAME_ID_ATTR)) break;
938
+ if (p !== root) continue;
939
+ if (!out.has(id)) out.set(id, n);
940
+ const end = findMarker(n, slotEnd(id));
941
+ if (end) {
942
+ w.currentNode = end;
923
943
  continue;
924
944
  }
945
+ devReportRange(id);
946
+ p = n.parentNode;
947
+ if (p === root) return;
925
948
  while (p.lastChild) p = p.lastChild;
926
949
  w.currentNode = p;
927
950
  }
@@ -941,74 +964,6 @@ function slotStartId(node) {
941
964
  const m = SLOT_START.exec(node.data);
942
965
  return m ? m[1] : null;
943
966
  }
944
- function isSlotMarker(node) {
945
- if (node.nodeType !== COMMENT_NODE) return false;
946
- const data = node.data;
947
- return SLOT_START.test(data) || SLOT_END.test(data);
948
- }
949
- function compatible(a, b) {
950
- if (a.nodeType !== b.nodeType) return false;
951
- if (a.nodeType === ELEMENT_NODE) return a.nodeName === b.nodeName && a.getAttribute("_key") === b.getAttribute("_key");
952
- return a.nodeType === TEXT_NODE || a.nodeType === COMMENT_NODE;
953
- }
954
- function preservesOpen(el) {
955
- const t = el.tagName;
956
- return t === "DETAILS" || t === "DIALOG";
957
- }
958
- const ownedPositions = el => {
959
- const B = tierLoads.bind?.r;
960
- return B ? B.owned(el) : null;
961
- };
962
- const applyOwned = (oldEl, name, value, owned) => owned === null ? undefined : tierLoads.bind.r.apply(oldEl, name, value, owned);
963
- function morphAttributes(oldEl, newEl, claim) {
964
- let reclaim = false;
965
- let changed = false;
966
- const keepOpen = preservesOpen(oldEl);
967
- const owned = ownedPositions(newEl);
968
- const oldAttrs = oldEl.attributes;
969
- for (let i = oldAttrs.length - 1; i >= 0; i--) {
970
- const name = oldAttrs[i].name;
971
- if (keepOpen && name === "open") continue;
972
- if (!newEl.hasAttribute(name)) {
973
- const handled = applyOwned(oldEl, name, "", owned);
974
- if (handled !== undefined) {
975
- changed = handled || changed;
976
- continue;
977
- }
978
- oldEl.removeAttribute(name);
979
- changed = true;
980
- reclaim ||= claimedAttr(name);
981
- }
982
- }
983
- const newAttrs = newEl.attributes;
984
- for (let i = 0; i < newAttrs.length; i++) {
985
- const attr = newAttrs[i];
986
- const name = attr.name;
987
- if (keepOpen && name === "open") continue;
988
- const handled = applyOwned(oldEl, name, attr.value, owned);
989
- if (handled !== undefined) {
990
- changed = handled || changed;
991
- continue;
992
- }
993
- if (oldEl.getAttribute(name) !== attr.value) {
994
- oldEl.setAttribute(name, attr.value);
995
- changed = true;
996
- reclaim ||= claimedAttr(name);
997
- }
998
- }
999
- if (claim && (reclaim || changed && oldEl.matches(CLAIMED_ELEMENTS))) claim(oldEl, true);
1000
- }
1001
- function morphNode(oldNode, newNode, claim, ranges, grafts) {
1002
- if (oldNode.nodeType === ELEMENT_NODE) {
1003
- if (oldNode.hasAttribute("data-preserve")) return;
1004
- morphAttributes(oldNode, newNode, claim);
1005
- reconcileChildren(oldNode, newNode, null, null, claim, ranges, grafts);
1006
- } else if (oldNode.data !== newNode.data) {
1007
- oldNode.data = newNode.data;
1008
- }
1009
- }
1010
- const afterRange = (start, id) => findMarker(start, slotEnd(id))?.nextSibling;
1011
- const afterText = start => findMarker(start, SLOT_TEXT_END)?.nextSibling;
1012
967
  function findMarker(start, end) {
1013
968
  let n = start.nextSibling;
1014
969
  while (n) {
@@ -1017,29 +972,6 @@ function findMarker(start, end) {
1017
972
  }
1018
973
  return null;
1019
974
  }
1020
- let slotOrphans;
1021
- function devSlotOrphan(frame, occurrence, consumers, why) {
1022
- let seen = (slotOrphans ??= new WeakMap()).get(frame);
1023
- if (!seen) slotOrphans.set(frame, seen = new Set());
1024
- if (seen.has(occurrence)) return;
1025
- seen.add(occurrence);
1026
- const prop = propOf(occurrence);
1027
- const positions = new Set();
1028
- for (const c of consumers) for (const p of c.positions) positions.add(p.pos);
1029
- const where = `${consumers.length} element${consumers.length === 1 ? "" : "s"} (positions: ${[...positions].join(", ")})`;
1030
- DEV.report(OBSERVE.diagnostics.emit({
1031
- code: "BINDING_SLOT_POSITION",
1032
- kind: "render",
1033
- severity: "warn",
1034
- 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.`,
1035
- data: {
1036
- reason: "orphan",
1037
- why,
1038
- occurrence,
1039
- elements: consumers.map(c => c.element)
1040
- }
1041
- }, null));
1042
- }
1043
975
  function devReportRange(id) {
1044
976
  const end = slotEnd(id);
1045
977
  DEV.report(OBSERVE.diagnostics.emit({
@@ -1053,170 +985,22 @@ function devReportRange(id) {
1053
985
  }
1054
986
  }, null));
1055
987
  }
1056
- function findRangeStart(from, id, bound) {
1057
- const target = `slot:${id}:start`;
1058
- let n = from;
1059
- while (n && n !== bound) {
1060
- if (n.nodeType === COMMENT_NODE && n.data === target) return n;
1061
- n = n.nextSibling;
1062
- }
1063
- return null;
1064
- }
1065
- function moveRangeBefore(parent, start, id, ref) {
1066
- const end = slotEnd(id);
1067
- let n = start;
1068
- while (n) {
1069
- const next = n.nextSibling;
1070
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1071
- parent.insertBefore(n, ref);
1072
- if (isEnd) break;
1073
- n = next;
1074
- }
1075
- }
1076
- function placeRange(parent, range, id, ref) {
1077
- if (range.nodeType === 11 ) {
1078
- parent.insertBefore(range, ref);
1079
- } else {
1080
- moveRangeBefore(parent, range, id, ref);
1081
- }
1082
- }
1083
- function adoptRange(parent, start, id, ref, claim) {
1084
- const end = slotEnd(id);
1085
- let n = start;
1086
- let after = null;
1087
- while (n) {
1088
- const next = n.nextSibling;
1089
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1090
- parent.insertBefore(n, ref);
1091
- if (claim) claim(n);
1092
- if (isEnd) {
1093
- after = next;
1094
- break;
1095
- }
1096
- n = next;
1097
- }
1098
- return after;
1099
- }
1100
- function reconcileChildren(parent, source, boundStart = null, boundEnd = null, claim = null, ranges = null, grafts = null) {
1101
- let oldChild = boundStart ? boundStart.nextSibling : parent.firstChild;
1102
- let newChild = source.firstChild;
1103
- while (newChild) {
1104
- const nextNew = newChild.nextSibling;
1105
- const pid = slotStartId(newChild);
1106
- const old = oldChild === boundEnd ? null : oldChild;
1107
- if (old && isTextStart(newChild) && old.nodeType === COMMENT_NODE && old.data === newChild.data) {
1108
- oldChild = afterText(old);
1109
- newChild = afterText(newChild);
1110
- continue;
1111
- }
1112
- if (pid !== null) {
1113
- if (old && slotStartId(old) === pid) {
1114
- oldChild = afterRange(old, pid);
1115
- newChild = afterRange(newChild, pid);
1116
- } else {
1117
- const displaced = ranges && ranges.get(pid);
1118
- const existing = displaced || findRangeStart(old, pid, boundEnd);
1119
- if (existing) {
1120
- if (ranges) ranges.delete(pid);
1121
- placeRange(parent, existing, pid, old ?? boundEnd);
1122
- newChild = afterRange(newChild, pid);
1123
- } else {
1124
- newChild = adoptRange(parent, newChild, pid, old ?? boundEnd, claim);
1125
- }
1126
- }
1127
- continue;
1128
- }
1129
- if (!old) {
1130
- parent.insertBefore(newChild, boundEnd);
1131
- if (claim) claim(newChild);
1132
- if (grafts) grafts.push(newChild);
1133
- newChild = nextNew;
1134
- continue;
1135
- }
1136
- if (isSlotMarker(old)) {
1137
- parent.insertBefore(newChild, old);
1138
- if (claim) claim(newChild);
1139
- if (grafts) grafts.push(newChild);
1140
- newChild = nextNew;
1141
- continue;
1142
- }
1143
- if (compatible(old, newChild)) {
1144
- morphNode(old, newChild, claim, ranges, grafts);
1145
- oldChild = old.nextSibling;
1146
- newChild = nextNew;
1147
- continue;
1148
- }
1149
- if (newChild.nodeType === 1) {
1150
- let ahead = old.nextSibling;
1151
- while (ahead && ahead !== boundEnd && !compatible(ahead, newChild)) {
1152
- const aheadPid = slotStartId(ahead);
1153
- ahead = aheadPid !== null ? afterRange(ahead, aheadPid) : ahead.nextSibling;
1154
- }
1155
- if (ahead && ahead !== boundEnd) {
1156
- parent.insertBefore(ahead, old);
1157
- morphNode(ahead, newChild, claim, ranges, grafts);
1158
- newChild = nextNew;
1159
- continue;
1160
- }
1161
- }
1162
- parent.insertBefore(newChild, old);
1163
- if (claim) claim(newChild);
1164
- if (grafts) grafts.push(newChild);
1165
- newChild = nextNew;
1166
- }
1167
- while (oldChild && oldChild !== boundEnd) {
1168
- const next = oldChild.nextSibling;
1169
- const pid = ranges ? slotStartId(oldChild) : null;
1170
- if (pid !== null && ranges.get(pid) === oldChild) {
1171
- const frag = document.createDocumentFragment();
1172
- const after = stashRange(frag, oldChild, pid);
1173
- ranges.set(pid, frag);
1174
- oldChild = after;
1175
- continue;
1176
- }
1177
- parent.removeChild(oldChild);
1178
- oldChild = next;
1179
- }
1180
- }
1181
- function flushGrafts(node, ranges) {
1182
- if (node.nodeType !== ELEMENT_NODE || isFrameElement(node)) return;
1183
- let n = node.firstChild;
1184
- while (n) {
1185
- const id = slotStartId(n);
1186
- if (id !== null) {
1187
- const next = afterRange(n, id);
1188
- const displaced = ranges.get(id);
1189
- if (displaced) {
1190
- ranges.delete(id);
1191
- placeRange(node, displaced, id, n);
1192
- stashRange(document.createDocumentFragment(), n, id);
1193
- }
1194
- n = next;
1195
- continue;
1196
- }
1197
- flushGrafts(n, ranges);
1198
- n = n.nextSibling;
1199
- }
1200
- }
1201
- function stashRange(frag, start, id) {
1202
- const end = slotEnd(id);
1203
- let n = start;
1204
- while (n) {
1205
- const next = n.nextSibling;
1206
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1207
- frag.appendChild(n);
1208
- if (isEnd) return next;
1209
- n = next;
1210
- }
1211
- return null;
1212
- }
1213
988
 
1214
989
  const RECORDS = Symbol.for("@solidjs/signals/observe/records");
1215
990
  function records() {
1216
991
  return globalThis[RECORDS];
1217
992
  }
1218
- function frameCensus(event, type, own) {
1219
- event.chunks++;
993
+ function frameRecordCensus(event, message, own) {
994
+ const r = message.r;
995
+ let counted = !r;
996
+ for (const key in r) {
997
+ if (key === ":complete" || key === ":bound") continue;
998
+ counted = true;
999
+ countEvent(event, key === "" ? "html" : key.endsWith(":error") ? "error" : key.startsWith("slot:") ? "slot" : key.startsWith("seg:") && r[key] && r[key].kind === "html" ? "fragment" : key, own);
1000
+ }
1001
+ if (counted) event.chunks++;
1002
+ }
1003
+ function countEvent(event, type, own) {
1220
1004
  switch (type) {
1221
1005
  case "html":
1222
1006
  if (!own) event.regions++;else if (event.shellMs === undefined) event.shellMs = performance.now() - event.at;
@@ -1272,11 +1056,8 @@ function observeFrameApply(response) {
1272
1056
  return;
1273
1057
  }
1274
1058
  if (current === undefined) return;
1275
- if (chunk.type === "complete") {
1276
- if (chunk.id === current.applied) close("complete");
1277
- return;
1278
- }
1279
- frameCensus(current.event, chunk.type, chunk.id === current.applied);
1059
+ frameRecordCensus(current.event, chunk, chunk.id === current.applied);
1060
+ if (chunk.r && ":complete" in chunk.r && chunk.id === current.applied) close("complete");
1280
1061
  },
1281
1062
  end(error) {
1282
1063
  if (current !== undefined) close(error !== undefined ? "error" : "truncated", error);
@@ -1303,6 +1084,11 @@ async function observedApplyFrameResponse(response, host, options = {}) {
1303
1084
  observation.end();
1304
1085
  return applied;
1305
1086
  }
1087
+ const ends = msg => !!msg.r && (":complete" in msg.r || ":error" in msg.r);
1088
+ const readsData = msg => {
1089
+ for (const key in msg.r) if (key.startsWith("slot:")) for (const v of Object.values(msg.r[key].args)) if (v && v.$ref) return true;
1090
+ return false;
1091
+ };
1306
1092
  function applyFrames(response, host, options = {}, observation) {
1307
1093
  const rootId = response.headers.get(FRAME_STREAM_HEADER) ?? "";
1308
1094
  response.headers.get(FRAME_TIERS_HEADER)?.split(",").forEach(prepareTier);
@@ -1312,11 +1098,12 @@ function applyFrames(response, host, options = {}, observation) {
1312
1098
  const reader = options[LIVE_WIRE] || new ChunkReader(response.body);
1313
1099
  const open = new Map();
1314
1100
  const errorRecord = (id, error) => ({
1315
- type: "error",
1316
1101
  id,
1317
1102
  version: open.get(id),
1318
- error: {
1319
- message: String(error && error.message)
1103
+ r: {
1104
+ ":error": {
1105
+ message: String(error && error.message)
1106
+ }
1320
1107
  }
1321
1108
  });
1322
1109
  const drain = async () => {
@@ -1333,10 +1120,10 @@ function applyFrames(response, host, options = {}, observation) {
1333
1120
  if (v === undefined) perFrame.set(chunk.id, v = version(chunk.id));
1334
1121
  chunk.version = v;
1335
1122
  } else if (version !== undefined) chunk.version = version;
1336
- if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (chunk.type === "complete" || chunk.type === "error" && !chunk.key) open.delete(chunk.id);
1123
+ if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (ends(chunk)) open.delete(chunk.id);
1337
1124
  if (observation) observation.chunk(chunk, wireId);
1338
1125
  const needs = chunk.tiers?.map(prepareTier) || [];
1339
- if (chunk.type === "data" || chunk.type === "slot" && Object.values(chunk.args).some(v => v && v.$ref)) await Promise.all([host.prepareData?.(), ...needs]);
1126
+ if (chunk.type === "data" || readsData(chunk)) await Promise.all([host.prepareData?.(), ...needs]);
1340
1127
  host.apply(chunk);
1341
1128
  }
1342
1129
  result = await reader.next();
@@ -1496,7 +1283,7 @@ function createServerComponentHandler({
1496
1283
  return {
1497
1284
  intercept: intercept && (info => {
1498
1285
  const hit = intercept(info);
1499
- if (hit === undefined) return undefined;
1286
+ if (hit === undefined) return void prepareMorph();
1500
1287
  const address = frameAddress(info.id, info.args);
1501
1288
  if (!info.meta?.live) calls.set(address, info);
1502
1289
  const binding = () => bindingFor(address, info.id);
@@ -1521,17 +1308,23 @@ function createServerComponentHandler({
1521
1308
  calls.set(address, ctx);
1522
1309
  const version = bump(address);
1523
1310
  const entry = showing(address) ? stage(address, binding, version) : undefined;
1524
- if (!entry) begin(address, version);
1311
+ if (!entry) host.apply({
1312
+ type: "start",
1313
+ id: address,
1314
+ version,
1315
+ startedAt: ctx.startedAt
1316
+ }) ;
1525
1317
  const target = entry || host;
1526
1318
  const applied = applyFrameResponse(response, target, {
1527
1319
  as: address,
1528
1320
  version: frameId => frameId === address ? version : bump(frameId)
1529
1321
  }).catch(err => target.apply({
1530
- type: "error",
1531
1322
  id: address,
1532
1323
  version,
1533
- error: {
1534
- message: String(err && err.message)
1324
+ r: {
1325
+ ":error": {
1326
+ message: String(err && err.message)
1327
+ }
1535
1328
  }
1536
1329
  }));
1537
1330
  return entry ? applied.then(() => settled(address, binding)) : binding;
@@ -1593,7 +1386,6 @@ const TRACE_STATE = Symbol.for("solid.container-trace-state");
1593
1386
  tierLoaders.trace = () => import('@solidjs/web/frames/trace');
1594
1387
  tierLoaders.regions = () => import('@solidjs/web/frames/regions');
1595
1388
  tierLoaders.assets = () => import('@solidjs/web/frames/assets');
1596
- tierLoaders.bind = () => import('@solidjs/web/frames/bind');
1597
1389
  tierLoaders.wire = () => import('@solidjs/web/frames/wire');
1598
1390
  function asyncArg(value) {
1599
1391
  return value;
@@ -1634,7 +1426,12 @@ function landing(host, address, value, failed) {
1634
1426
  if (state > 1) throw frame.error;
1635
1427
  const wait = host.landing(address);
1636
1428
  if (!wait) return value;
1637
- return (state ? reask(address, wait) : wait).then(() => value);
1429
+ const landed = (state ? reask(address, wait) : wait).then(() => value);
1430
+ if (!state) {
1431
+ const origin = OBSERVE.attribution.flightOrigin(wait);
1432
+ if (origin !== undefined) OBSERVE.attribution.markFlight(landed, origin);
1433
+ }
1434
+ return landed;
1638
1435
  });
1639
1436
  }
1640
1437
  function reask(address, wait) {
@@ -1682,15 +1479,13 @@ function claimScope(el) {
1682
1479
  index
1683
1480
  };
1684
1481
  }
1685
- function claimRender(prefix, existing, render, scope, bound) {
1482
+ function claimRender(prefix, owner, existing, render, scope, bound) {
1686
1483
  const sc = sharedConfig;
1687
- if (!sc.hydrateWindow || !sc.registry) return render();
1484
+ if (!sc.hydrateWindow || !sc.registry) return runWithOwner(owner, render);
1688
1485
  const prevRoots = sc.claimRoots;
1689
1486
  sc.claimRoots = existing;
1690
1487
  try {
1691
- return runWithOwner(createOwner({
1692
- id: prefix
1693
- }), () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1488
+ return runWithOwner(owner, () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1694
1489
  } finally {
1695
1490
  sc.claimRoots = prevRoots;
1696
1491
  }
@@ -1742,6 +1537,7 @@ function slotArgsProxy(args) {
1742
1537
  reads.set(key, read);
1743
1538
  }
1744
1539
  const v = read();
1540
+ if (v instanceof Element) tierLoads.regions.r.place(v);
1745
1541
  return v instanceof Boxed ? v.c : v;
1746
1542
  },
1747
1543
  has: (_, key) => key in args(),
@@ -1757,47 +1553,24 @@ function slotsFor(props, scope) {
1757
1553
  return new Proxy({}, {
1758
1554
  get(_, prop) {
1759
1555
  if (typeof prop !== "string" || !(prop in props)) return undefined;
1760
- return (slotProps, ctx) => {
1556
+ const mount = (slotProps, ctx) => {
1761
1557
  const key = ctx && ctx.key;
1762
1558
  const prevFill = key !== undefined && fillScopes.get(key);
1763
1559
  if (prevFill) {
1764
1560
  fillScopes.delete(key);
1765
1561
  prevFill.dispose();
1766
1562
  }
1767
- if (ctx && ctx.positions) {
1768
- const fill = props[prop];
1769
- if (typeof fill !== "function") {
1770
- {
1771
- slotShapeFinding({
1772
- reason: "fill-shape",
1773
- occurrence: key,
1774
- shape: typeof fill
1775
- }, `[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.`);
1776
- }
1777
- return undefined;
1778
- }
1779
- const owner = createOwner();
1780
- fillScopes.set(key, owner);
1781
- ctx.onCleanup(() => {
1782
- if (fillScopes.get(key) === owner) fillScopes.delete(key);
1783
- owner.dispose();
1784
- });
1785
- runWithOwner(owner, () => {
1786
- const args = ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps);
1787
- tierLoads.bind.r.bind(fill, args, ctx, `the \`${prop}\` binding-slot fill` );
1788
- });
1789
- return undefined;
1790
- }
1791
1563
  const range = ctx && ctx.range;
1792
1564
  if (!range) return undefined;
1793
1565
  const fillOwner = streamInvoke ? createOwner() : null;
1794
- if (fillOwner && key !== undefined && ctx) {
1795
- fillScopes.set(key, fillOwner);
1796
- ctx.onCleanup(() => {
1797
- if (fillScopes.get(key) === fillOwner) fillScopes.delete(key);
1798
- fillOwner.dispose();
1799
- });
1800
- }
1566
+ const owner = fillOwner || createOwner({
1567
+ transparent: true
1568
+ });
1569
+ fillScopes.set(key, owner);
1570
+ ctx.onCleanup(() => {
1571
+ if (fillScopes.get(key) === owner) fillScopes.delete(key);
1572
+ owner.dispose();
1573
+ });
1801
1574
  const evaluate = () => {
1802
1575
  const v = props[prop];
1803
1576
  if (typeof v === "function" && ctx && ctx.invoked) {
@@ -1808,22 +1581,19 @@ function slotsFor(props, scope) {
1808
1581
  };
1809
1582
  const adopted = !!(ctx && ctx.frame && ctx.adopted && ctx.existing && ctx.existing.length);
1810
1583
  const prefix = ctx && ctx.frame ? `sc-${ctx.frame}-${ctx.key}-` : "";
1811
- const value = fillOwner ? runWithOwner(fillOwner, () => adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate()) : adopted ? claimRender(prefix, ctx.existing, evaluate, scope) : evaluate();
1812
- const owner = fillOwner || createOwner({
1813
- transparent: true
1814
- });
1815
- if (!fillOwner) {
1816
- fillScopes.set(key, owner);
1817
- ctx.onCleanup(() => {
1818
- if (fillScopes.get(key) === owner) fillScopes.delete(key);
1819
- owner.dispose();
1820
- });
1821
- }
1584
+ const claim = adopted && runWithOwner(owner, () => createOwner({
1585
+ id: prefix
1586
+ }));
1587
+ const value = adopted ? claimRender(prefix, claim, ctx.existing, evaluate, scope) : fillOwner ? runWithOwner(fillOwner, evaluate) : evaluate();
1822
1588
  const end = range.end;
1823
1589
  const bind = () => insert(end.parentNode, value, end, [...ctx.existing]);
1824
- runWithOwner(owner, () => adopted ? claimRender(prefix, ctx.existing, bind, scope, true) : bind());
1590
+ adopted ? claimRender(prefix, claim, ctx.existing, bind, scope, true) : runWithOwner(owner, bind);
1825
1591
  return undefined;
1826
1592
  };
1593
+ return (slotProps, ctx) => {
1594
+ const R = tierLoads.regions?.r;
1595
+ R ? R.nest(mount, slotProps, ctx) : mount(slotProps, ctx);
1596
+ };
1827
1597
  }
1828
1598
  });
1829
1599
  }
@@ -1877,7 +1647,12 @@ function pumpLiveChannel() {
1877
1647
  const pump = () => reader.read().then(r => {
1878
1648
  if (r.done) return;
1879
1649
  const op = r.value;
1880
- for (const m of op.type === "ops" ? op.ops : [op]) liveOps.set(`${m.type}:${m.fid || ""}:${m.key || ""}`, m);
1650
+ for (const key in op.r) liveOps.set(`${op.fid || ""}:${key}`, {
1651
+ fid: op.fid,
1652
+ r: {
1653
+ [key]: op.r[key]
1654
+ }
1655
+ });
1881
1656
  for (const apply of liveAppliers) apply(op);
1882
1657
  return pump();
1883
1658
  });
@@ -1892,14 +1667,18 @@ function indexBoundaries(root) {
1892
1667
  if (key && isBoundaryId(key) && !boundaryIndex.has(key)) boundaryIndex.set(key, el);
1893
1668
  });
1894
1669
  }
1895
- function findBoundaryElement(id) {
1670
+ function findBoundaryElement(id, address) {
1896
1671
  if (!boundaryIndex) {
1897
1672
  boundaryIndex = new Map();
1898
1673
  if (typeof document !== "undefined" && document.body) indexBoundaries(document.body);
1899
1674
  }
1675
+ const args = address && address.slice(id.length + 1);
1676
+ let first, el;
1900
1677
  for (let n = 0;; n++) {
1901
1678
  const key = n ? id + "~" + (n + 1) : id;
1902
- if (!claimedBoundaries.has(key)) return boundaryIndex.get(key);
1679
+ if (claimedBoundaries.has(key)) continue;
1680
+ if (!(el = boundaryIndex.get(key)) || !args || el.dataset.fa == args) return el || first;
1681
+ first = first || el;
1903
1682
  }
1904
1683
  }
1905
1684
  const arrivals = new Map();
@@ -1910,17 +1689,29 @@ function awaitBoundary(id) {
1910
1689
  if (!arrival) {
1911
1690
  let resolve;
1912
1691
  const promise = new Promise(r => resolve = r);
1692
+ if (!resolve) return promise;
1913
1693
  arrivals.set(id, arrival = {
1914
1694
  promise,
1915
1695
  resolve
1916
1696
  });
1697
+ onHydrationEnd(releaseArrivals);
1917
1698
  }
1918
1699
  return arrival.promise;
1919
1700
  }
1701
+ function releaseArrivals() {
1702
+ if (!arrivals.size) return;
1703
+ const exhausted = !boundaryMayArrive();
1704
+ for (const [id, arrival] of arrivals) {
1705
+ const el = boundaryIndex && boundaryIndex.get(id);
1706
+ if (!el && !exhausted) continue;
1707
+ arrivals.delete(id);
1708
+ arrival.resolve(!!el);
1709
+ }
1710
+ }
1920
1711
  function boundaryMayArrive() {
1921
1712
  const hy = globalThis._$HY;
1922
1713
  if (!hy) return false;
1923
- return !hy.done || !!(hy.fr && hy.fr.pending());
1714
+ return !(hy.done || sharedConfig.done) || !!(hy.fr && hy.fr.pending());
1924
1715
  }
1925
1716
  function installRevealHook() {
1926
1717
  installServerComponentHydration();
@@ -1935,26 +1726,20 @@ function installRevealHook() {
1935
1726
  if (!boundaryIndex) return;
1936
1727
  const root = parent || (typeof document !== "undefined" ? document.body : null);
1937
1728
  if (root) indexBoundaries(root);
1938
- if (!arrivals.size) return;
1939
- const exhausted = hy.done && !hy.fr.pending();
1940
- for (const [id, arrival] of arrivals) {
1941
- const el = boundaryIndex && boundaryIndex.get(id);
1942
- if (!el && !exhausted) continue;
1943
- arrivals.delete(id);
1944
- arrival.resolve(!!el);
1945
- }
1729
+ releaseArrivals();
1946
1730
  });
1947
1731
  }
1948
1732
  function documentBoundary(host, id, props, binding) {
1949
1733
  installRevealHook();
1950
- const el = findBoundaryElement(id);
1734
+ const address = binding && contentAddress(binding());
1735
+ const el = findBoundaryElement(id, address);
1951
1736
  if (el) return adoptBoundary(host, id, el, props, binding);
1952
1737
  if (!claimedBoundaries.has(id) && boundaryMayArrive()) {
1953
1738
  const owner = getOwner();
1954
1739
  let live = true;
1955
1740
  onCleanup(() => live = false);
1956
1741
  return createMemo(() => awaitBoundary(id).then(() => live && runWithOwner(owner, () => {
1957
- const node = findBoundaryElement(id);
1742
+ const node = findBoundaryElement(id, address);
1958
1743
  return node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding);
1959
1744
  })));
1960
1745
  }
@@ -1963,6 +1748,7 @@ function documentBoundary(host, id, props, binding) {
1963
1748
  function adoptBoundary(host, id, el, props, binding) {
1964
1749
  const siteId = el.getAttribute(FRAME_ID_ATTR);
1965
1750
  claimedBoundaries.add(siteId);
1751
+ edgeRoots.set(siteId, el);
1966
1752
  const address = binding ? contentAddress(binding()) : id;
1967
1753
  const appliedRecords = new Set();
1968
1754
  const reportedFragments = new Set();
@@ -1987,11 +1773,14 @@ function adoptBoundary(host, id, el, props, binding) {
1987
1773
  if (key.startsWith(slotPrefix)) {
1988
1774
  appliedRecords.add(key);
1989
1775
  const apply = args => host.apply({
1990
- type: "slot",
1991
1776
  id: address,
1992
1777
  version: 0,
1993
- key: key.slice(slotPrefix.length),
1994
- args
1778
+ r: {
1779
+ [`slot:${key.slice(slotPrefix.length)}`]: {
1780
+ kind: "slot",
1781
+ args
1782
+ }
1783
+ }
1995
1784
  });
1996
1785
  const value = hy.r[key];
1997
1786
  if (value && typeof value.then === "function") {
@@ -2003,10 +1792,14 @@ function adoptBoundary(host, id, el, props, binding) {
2003
1792
  appliedRecords.add(key);
2004
1793
  const val = hy.r[key];
2005
1794
  const apply = html => host.apply({
2006
- type: "html",
2007
1795
  id: childId,
2008
1796
  version: 0,
2009
- html
1797
+ r: {
1798
+ "": {
1799
+ kind: "html",
1800
+ value: html
1801
+ }
1802
+ }
2010
1803
  });
2011
1804
  val && typeof val.then === "function" ? val.then(apply) : apply(val);
2012
1805
  }
@@ -2030,9 +1823,9 @@ function adoptBoundary(host, id, el, props, binding) {
2030
1823
  const applyLiveOp = op => {
2031
1824
  if (op.fid && op.fid !== siteId) return;
2032
1825
  host.apply({
2033
- ...op,
2034
1826
  id: address,
2035
- version: 0
1827
+ version: 0,
1828
+ r: op.r
2036
1829
  });
2037
1830
  };
2038
1831
  liveAppliers.add(applyLiveOp);
@@ -2047,6 +1840,7 @@ function adoptBoundary(host, id, el, props, binding) {
2047
1840
  const [failed, onApply] = failing();
2048
1841
  frame = createFrame(el, {
2049
1842
  adopt: true,
1843
+ defer: true,
2050
1844
  host,
2051
1845
  id: address,
2052
1846
  slots: slotsFor(props, scope),
@@ -2070,6 +1864,196 @@ function adoptBoundary(host, id, el, props, binding) {
2070
1864
  });
2071
1865
  return el;
2072
1866
  }
1867
+ const DEFER_EVENTS = ["click", "input", "change", "keydown", "pointerdown", "submit", "focusin"];
1868
+ const DEFER_BUDGET = 8;
1869
+ let mounting = false;
1870
+ const idleTick = () => new Promise(r => typeof requestIdleCallback === "function" ? requestIdleCallback(() => r(), {
1871
+ timeout: 100
1872
+ }) : setTimeout(r, 0));
1873
+ function wakeAt(e) {
1874
+ const target = e.target;
1875
+ if (!target || mounting) return;
1876
+ mounting = true;
1877
+ try {
1878
+ for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1879
+ } finally {
1880
+ mounting = false;
1881
+ }
1882
+ deferDone();
1883
+ }
1884
+ function mountAllDeferred() {
1885
+ if (mounting || sharedConfig.hydrating) return;
1886
+ mounting = true;
1887
+ try {
1888
+ for (let frames; (frames = deferredFrames()).length;) for (const f of frames) f.mountDeferred();
1889
+ } finally {
1890
+ mounting = false;
1891
+ }
1892
+ deferDone();
1893
+ }
1894
+ const edgeRoots = new Map();
1895
+ let edgeIndex;
1896
+ const DEPS = "sc:deps:";
1897
+ function buildEdgeIndex() {
1898
+ const r = globalThis._$HY?.r;
1899
+ if (!r) return undefined;
1900
+ const idx = {
1901
+ readers: new Map(),
1902
+ wide: new Set(),
1903
+ untracked: [],
1904
+ sites: new Set(),
1905
+ starts: new Map()
1906
+ };
1907
+ for (const site of edgeRoots.keys()) for (let n = 0, batch; batch = r[DEPS + site + ":" + n]; n++) {
1908
+ if (typeof batch !== "object") return undefined;
1909
+ idx.sites.add(site);
1910
+ for (const sid in batch) {
1911
+ const occs = unpackOccurrences(batch[sid]);
1912
+ if (sid === "*") occs.forEach(w => idx.wide.add(w));else if (sid === "!") occs.forEach(o => idx.untracked.push([site, o]));else {
1913
+ let list = idx.readers.get(sid);
1914
+ if (!list) idx.readers.set(sid, list = []);
1915
+ for (const o of occs) list.push([site, o]);
1916
+ }
1917
+ }
1918
+ }
1919
+ return idx;
1920
+ }
1921
+ function unpackOccurrences(packed) {
1922
+ const out = [];
1923
+ for (const part of packed.split(" ")) {
1924
+ const m = /^(.*)#(\d+)-(\d+)$/.exec(part);
1925
+ if (!m) part && out.push(part);else for (let i = +m[2]; i <= +m[3]; i++) out.push(m[1] + "#" + i);
1926
+ }
1927
+ return out;
1928
+ }
1929
+ function startOf(idx, site, occ) {
1930
+ let m = idx.starts.get(site);
1931
+ if (!m) {
1932
+ idx.starts.set(site, m = new Map());
1933
+ const root = edgeRoots.get(site);
1934
+ if (root) {
1935
+ const w = document.createTreeWalker(root, 128 );
1936
+ for (let c = w.nextNode(); c; c = w.nextNode()) {
1937
+ const d = c.data;
1938
+ if (d.startsWith("slot:") && d.endsWith(":start")) m.set(d.slice(5, -6), c);
1939
+ }
1940
+ }
1941
+ }
1942
+ return m.get(occ);
1943
+ }
1944
+ function edgesCover(idx) {
1945
+ outer: for (const f of deferredFrames()) {
1946
+ for (const [site, root] of edgeRoots) if (idx.sites.has(site) && root.contains(f.el)) continue outer;
1947
+ return false;
1948
+ }
1949
+ return true;
1950
+ }
1951
+ function mountForWrite(node) {
1952
+ if (mounting || sharedConfig.hydrating) return;
1953
+ const sid = signalName(node) ?? storeName(node);
1954
+ if (sid === undefined || document.readyState === "loading") return mountAllDeferred();
1955
+ const idx = edgeIndex ||= buildEdgeIndex();
1956
+ if (!idx || idx.wide.has(sid) || !edgesCover(idx)) return mountAllDeferred();
1957
+ const readers = idx.readers.get(sid);
1958
+ if (!readers && !idx.untracked.length) return;
1959
+ mounting = true;
1960
+ try {
1961
+ for (const list of [readers || [], idx.untracked]) for (const [site, occ] of list) {
1962
+ const root = edgeRoots.get(site);
1963
+ if (root && deferredFrames().some(f => root.contains(f.el) && f.mountOccurrence(occ))) continue;
1964
+ const start = startOf(idx, site, occ);
1965
+ const target = start && (start.nextSibling || start);
1966
+ if (target) for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1967
+ }
1968
+ } finally {
1969
+ mounting = false;
1970
+ }
1971
+ deferDone();
1972
+ }
1973
+ let driftReads;
1974
+ const driftWarned = new Set();
1975
+ function watchDeferredMount(site, occ, mount) {
1976
+ const reads = new Set();
1977
+ setReadWatch(node => {
1978
+ const sid = signalName(node);
1979
+ if (sid !== undefined) reads.add(sid);
1980
+ });
1981
+ try {
1982
+ mount();
1983
+ } finally {
1984
+ setReadWatch(null);
1985
+ }
1986
+ const idx = edgeIndex ||= buildEdgeIndex();
1987
+ if (!idx || !idx.sites.has(site) || idx.untracked.some(([s, o]) => s === site && o === occ)) return;
1988
+ if (!driftReads) {
1989
+ driftReads = new Map();
1990
+ for (const [sid, list] of idx.readers) for (const [s, o] of list) {
1991
+ const key = s + " " + o;
1992
+ let set = driftReads.get(key);
1993
+ if (!set) driftReads.set(key, set = new Set());
1994
+ set.add(sid);
1995
+ }
1996
+ }
1997
+ const own = `sc-${site}-${occ}-`;
1998
+ const listed = driftReads.get(site + " " + occ);
1999
+ for (const sid of reads) {
2000
+ if (sid.startsWith(own) || listed?.has(sid) || driftWarned.has(sid)) continue;
2001
+ driftWarned.add(sid);
2002
+ console.warn(`[deferred hydration] The slot occurrence "${occ}" read the signal "${sid}" while mounting, ` + `but the server did not record that read. The client and the server name this signal ` + `differently: a plain signal is created on only one side, under the same component or ` + `owner, before it (code that branches on isServer, or a client-only helper). A write to ` + `it would mount the wrong occurrences. Create such signals after the shared ones, or ` + `under their own owner.`);
2003
+ }
2004
+ }
2005
+ let idlePass;
2006
+ function mountIdle() {
2007
+ return idlePass ||= (async () => {
2008
+ if (document.readyState !== "complete") await new Promise(r => addEventListener("load", r, {
2009
+ once: true
2010
+ }));
2011
+ globalThis._$HY?.r?.["sc:tiers"]?.forEach(prepareTier);
2012
+ await Promise.all(Object.values(tierLoads)).catch(() => {});
2013
+ for (let frames; (frames = deferredFrames()).length;) {
2014
+ await idleTick();
2015
+ const deadline = performance.now() + DEFER_BUDGET;
2016
+ mounting = true;
2017
+ try {
2018
+ for (const f of frames) if (!f.mountDeferred(deadline) || performance.now() > deadline) break;
2019
+ } finally {
2020
+ mounting = false;
2021
+ }
2022
+ }
2023
+ idlePass = undefined;
2024
+ deferDone();
2025
+ })();
2026
+ }
2027
+ function deferDone() {
2028
+ if (deferredFrames().length) return;
2029
+ if (deferring) {
2030
+ deferring = false;
2031
+ edgeIndex = driftReads = undefined;
2032
+ setWriteHook(null);
2033
+ DEFER_EVENTS.forEach(t => document.removeEventListener(t, wakeAt, true));
2034
+ }
2035
+ releaseDeferHolds();
2036
+ }
2037
+ let deferHydration = true;
2038
+ function setDeferredHydration(on) {
2039
+ deferHydration = on;
2040
+ setDeferDriver(on && typeof document !== "undefined" ? deferFrame : null);
2041
+ setSignalIdentities(on && typeof document !== "undefined");
2042
+ setDeferMountWatch(on ? watchDeferredMount : null);
2043
+ }
2044
+ let deferring = false;
2045
+ function deferFrame(frame) {
2046
+ if (!deferring) {
2047
+ deferring = true;
2048
+ setWriteHook(mountForWrite);
2049
+ DEFER_EVENTS.forEach(t => document.addEventListener(t, wakeAt, true));
2050
+ }
2051
+ const queued = sharedConfig.events;
2052
+ if (queued && queued.length) for (const [el, e] of queued) if (frame.el.contains(el)) wakeAt({
2053
+ target: e.target ?? el
2054
+ });
2055
+ mountIdle();
2056
+ }
2073
2057
  function installServerComponents(host = getFrameHost(), options) {
2074
2058
  const g = globalThis;
2075
2059
  Object.assign(tierLoaders, options?.tiers);
@@ -2095,6 +2079,11 @@ function installServerComponents(host = getFrameHost(), options) {
2095
2079
  }
2096
2080
  g._$SC.impl = (id, props, binding) => documentBoundary(host, id, props, binding);
2097
2081
  installRevealHook();
2082
+ if (typeof document !== "undefined" && deferHydration) {
2083
+ setDeferDriver(deferFrame);
2084
+ setSignalIdentities(true);
2085
+ setDeferMountWatch(watchDeferredMount);
2086
+ }
2098
2087
  const handler = createServerComponentHandler({
2099
2088
  host,
2100
2089
  component: fnId => g._$SC.r(fnId),
@@ -2116,4 +2105,4 @@ function installServerComponents(host = getFrameHost(), options) {
2116
2105
  });
2117
2106
  }
2118
2107
 
2119
- export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isAsyncValue, isFrameStreamResponse };
2108
+ export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isFrameStreamResponse, setDeferredHydration };