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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +5165 -0
  3. package/dist/server.js +1876 -374
  4. package/dist/{server.cjs → server.observe.js} +2070 -577
  5. package/dist/{dev.cjs → web.dev.js} +955 -567
  6. package/dist/web.js +646 -350
  7. package/dist/{dev.js → web.observe.js} +699 -421
  8. package/frames/dist/assets.js +92 -0
  9. package/frames/dist/client.dev.js +1296 -1198
  10. package/frames/dist/client.js +1128 -1191
  11. package/frames/dist/client.observe.js +2041 -0
  12. package/frames/dist/regions.js +171 -0
  13. package/frames/dist/server.dev.js +2545 -0
  14. package/frames/dist/server.js +1683 -3004
  15. package/frames/dist/server.observe.js +2544 -0
  16. package/frames/dist/trace.js +45 -0
  17. package/frames/dist/wire.js +594 -0
  18. package/frames/package.json +2 -25
  19. package/package.json +244 -256
  20. package/performance-tracks/dist/performance-tracks.dev.js +679 -0
  21. package/performance-tracks/dist/performance-tracks.js +6 -0
  22. package/performance-tracks/dist/performance-tracks.observe.js +667 -0
  23. package/performance-tracks/package.json +7 -0
  24. package/performance-tracks/types/index.d.ts +69 -0
  25. package/serialization/decode/package.json +2 -15
  26. package/serialization/dist/decode.js +121 -25
  27. package/serialization/dist/serialization.js +282 -88
  28. package/serialization/package.json +2 -15
  29. package/serialization/types/index.d.ts +115 -153
  30. package/serialization/types/serializer-decode.d.ts +173 -114
  31. package/serialization/types/serializer.d.ts +144 -0
  32. package/server-functions/dist/client.dev.js +1462 -0
  33. package/server-functions/dist/client.js +667 -165
  34. package/server-functions/dist/client.observe.js +1441 -0
  35. package/server-functions/dist/rich-args.js +102 -1
  36. package/server-functions/dist/server.dev.js +2802 -299
  37. package/server-functions/dist/server.js +2724 -314
  38. package/server-functions/dist/server.observe.js +3680 -0
  39. package/server-functions/package.json +2 -35
  40. package/server-functions/rich-args/package.json +2 -15
  41. package/skills/server-components/SKILL.md +117 -0
  42. package/storage/package.json +2 -15
  43. package/types/client.d.ts +342 -288
  44. package/types/constants.d.ts +22 -0
  45. package/types/cookies.d.ts +32 -84
  46. package/types/diagnostics.d.ts +80 -0
  47. package/types/frames/assets-tier.d.ts +78 -0
  48. package/types/frames/client.d.ts +40 -1
  49. package/types/frames/frame-client.d.ts +443 -280
  50. package/types/frames/frame-container-plugin.d.ts +64 -0
  51. package/types/frames/frame-morph.d.ts +29 -0
  52. package/types/frames/frame-sink.d.ts +141 -161
  53. package/types/frames/frame-transport.d.ts +263 -184
  54. package/types/frames/regions-tier.d.ts +60 -0
  55. package/types/frames/serializer-decode.d.ts +241 -0
  56. package/types/frames/serializer.d.ts +115 -153
  57. package/types/frames/server.d.ts +2 -2
  58. package/types/frames/trace-tier.d.ts +2 -0
  59. package/types/frames/tree-rewrite.d.ts +39 -0
  60. package/types/frames/wire-tier.d.ts +169 -0
  61. package/types/head.d.ts +20 -0
  62. package/types/index.d.ts +98 -81
  63. package/types/index.server.d.ts +159 -0
  64. package/types/jsx.d.ts +49 -44
  65. package/types/observe.d.ts +535 -0
  66. package/types/reconcile.d.ts +1 -0
  67. package/types/render.d.ts +11 -0
  68. package/types/request-error-hook.d.ts +5 -0
  69. package/types/response.d.ts +95 -147
  70. package/types/serializer-decode.d.ts +173 -114
  71. package/types/serializer.d.ts +115 -153
  72. package/types/server-functions/argument-codec.d.ts +30 -0
  73. package/types/server-functions/client.d.ts +237 -223
  74. package/types/server-functions/flash.d.ts +28 -30
  75. package/types/server-functions/registry.d.ts +105 -0
  76. package/types/server-functions/rich-args.d.ts +1 -10
  77. package/types/server-functions/server.d.ts +538 -531
  78. package/types/server-functions/shared.d.ts +398 -425
  79. package/types/server-functions/uploads.d.ts +53 -0
  80. package/types/server-mock.d.ts +154 -20
  81. package/types/server-observe.d.ts +86 -0
  82. package/types/server.d.ts +601 -422
  83. package/types/trace.d.ts +127 -0
  84. package/LICENSE +0 -21
  85. package/dist/web.cjs +0 -2033
  86. package/frames/dist/client.cjs +0 -2002
  87. package/frames/dist/client.dev.cjs +0 -2022
  88. package/frames/dist/server.cjs +0 -3877
  89. package/serialization/dist/decode.cjs +0 -139
  90. package/serialization/dist/serialization.cjs +0 -261
  91. package/serialization/types-cjs/index.d.cts +0 -182
  92. package/serialization/types-cjs/package.json +0 -3
  93. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  94. package/server-functions/dist/client.cjs +0 -834
  95. package/server-functions/dist/rich-args.cjs +0 -11
  96. package/server-functions/dist/server.cjs +0 -1242
  97. package/server-functions/dist/server.dev.cjs +0 -1242
  98. package/storage/dist/storage.cjs +0 -12
  99. package/storage/types-cjs/index.d.cts +0 -28
  100. package/storage/types-cjs/package.json +0 -3
  101. package/types/core.d.ts +0 -9
  102. package/types-cjs/client.d.cts +0 -337
  103. package/types-cjs/cookies.d.cts +0 -93
  104. package/types-cjs/core.d.cts +0 -9
  105. package/types-cjs/frames/client.d.cts +0 -36
  106. package/types-cjs/frames/frame-client.d.cts +0 -356
  107. package/types-cjs/frames/frame-sink.d.cts +0 -194
  108. package/types-cjs/frames/frame-transport.d.cts +0 -222
  109. package/types-cjs/frames/serializer.d.cts +0 -182
  110. package/types-cjs/frames/server.d.cts +0 -52
  111. package/types-cjs/index.d.cts +0 -244
  112. package/types-cjs/jsx-properties.d.cts +0 -93
  113. package/types-cjs/jsx.d.cts +0 -4159
  114. package/types-cjs/package.json +0 -3
  115. package/types-cjs/response.d.cts +0 -174
  116. package/types-cjs/serializer-decode.d.cts +0 -182
  117. package/types-cjs/serializer.d.cts +0 -182
  118. package/types-cjs/server-functions/client.d.cts +0 -262
  119. package/types-cjs/server-functions/flash.d.cts +0 -38
  120. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  121. package/types-cjs/server-functions/server.d.cts +0 -681
  122. package/types-cjs/server-functions/shared.d.cts +0 -523
  123. package/types-cjs/server-mock.d.cts +0 -286
  124. package/types-cjs/server.d.cts +0 -544
@@ -1,162 +1,38 @@
1
- import { getOwner, onCleanup, createMemo, runWithOwner, createSignal, createRenderEffect, createLoadingBoundary, createOwner, sharedConfig, materializeContainerTrace } from 'solid-js';
2
- import { delegateEvents, insert } from '@solidjs/web';
3
- import { ChunkReader, frameAddress, SINGLE_FLIGHT_HEADER, deserializeStream, getServerFunctionsCodec, createChunk, getFlightDataConsumer, ERROR_HEADER, REVALIDATE_HEADER, configureServerFunctionsClient } from '@solidjs/web/server-functions/client';
1
+ import { getOwner, onCleanup, createMemo, runWithOwner, untrack, createRenderEffect, onHydrationEnd, createSignal, createOwner } from 'solid-js';
2
+ import { installServerComponentHydration, insert } from '@solidjs/web';
3
+ import { LIVE_WIRE, ChunkReader, frameAddress, SINGLE_FLIGHT_HEADER, deserializeStream, getServerFunctionsCodec, createChunk, deliverFlightData, ERROR_HEADER, hasFlightMetadata, configureServerFunctionsClient } from '@solidjs/web/server-functions/client';
4
+ import { setSignalIdentities, sharedConfig, createLoadingBoundary, setWriteHook, signalName, storeName } from 'solid-js/internal';
4
5
 
5
6
  const ELEMENT_NODE = 1;
6
- const TEXT_NODE = 3;
7
7
  const COMMENT_NODE = 8;
8
- const CLAIM_SEAM = Symbol.for("dom-expressions.element-claims");
8
+ const CLAIM_SEAM = Symbol.for("solid.element-claims");
9
9
  const CLAIMED_ELEMENTS = "a[href], form[action]";
10
10
  function claimHandlers() {
11
11
  const handlers = globalThis[CLAIM_SEAM];
12
12
  return handlers !== undefined && handlers.length !== 0 ? handlers : undefined;
13
13
  }
14
- function claimNode(handlers, el) {
15
- for (let i = 0; i < handlers.length; i++) handlers[i](el);
16
- }
17
- const claimedAttr = name => name === "href" || name === "action";
18
- const BOUND_SEAM = Symbol.for("dx.bnd");
19
- const boundSeam = globalThis[BOUND_SEAM] || (globalThis[BOUND_SEAM] = {});
20
- const BND_ATTR = "_bnd";
21
- const BND_SELECTOR = "[_bnd]";
22
- function bndMap(el) {
23
- const s = el.getAttribute(BND_ATTR);
24
- if (!s) return undefined;
25
- const map = {};
26
- for (const entry of s.split(",")) {
27
- const eq = entry.indexOf("=");
28
- if (eq < 1) continue;
29
- const pos = entry.slice(0, eq);
30
- const prop = decodeURIComponent(entry.slice(eq + 1));
31
- const prev = map[pos];
32
- if (prev === undefined) map[pos] = prop;else if (Array.isArray(prev)) prev.push(prop);else map[pos] = [prev, prop];
33
- }
34
- return map;
35
- }
36
- boundSeam.resolve = (el, type) => {
37
- const frame = el._$bndFrame;
38
- if (!frame) return undefined;
39
- const map = bndMap(el);
40
- const prop = map && map[type];
41
- if (typeof prop !== "string") return undefined;
42
- return claimFn(frame, type, prop);
43
- };
44
- function claimFn(frame, pos, prop) {
45
- const fn = frame.clientProp(prop);
46
- if (typeof fn === "function") return fn;
47
- return undefined;
48
- }
49
- function sweepBound(root, frame, delegate, scope) {
50
- const isElement = root.nodeType === ELEMENT_NODE;
51
- if (!isElement && root.nodeType !== 11 ) return;
52
- let els;
53
- if (isElement && root.hasAttribute(BND_ATTR)) (els = []).push(root);
54
- const found = root.querySelectorAll(BND_SELECTOR);
55
- if (found.length) {
56
- els || (els = []);
57
- for (let i = 0; i < found.length; i++) els.push(found[i]);
58
- }
59
- if (!els) return;
60
- const run = () => {
61
- let types;
62
- for (const el of els) {
63
- el._$bndFrame = frame;
64
- const map = bndMap(el);
65
- if (!map) continue;
66
- for (const pos in map) {
67
- if (pos === "ref") fireRefs(frame, el, map.ref);else (types || (types = [])).push(pos);
68
- }
69
- }
70
- if (types && delegate) delegate(types);
71
- };
72
- scope ? scope(run) : run();
73
- }
74
- function fireRefs(frame, el, prop) {
75
- const fired = el._$bndFired || (el._$bndFired = new Set());
76
- for (const p of Array.isArray(prop) ? prop : [prop]) {
77
- if (fired.has(p)) continue;
78
- fired.add(p);
79
- const fn = claimFn(frame, "ref", p);
80
- if (fn) fn(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);
81
19
  }
20
+ for (let i = 0; i < handlers.length; i++) handlers[i](el);
82
21
  }
83
- function claimTree(handlers, root) {
22
+ function claimTree(handlers, root, adopter) {
84
23
  const isElement = root.nodeType === ELEMENT_NODE;
85
24
  if (!isElement && root.nodeType !== 11 ) return;
86
- if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root);
25
+ if (isElement && root.matches(CLAIMED_ELEMENTS)) claimNode(handlers, root, adopter);
87
26
  const found = root.querySelectorAll(CLAIMED_ELEMENTS);
88
- 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);
89
28
  }
29
+ const adoptedBy = new WeakMap();
90
30
  const placeholderId = name => `pl-${name}`;
91
31
  const SLOT_START = /^slot:(.+):start$/;
92
32
  const SLOT_END = /^slot:(.+):end$/;
93
33
  const slotEnd = id => `slot:${id}:end`;
94
- function chunkToRecords(chunk) {
95
- switch (chunk.type) {
96
- case "start":
97
- case "data":
98
- return {};
99
- case "html":
100
- return {
101
- "": {
102
- kind: "html",
103
- value: chunk.html
104
- }
105
- };
106
- case "fragment":
107
- return {
108
- [`seg:${chunk.key}`]: {
109
- kind: "html",
110
- value: chunk.html
111
- }
112
- };
113
- case "reveal":
114
- {
115
- const records = {};
116
- const gate = chunk.fallback ? "fallback" : "reveal";
117
- for (const key of chunk.keys) records[`seg:${key}:${gate}`] = true;
118
- return records;
119
- }
120
- case "assets":
121
- return {
122
- [`seg:${chunk.key}:assets`]: chunk
123
- };
124
- case "slot":
125
- return {
126
- [`slot:${chunk.key}`]: {
127
- kind: "slot",
128
- args: chunk.args
129
- }
130
- };
131
- case "hole":
132
- return {
133
- [`hole:${chunk.key}`]: {
134
- kind: "html",
135
- value: chunk.html
136
- }
137
- };
138
- case "attr":
139
- return {
140
- [`attr:${chunk.key}`]: {
141
- kind: "attrs",
142
- value: chunk.attrs,
143
- removed: chunk.removed
144
- }
145
- };
146
- case "complete":
147
- return {
148
- ":complete": true
149
- };
150
- case "error":
151
- if (!chunk.key) return {
152
- ":error": chunk.error
153
- };
154
- return {
155
- [`${/^lha?:/.test(chunk.key) ? "hole" : "seg"}:${chunk.key}:error`]: chunk.error
156
- };
157
- default:
158
- return {};
159
- }
34
+ function isAsyncValue(v) {
35
+ return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
160
36
  }
161
37
  function createFrameHost(options = {}) {
162
38
  const frames = new Map();
@@ -169,28 +45,77 @@ function createFrameHost(options = {}) {
169
45
  });
170
46
  return store;
171
47
  };
48
+ const landings = new Map();
49
+ const lands = records => "" in records || ":error" in records || ":complete" in records;
50
+ const applyTo = (id, version, r) => {
51
+ const set = frames.get(id);
52
+ if (set) for (const frame of set) frame.apply({
53
+ version,
54
+ r
55
+ });
56
+ };
172
57
  const write = (store, version, records) => {
173
58
  if (store.version !== undefined && version < store.version) return false;
174
59
  if (store.version === undefined || version > store.version) {
175
60
  store.version = version;
176
- clearStreamRecords(store.records);
61
+ store.records = {};
177
62
  }
63
+ const assets = records["seg::assets"];
64
+ const previous = assets && store.records["seg::assets"];
178
65
  Object.assign(store.records, records);
66
+ if (previous && previous !== assets) {
67
+ const merged = {
68
+ ...previous
69
+ };
70
+ for (const name in assets) {
71
+ const values = assets[name];
72
+ if (Array.isArray(values)) merged[name] = previous[name] ? previous[name].concat(values) : values;
73
+ }
74
+ store.records["seg::assets"] = merged;
75
+ }
179
76
  return true;
180
77
  };
78
+ const settleArgs = (store, recordKey, record, chunk) => {
79
+ const args = record.args;
80
+ const out = {};
81
+ let regions, decoded;
82
+ const settle = () => {
83
+ if (! --record.pending && store.records[recordKey] === record) applyTo(chunk.id, store.version, {
84
+ [recordKey]: record
85
+ });
86
+ };
87
+ for (const key in args) {
88
+ const value = args[key];
89
+ if (value && typeof value.$ref === "string") {
90
+ const resolved = out[key] = options.resolve && options.resolve(value, chunk.id, chunk.version, store.version);
91
+ (decoded ??= {})[key] = true;
92
+ if (resolved instanceof Promise && resolved.s === 0) {
93
+ record.pending = (record.pending || 0) + 1;
94
+ resolved.c.push(settle);
95
+ }
96
+ } else {
97
+ if (value && typeof value.$frame === "string") (regions ??= {})[key] = value.$frame;
98
+ out[key] = value;
99
+ }
100
+ }
101
+ record.args = out;
102
+ record.regions = regions;
103
+ record.decoded = decoded;
104
+ };
181
105
  return {
182
- delegate: options.delegate,
183
106
  register(id, frame) {
184
107
  let set = frames.get(id);
185
108
  if (!set) frames.set(id, set = new Set());
186
109
  set.add(frame);
187
110
  const store = stores.get(id);
188
111
  if (store && store.version !== undefined) {
189
- frame.apply({
112
+ if (!store.open) frame.apply({
190
113
  version: store.version,
191
114
  r: store.records
115
+ });else if (store.shown) frame.apply({
116
+ version: store.shownVersion,
117
+ r: store.shown
192
118
  });
193
- frame.rebase && frame.rebase();
194
119
  }
195
120
  },
196
121
  unregister(id, frame) {
@@ -208,26 +133,77 @@ function createFrameHost(options = {}) {
208
133
  value: html
209
134
  };
210
135
  if (store.version === undefined) store.version = 0;
136
+ store.shown = store.records;
137
+ store.shownVersion = store.version;
211
138
  }
212
139
  }
213
140
  }
214
141
  }
215
- if (!frame) stores.delete(id);
142
+ if (!frame) {
143
+ stores.delete(id);
144
+ landings.delete(id);
145
+ }
216
146
  },
217
- apply(chunk) {
218
- if (chunk.type === "data") {
219
- options.applyData && options.applyData(chunk);
147
+ apply(msg) {
148
+ if (msg.type === "data") {
149
+ const store = stores.get(msg.id);
150
+ const current = store && store.version;
151
+ if (store && msg.version < current) return;
152
+ options.applyData && options.applyData(msg, current);
220
153
  return;
221
154
  }
222
- const records = chunkToRecords(chunk);
223
- if (!write(storeFor(chunk.id), chunk.version, records)) return;
224
- const set = frames.get(chunk.id);
225
- if (set) {
226
- for (const frame of set) frame.apply({
227
- version: chunk.version,
228
- r: records
229
- });
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
+ };
165
+ }
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
+ let r = records;
170
+ if (msg.type === "start") {
171
+ store.open = true;
172
+ } else if (lands(records)) {
173
+ store.open = false;
174
+ store.shown = r = store.records;
175
+ store.shownVersion = msg.version;
176
+ const landed = landings.get(msg.id);
177
+ if (landed && !(":complete" in records && ":error" in r)) {
178
+ landings.delete(msg.id);
179
+ ":error" in records ? landed.j(records[":error"]) : landed.r();
180
+ }
181
+ }
182
+ applyTo(msg.id, msg.version, r);
183
+ if (":complete" in records || ":error" in records) options.closeData && options.closeData(msg.id, msg.version, records[":error"]);
184
+ },
185
+ landing(id) {
186
+ const store = stores.get(id);
187
+ if (!store || !store.open && !store.shown) return undefined;
188
+ if (store.shown && !(":error" in store.shown)) return undefined;
189
+ let wait = landings.get(id);
190
+ if (!wait) {
191
+ landings.set(id, wait = {});
192
+ wait.p = new Promise((r, j) => (wait.r = r, wait.j = j));
193
+ }
194
+ return wait.p;
195
+ },
196
+ preview(msg) {
197
+ const set = frames.get(msg.id);
198
+ if (!set || !msg.r) return;
199
+ let records;
200
+ for (const key in msg.r) if (key.startsWith("slot:")) {
201
+ const record = (records ??= {})[key] = {
202
+ ...msg.r[key]
203
+ };
204
+ settleArgs(storeFor(msg.id), key, record, msg);
230
205
  }
206
+ if (records) for (const frame of set) frame.preview && frame.preview(records);
231
207
  },
232
208
  get(id) {
233
209
  const set = frames.get(id);
@@ -237,83 +213,119 @@ function createFrameHost(options = {}) {
237
213
  if (!options.serialize) throw new Error("host has no serializer");
238
214
  return options.serialize(value);
239
215
  },
240
- resolve(ref, frameId) {
241
- return options.resolve ? options.resolve(ref, frameId) : undefined;
242
- },
243
216
  revive: options.revive,
244
- isContainer: options.isContainer,
245
217
  prepareData: options.prepareData
246
218
  };
247
219
  }
248
220
  const FRAME_APPLIED_EVENT = "frame:applied";
221
+ const tierLoaders = {};
222
+ const tierLoads = {};
223
+ const liveFrames = new Set();
224
+ let deferDriver = null;
225
+ function setDeferDriver(driver) {
226
+ deferDriver = driver;
227
+ }
228
+ function deferredFrames() {
229
+ return [...liveFrames].filter(f => f.deferred);
230
+ }
231
+ function releaseDeferHolds() {
232
+ for (const f of liveFrames) f.releaseDeferHold();
233
+ }
234
+ function hasSlotRange(root) {
235
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
236
+ for (let n; n = w.nextNode();) if (n.data.startsWith("slot:")) return true;
237
+ return false;
238
+ }
239
+ function liveFrameAt(node) {
240
+ let hit;
241
+ for (const f of liveFrames) if (f.el.contains(node) && (!hit || hit.el.contains(f.el))) hit = f;
242
+ return hit;
243
+ }
244
+ function prepareTier(name) {
245
+ let load = tierLoads[name];
246
+ if (!load) {
247
+ const loader = tierLoaders[name];
248
+ tierLoads[name] = load = loader ? loader().then(module => {
249
+ load.r = module;
250
+ module.install?.();
251
+ for (const frame of liveFrames) frame.apply({
252
+ version: frame.version,
253
+ r: {}
254
+ });
255
+ }) : Promise.resolve();
256
+ }
257
+ return load;
258
+ }
259
+ const prepareMorph = () => liveFrames.size && prepareTier("wire");
260
+ const tierReady = name => !tierLoaders[name] || prepareTier(name).r;
261
+ const needsRegions = record => record.regions && !tierReady("regions");
262
+ const carriesTrace = value => value != null && typeof value === "object" && (value.$tr != null || Object.values(value).some(carriesTrace));
263
+ const needsTrace = args => !tierLoads.trace?.r && carriesTrace(args) && !tierReady("trace");
249
264
  class FrameImpl {
250
265
  #element;
251
- #start;
252
- #end;
253
266
  #options;
267
+ #outer;
254
268
  #version;
255
269
  #store = Object.create(null);
256
- #appliedRootValue;
270
+ #content = new Set();
271
+ #appliedRoot;
272
+ #appliedError;
257
273
  #hasContent = false;
258
- #errorNotified = false;
259
- #revealed = new Set();
260
- #fallbackShown = new Set();
261
274
  #appliedHoles = new Map();
275
+ #liveTargets = new Map();
276
+ #shows = {};
277
+ #liveMount;
262
278
  #slots;
263
279
  #mountedSlots = new Set();
264
280
  #slotCleanups = new Map();
265
281
  #slotArgs = new Map();
266
282
  #slotUpdaters = new Map();
267
- #slotRegions = new Map();
268
- #slotResolvedRefs = new Map();
269
- #slotNodes = new Map();
270
- #processedAssets = new Set();
271
- #recordRefresh = null;
283
+ #hold;
284
+ #heldRecords = new Map();
285
+ #found;
286
+ #waiting = new Set();
272
287
  #disposed = false;
273
- #styleFlush = () => {
274
- if (!this.#disposed) this.#flush();
275
- };
276
- #claimTree = (node, direct) => {
277
- if (!direct && node.nodeType !== TEXT_NODE && node.nodeType !== COMMENT_NODE) {
278
- const o = this.#options;
279
- sweepBound(node, this, o.delegate || o.host && o.host.delegate, o.ownerScope);
280
- }
288
+ #defers = false;
289
+ #deferred = false;
290
+ #deferFound;
291
+ #deferWaiting = false;
292
+ #deferMounted = new Map();
293
+ #deferHold;
294
+ #claimTree = (node, direct, adopter) => {
281
295
  const handlers = claimHandlers();
282
296
  if (!handlers) return;
283
- this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node));
297
+ this.#scoped(() => direct ? claimNode(handlers, node) : claimTree(handlers, node, adopter));
284
298
  };
285
- clientProp(name) {
286
- const props = this.#options.props;
287
- return props ? props[name] : undefined;
288
- }
289
299
  #scoped(fn) {
290
300
  const scope = this.#options.ownerScope;
291
301
  return scope ? scope(fn) : fn();
292
302
  }
293
- constructor(element, start, end, options = {}) {
303
+ constructor(element, options = {}) {
294
304
  this.#element = element;
295
- this.#start = start;
296
- this.#end = end;
297
305
  this.#options = options;
298
306
  this.#slots = options.slots;
307
+ this.#outer = options.parent;
308
+ liveFrames.add(this);
299
309
  if (options.adopt) {
300
310
  this.#hasContent = true;
301
311
  this.#claimContent();
312
+ this.#defers = !!deferDriver && !!(options.defer || this.#outer?.defers);
313
+ this.#deferred = this.#defers && !!(this.#slots || this.#outer) && hasSlotRange(element);
302
314
  }
303
315
  if (options.host && options.id !== undefined) {
304
316
  options.host.register(options.id, this);
305
317
  }
306
- if (options.adopt && this.#version === undefined) this.#syncSlots();
307
- }
308
- #parent() {
309
- return this.#element ?? this.#start.parentNode;
318
+ if (this.#deferred) {
319
+ this.#deferHold = options.hold?.();
320
+ deferDriver(this);
321
+ } else if (options.adopt && this.#version === undefined) this.#syncSlots();
310
322
  }
311
323
  #applied(version, reason) {
312
324
  this.#options.onApply?.({
313
325
  version,
314
326
  reason
315
327
  });
316
- const parent = this.#parent();
328
+ const parent = this.#element;
317
329
  const Ev = parent && (parent.ownerDocument || parent).defaultView?.CustomEvent;
318
330
  if (Ev) {
319
331
  parent.dispatchEvent(new Ev(FRAME_APPLIED_EVENT, {
@@ -326,18 +338,12 @@ class FrameImpl {
326
338
  }));
327
339
  }
328
340
  }
329
- #firstContent() {
330
- return this.#start ? this.#start.nextSibling : this.#parent().firstChild;
331
- }
332
341
  get version() {
333
342
  return this.#version;
334
343
  }
335
344
  get store() {
336
345
  return this.#store;
337
346
  }
338
- isRevealed(segment) {
339
- return this.#revealed.has(segment);
340
- }
341
347
  get error() {
342
348
  return this.#store[":error"];
343
349
  }
@@ -352,162 +358,273 @@ class FrameImpl {
352
358
  this.#version = v;
353
359
  this.#resetStreamState();
354
360
  }
361
+ let only = [];
355
362
  for (const key in write.r) {
356
- const incoming = write.r[key];
357
- if (incoming && incoming.kind === "slot" && key.charCodeAt(0) === 115 && key.startsWith("slot:")) {
358
- const existing = this.#store[key];
359
- if (existing && existing.kind === "slot" && argsEquivalent(existing.args, incoming.args)) {
360
- continue;
361
- }
362
- }
363
- this.#store[key] = incoming;
363
+ const prev = this.#store[key];
364
+ const occurrence = key.slice(5);
365
+ if (this.#deferred && prev?.kind === "slot" && !prev.pending && !this.#mountedSlots.has(occurrence)) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, prev);
366
+ this.#store[key] = write.r[key];
367
+ if (key.startsWith("slot:")) only?.push(occurrence);else this.#content.add(key), only = undefined;
364
368
  }
365
- this.#flush();
366
- }
367
- #resetStreamState(root) {
368
- this.#revealed.clear();
369
- this.#fallbackShown.clear();
369
+ this.#flush(only?.length ? only : undefined);
370
+ }
371
+ preview(records, inherited) {
372
+ const adopted = new Set();
373
+ if (this.#disposed) return adopted;
374
+ const R = tierLoads.regions?.r;
375
+ for (const key in records) {
376
+ const record = records[key];
377
+ if (!record || record.kind !== "slot" || !key.startsWith("slot:")) continue;
378
+ if (inherited && key in this.#store) continue;
379
+ const occurrence = key.slice(5);
380
+ const update = this.#mountedSlots.has(occurrence) && this.#slotUpdaters.get(occurrence);
381
+ if (!update || (R ? R.changed(this, occurrence, record) : record.regions)) continue;
382
+ this.#slotArgs.set(occurrence, record);
383
+ adopted.add(key);
384
+ update(this.#resolveArgs(occurrence, record));
385
+ }
386
+ if (R) for (const frame of R.frames(this)) for (const key of frame.preview(records, true)) adopted.add(key);
387
+ if (!inherited) for (const key of adopted) this.#store[key] = records[key];
388
+ return adopted;
389
+ }
390
+ #resetStreamState() {
391
+ if (this.#hasContent) prepareTier("wire");
392
+ this.#found = undefined;
393
+ this.#store = Object.create(null);
394
+ this.#content.clear();
395
+ this.#appliedRoot = this.#appliedError = undefined;
370
396
  this.#appliedHoles.clear();
371
- this.#errorNotified = false;
372
- clearStreamRecords(this.#store, root);
397
+ this.#liveTargets.clear();
398
+ this.#shows = {};
373
399
  }
374
- #flush() {
400
+ #flush(only) {
375
401
  if (this.#disposed) return;
376
402
  const version = this.#version;
377
403
  const root = this.#store[""];
378
- if (root && root.kind === "html" && root.value !== this.#appliedRootValue) {
379
- const reason = this.#hasContent ? "morph" : "materialize";
380
- this.#applyRoot(root.value);
381
- this.#appliedRootValue = root.value;
404
+ const applied = this.#appliedRoot;
405
+ if (root && root.kind === "html" && root !== this.#appliedRoot) {
406
+ const wire = this.#hasContent ? tierReady("wire") : null;
407
+ if (wire === undefined) return;
408
+ const reason = wire ? "morph" : "materialize";
409
+ this.#applyRoot(root.value, wire);
410
+ this.#appliedRoot = root;
411
+ this.#recordHave("", root);
382
412
  this.#applied(version, reason);
383
413
  }
384
- if (this.#store[":error"] && !this.#errorNotified) {
385
- this.#errorNotified = true;
414
+ const error = this.#store[":error"];
415
+ if (error && error !== this.#appliedError) {
416
+ this.#appliedError = error;
386
417
  this.#applied(version, "error");
387
418
  }
388
- let progressed = true;
389
- while (progressed) {
390
- progressed = false;
391
- for (const key in this.#store) {
392
- const name = segmentName(key);
393
- if (name === null || this.#revealed.has(name)) continue;
394
- if (this.#segmentReady(name)) {
395
- this.#revealSegment(name);
396
- this.#applied(version, "reveal");
397
- progressed = true;
398
- }
399
- }
400
- for (const key in this.#store) {
401
- const m = /^seg:([^:]+):fallback$/.exec(key);
402
- if (!m) continue;
403
- const name = m[1];
404
- if (this.#revealed.has(name) || this.#fallbackShown.has(name)) continue;
405
- if (this.#showFallback(name)) {
406
- this.#fallbackShown.add(name);
407
- this.#applied(version, "reveal");
408
- progressed = true;
409
- }
410
- }
419
+ for (const key of this.#content) {
420
+ const record = this.#store[key];
421
+ if (!key.endsWith(":assets") || !record || this.#appliedHoles.get(key) === record) continue;
422
+ const tier = tierReady("assets");
423
+ if (!tier) break;
424
+ this.#appliedHoles.set(key, record);
425
+ tier.apply(record);
411
426
  }
412
- for (const key in this.#store) {
427
+ const revealed = this.#revealSegments();
428
+ let morphed = false;
429
+ const index = {};
430
+ let wire;
431
+ for (const key of this.#content) {
413
432
  const record = this.#store[key];
414
433
  if (!record || this.#appliedHoles.get(key) === record) continue;
415
434
  if (key.startsWith("hole:")) {
416
435
  if (key.endsWith(":error")) {
417
436
  this.#appliedHoles.set(key, record);
418
- } else if (this.#applyHole(key.slice(5), record.value)) {
419
- this.#appliedHoles.set(key, record);
420
- this.#applied(version, "morph");
437
+ continue;
421
438
  }
422
- } else if (key.startsWith("attr:")) {
423
- if (this.#applyAttrs(key.slice(5), record.value, record.removed)) {
424
- this.#appliedHoles.set(key, record);
425
- this.#applied(version, "morph");
439
+ } else if (!key.startsWith("attr:")) continue;
440
+ if (!this.#hasContent || !(wire ??= tierReady("wire"))) continue;
441
+ const name = key.slice(5);
442
+ const attr = key[0] === "a";
443
+ if (!attr) this.#found = undefined;
444
+ if (attr ? wire.attrs(this.#live, name, record) : wire.hole(this.#live, name, record, index)) {
445
+ this.#appliedHoles.set(key, record);
446
+ this.#recordHave(attr ? "lha:" + name : name, record);
447
+ morphed = true;
448
+ }
449
+ }
450
+ if (index.r?.size) wire.graft(index.g, index.r);
451
+ if (morphed) this.#applied(version, "morph");
452
+ if (this.#deferred) {
453
+ if (!morphed && this.#appliedRoot === applied) {
454
+ if (revealed || !only) this.#deferFound = undefined;
455
+ const mounted = only ? new Map() : new Map(this.#deferMounted);
456
+ if (only) for (const id of only) {
457
+ const start = this.#deferMounted.get(id);
458
+ if (start) mounted.set(id, start);else if (!this.#deferFound?.has(id)) this.#deferFound = undefined;
426
459
  }
460
+ if (mounted.size) this.#deferWaiting = this.#mountFound(mounted) || this.#deferWaiting;
461
+ return;
427
462
  }
463
+ this.#deferred = false;
464
+ this.#deferFound = undefined;
465
+ this.#deferMounted.clear();
428
466
  }
429
- for (const key in this.#store) {
430
- if (this.#processedAssets.has(key) || !key.endsWith(":assets")) continue;
431
- this.#processedAssets.add(key);
432
- const record = this.#store[key];
433
- if (record && record.modules) {
434
- for (const href of record.modules) ensureModulePreload(href);
467
+ const found = this.#found;
468
+ if (only && found && this.#appliedRoot === applied) {
469
+ const sub = new Map();
470
+ for (const id of only) {
471
+ const start = found.get(id);
472
+ if (!start?.isConnected) return this.#syncSlots();
473
+ sub.set(id, start);
435
474
  }
475
+ this.#mountFound(sub);
476
+ return this.#holdIf(this.#waiting.size);
436
477
  }
437
478
  this.#syncSlots();
438
479
  }
439
480
  #resolveSlot(prop) {
440
- return this.#slots?.[prop] ?? this.#options.resolveSlot?.(prop);
481
+ return this.#slots?.[prop] ?? (this.#outer && this.#outer.#resolveSlot(prop));
441
482
  }
442
483
  #resolveSlotRecord(occurrence) {
443
484
  const record = this.#store[`slot:${occurrence}`];
444
485
  if (record !== undefined) return record;
445
- return this.#options.resolveSlotRecord?.(occurrence);
486
+ return this.#outer && this.#outer.#resolveSlotRecord(occurrence);
446
487
  }
447
488
  #removeSlotRecord(occurrence) {
448
489
  const key = `slot:${occurrence}`;
449
490
  if (key in this.#store) {
450
491
  if (!this.#mountedSlots.has(occurrence)) delete this.#store[key];
451
- } else this.#options.removeSlotRecord?.(occurrence);
492
+ } else this.#outer && this.#outer.#removeSlotRecord(occurrence);
452
493
  }
453
494
  #syncSlots(root) {
454
- if (!this.#slots && !this.#options.resolveSlot) return;
495
+ if (!this.#slots && !this.#outer) return;
455
496
  const found = new Map();
456
- if (root) collectSlots(root.firstChild, null, found);else this.#collectSlots(found);
497
+ this.#collectSlots(found, root);
498
+ if (root) this.#found = undefined;else this.#found = found, this.#waiting.clear();
499
+ const waiting = this.#mountFound(found);
500
+ if (!root) {
501
+ for (const occurrence of [...this.#mountedSlots]) {
502
+ if (!found.has(occurrence)) this.#unmountSlot(occurrence);
503
+ }
504
+ this.#holdIf(waiting);
505
+ }
506
+ }
507
+ #holdIf(waiting) {
508
+ if (waiting && !this.#hold) this.#hold = this.#options.hold?.();else if (!waiting && this.#hold) this.#releaseHold();
509
+ }
510
+ #mountFound(found) {
511
+ let waiting = false;
512
+ const R = tierLoads.regions?.r;
457
513
  for (const [occurrence, start] of found) {
514
+ this.#waiting.delete(occurrence);
458
515
  const callback = this.#resolveSlot(propOf(occurrence));
459
516
  if (!callback) continue;
460
517
  const record = this.#resolveSlotRecord(occurrence);
461
- if (record && record.kind === "slot" && this.#refsUnresolved(record.args)) continue;
462
- const prev = this.#slotNodes.get(occurrence);
463
- const prevFirst = Array.isArray(prev) ? prev[0] : prev;
464
- const zombie = this.#mountedSlots.has(occurrence) && prevFirst && !prevFirst.parentNode;
465
- if (zombie) {
466
- this.#mountedSlots.delete(occurrence);
467
- this.#runSlotCleanups(occurrence);
518
+ const mounted = this.#mountedSlots.has(occurrence);
519
+ if (record === undefined && isCalled(occurrence)) {
520
+ if (!mounted) waiting = true, this.#waiting.add(occurrence);
521
+ continue;
468
522
  }
469
- if (!this.#mountedSlots.has(occurrence)) {
470
- if (record === undefined && !root && this.#options.adopt && this.#options.recordsPending?.()) {
471
- this.#recordRefresh ??= setTimeout(() => {
472
- this.#recordRefresh = null;
473
- if (this.#disposed) return;
474
- this.#options.drainRecords?.();
475
- this.#syncSlots();
476
- });
477
- continue;
478
- }
479
- if (this.#options.adopt) this.#discoverRegions(occurrence, start);
480
- const nodes = this.#invokeSlot(occurrence, callback, record, start, this.#options.adopt);
481
- if (nodes) this.#replaceRange(occurrence, start, nodes);
482
- this.#slotNodes.set(occurrence, nodes);
523
+ if (!mounted && record && (record.pending || needsRegions(record) || needsTrace(record.args))) {
524
+ waiting = true;
525
+ this.#waiting.add(occurrence);
526
+ if (this.#options.adopt) this.#heldRecords.has(occurrence) || this.#heldRecords.set(occurrence, record);
527
+ continue;
528
+ }
529
+ if (!mounted) {
530
+ const held = this.#heldRecords.get(occurrence);
531
+ this.#heldRecords.delete(occurrence);
532
+ const mountRecord = held || record;
533
+ this.#invokeSlot(occurrence, callback, mountRecord, start, this.#options.adopt);
483
534
  this.#mountedSlots.add(occurrence);
484
- if (!this.#options.adopt || nodes) this.#discoverRegions(occurrence, start);
485
- this.#bindRegions(occurrence);
486
- } else if (record !== this.#slotArgs.get(occurrence)) {
487
- if (this.#refArgsUnchanged(occurrence, record)) {
488
- this.#slotArgs.set(occurrence, record);
489
- this.#reconcileRegions(occurrence, record);
490
- continue;
491
- }
535
+ R?.bind(this, occurrence);
536
+ if (mountRecord === record || !record || record.kind !== "slot") continue;
537
+ }
538
+ if (record !== this.#slotArgs.get(occurrence)) {
539
+ if (needsRegions(record) || needsTrace(record.args)) continue;
492
540
  const update = this.#slotUpdaters.get(occurrence);
493
541
  if (update) {
494
- const props = this.#resolveArgs(occurrence, record.args);
542
+ const props = this.#resolveArgs(occurrence, record);
495
543
  this.#slotArgs.set(occurrence, record);
496
544
  update(props);
497
- this.#bindRegions(occurrence);
545
+ R?.bind(this, occurrence);
498
546
  continue;
499
547
  }
500
- const nodes = this.#invokeSlot(occurrence, callback, record, start);
501
- if (nodes) this.#replaceRange(occurrence, start, nodes);
502
- this.#slotNodes.set(occurrence, nodes);
503
- this.#bindRegions(occurrence);
548
+ this.#invokeSlot(occurrence, callback, record, start);
549
+ R?.bind(this, occurrence);
504
550
  }
505
551
  }
506
- if (!root) {
507
- for (const occurrence of [...this.#mountedSlots]) {
508
- if (!found.has(occurrence)) this.#unmountSlot(occurrence);
552
+ return waiting;
553
+ }
554
+ get el() {
555
+ return this.#element;
556
+ }
557
+ get defers() {
558
+ return this.#defers;
559
+ }
560
+ get deferred() {
561
+ return this.#deferred;
562
+ }
563
+ mountEnclosing(target) {
564
+ if (!this.#deferred) return false;
565
+ const root = this.#element;
566
+ let outer;
567
+ for (let node = target; node && node !== root; node = node.parentNode) {
568
+ let depth = 0;
569
+ for (let s = node.previousSibling; s; s = s.previousSibling) {
570
+ if (s.nodeType !== COMMENT_NODE || !s.data.startsWith("slot:")) continue;
571
+ if (SLOT_END.test(s.data)) depth++;else if (depth) depth--;else outer = s;
509
572
  }
510
573
  }
574
+ const id = outer && slotStartId(outer);
575
+ if (!id || this.#mountedSlots.has(id)) return false;
576
+ return this.#mountOne(id, outer);
577
+ }
578
+ #mountOne(id, start) {
579
+ const mount = () => {
580
+ this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;
581
+ };
582
+ mount();
583
+ if (!this.#mountedSlots.has(id)) return false;
584
+ this.#deferMounted.set(id, start);
585
+ return true;
586
+ }
587
+ mountDeferred(deadline) {
588
+ if (!this.#deferred) return true;
589
+ let found = this.#deferFound;
590
+ if (!found) {
591
+ found = this.#deferFound = new Map();
592
+ this.#collectSlots(found);
593
+ }
594
+ for (const [id, start] of found) {
595
+ found.delete(id);
596
+ if (this.#mountedSlots.has(id)) this.#deferWaiting = this.#mountFound(new Map([[id, start]])) || this.#deferWaiting;else this.#mountOne(id, start);
597
+ if (deadline !== undefined && found.size && performance.now() > deadline) return false;
598
+ }
599
+ this.#deferred = false;
600
+ this.#deferFound = undefined;
601
+ this.#deferMounted.clear();
602
+ if (this.#deferWaiting && !this.#hold) this.#hold = this.#options.hold?.();
603
+ return true;
604
+ }
605
+ mountOccurrence(id) {
606
+ if (!this.#deferred) return false;
607
+ if (this.#mountedSlots.has(id)) return true;
608
+ let found = this.#deferFound;
609
+ if (!found) {
610
+ found = this.#deferFound = new Map();
611
+ this.#collectSlots(found);
612
+ }
613
+ const start = found.get(id);
614
+ if (!start) return false;
615
+ found.delete(id);
616
+ this.#mountOne(id, start);
617
+ return true;
618
+ }
619
+ releaseDeferHold() {
620
+ const release = this.#deferHold;
621
+ this.#deferHold = undefined;
622
+ release && release();
623
+ }
624
+ #releaseHold() {
625
+ const release = this.#hold;
626
+ this.#hold = undefined;
627
+ release && release();
511
628
  }
512
629
  #invokeSlot(occurrence, callback, record, start, adopted) {
513
630
  this.#slotUpdaters.delete(occurrence);
@@ -528,31 +645,19 @@ class FrameImpl {
528
645
  end
529
646
  } : undefined
530
647
  };
531
- const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record.args) : {};
532
- const content = this.#scoped(() => callback(props, ctx));
648
+ const props = record && record.kind === "slot" ? this.#resolveArgs(occurrence, record, adopted, start) : {};
649
+ this.#scoped(() => callback(props, ctx));
533
650
  this.#slotArgs.set(occurrence, record);
534
651
  if (cleanups.length) this.#slotCleanups.set(occurrence, cleanups);
535
- if (content == null) return null;
536
- return Array.isArray(content) ? content : [content];
537
- }
538
- #replaceRange(key, start, nodes) {
539
- const parent = start.parentNode;
540
- const end = eachInRange(start, key, n => parent.removeChild(n));
541
- for (const node of nodes) parent.insertBefore(node, end);
542
652
  }
543
653
  #unmountSlot(key) {
544
654
  this.#mountedSlots.delete(key);
545
- this.#slotNodes.delete(key);
546
655
  this.#slotArgs.delete(key);
547
656
  this.#slotUpdaters.delete(key);
548
- this.#slotResolvedRefs.delete(key);
657
+ this.#heldRecords.delete(key);
549
658
  this.#removeSlotRecord(key);
550
659
  this.#runSlotCleanups(key);
551
- const regions = this.#slotRegions.get(key);
552
- if (regions) {
553
- disposeRegions(regions);
554
- this.#slotRegions.delete(key);
555
- }
660
+ tierLoads.regions?.r?.unmount(this, key);
556
661
  }
557
662
  #runSlotCleanups(key) {
558
663
  const cleanups = this.#slotCleanups.get(key);
@@ -560,129 +665,33 @@ class FrameImpl {
560
665
  this.#slotCleanups.delete(key);
561
666
  for (const fn of cleanups) fn();
562
667
  }
563
- #refsUnresolved(args) {
564
- const {
565
- host,
566
- id
567
- } = this.#options;
568
- if (host) for (const key in args) {
569
- if (isDataRef(args[key]) && host.resolve(args[key], id) === undefined) return true;
570
- }
571
- return false;
572
- }
573
- #regionsFor(slotKey) {
574
- let regions = this.#slotRegions.get(slotKey);
575
- if (!regions) this.#slotRegions.set(slotKey, regions = new Map());
576
- return regions;
668
+ get options() {
669
+ return this.#options;
577
670
  }
578
- #resolveArgs(slotKey, args) {
579
- const host = this.#options.host;
580
- const regions = this.#regionsFor(slotKey);
671
+ #resolveArgs(slotKey, record, claiming, start) {
672
+ const {
673
+ args,
674
+ regions,
675
+ decoded
676
+ } = record;
677
+ const revive = this.#options.host && this.#options.host.revive;
581
678
  const props = {};
582
679
  for (const key in args) {
680
+ if (regions && key in regions) continue;
583
681
  const value = args[key];
584
- if (isDataRef(value)) {
585
- const resolved = host ? host.resolve(value, this.#options.id) : undefined;
586
- let cache = this.#slotResolvedRefs.get(slotKey);
587
- if (!cache) this.#slotResolvedRefs.set(slotKey, cache = {});
588
- cache[key] = resolved;
589
- props[key] = resolved;
590
- } else if (isFrameRef(value)) {
591
- let entry = regions.get(key);
592
- if (!entry) {
593
- const element = makeFrameElement(value.$frame);
594
- entry = {
595
- childId: value.$frame,
596
- element,
597
- frame: undefined
598
- };
599
- regions.set(key, entry);
600
- } else if (entry.childId !== value.$frame) {
601
- renameRegion(entry, value.$frame);
602
- }
603
- props[key] = entry.element;
604
- } else {
605
- props[key] = host && host.revive ? host.revive(value) : value;
606
- }
682
+ props[key] = revive && !(decoded && key in decoded) ? revive(value, claiming) : value;
607
683
  }
684
+ if (regions) tierLoads.regions.r.resolve(this, slotKey, regions, props, claiming && start);
608
685
  return props;
609
686
  }
610
- #discoverRegions(slotKey, start) {
611
- if (!start) return;
612
- const regions = this.#regionsFor(slotKey);
613
- eachInRange(start, slotKey, n => collectRegionElements(n, regions));
614
- }
615
- #refArgsUnchanged(occurrence, record) {
616
- const old = this.#slotArgs.get(occurrence);
617
- if (!record || record.kind !== "slot") return false;
618
- if (old && old.kind !== "slot") return false;
619
- const a = old && old.args || {};
620
- const b = record.args || {};
621
- const ka = Object.keys(a);
622
- const kb = Object.keys(b);
623
- if (kb.length !== ka.length) return false;
624
- const cache = this.#slotResolvedRefs.get(occurrence);
625
- for (const key of ka) {
626
- const va = a[key];
627
- const vb = b[key];
628
- if (va === vb) continue;
629
- if (isFrameRef(va) && isFrameRef(vb)) continue;
630
- if (isDataRef(va) && isDataRef(vb) && cache && key in cache) {
631
- const host = this.#options.host;
632
- const next = host ? host.resolve(vb, this.#options.id) : undefined;
633
- if (host && host.isContainer && (host.isContainer(next) || host.isContainer(cache[key]))) {
634
- if (next === cache[key]) continue;
635
- return false;
636
- }
637
- if (isAsyncLike(next) || isAsyncLike(cache[key])) return false;
638
- try {
639
- if (JSON.stringify(next) === JSON.stringify(cache[key])) continue;
640
- } catch (e) {
641
- return false;
642
- }
643
- }
644
- return false;
645
- }
646
- return true;
647
- }
648
- #reconcileRegions(occurrence, record) {
649
- const args = record && record.args;
650
- if (!args) return;
651
- const regions = this.#slotRegions.get(occurrence);
652
- if (!regions) return;
653
- for (const key in args) {
654
- const value = args[key];
655
- if (!isFrameRef(value)) continue;
656
- const entry = regions.get(key);
657
- if (entry && entry.childId !== value.$frame) renameRegion(entry, value.$frame);
658
- }
687
+ #collectSlots(found, root) {
688
+ collectSlots(root || this.#element, found);
659
689
  }
660
- #bindRegions(slotKey) {
661
- const regions = this.#slotRegions.get(slotKey);
662
- if (!regions) return;
663
- for (const entry of regions.values()) {
664
- if (!entry.frame) {
665
- entry.frame = new FrameImpl(entry.element, null, null, {
666
- id: entry.childId,
667
- host: this.#options.host,
668
- adopt: entry.adopt,
669
- claimScope: this.#options.claimScope ?? this.#options.id,
670
- ownerScope: this.#options.ownerScope,
671
- resolveSlot: prop => this.#resolveSlot(prop),
672
- resolveSlotRecord: occurrence => this.#resolveSlotRecord(occurrence),
673
- removeSlotRecord: occurrence => this.#removeSlotRecord(occurrence)
674
- });
675
- }
676
- }
677
- }
678
- #collectSlots(found) {
679
- collectSlots(this.#firstContent(), this.#end, found);
680
- }
681
- #findPlaceholder(name) {
682
- return findPlaceholder(this.#firstContent(), this.#end, placeholderId(name));
690
+ #findPlaceholder(name, root) {
691
+ return findPlaceholder((root || this.#element).firstChild, null, placeholderId(name));
683
692
  }
684
693
  contentHTML() {
685
- if (this.#disposed || !this.#element || !this.#hasContent) return null;
694
+ if (this.#disposed || !this.#hasContent) return null;
686
695
  return this.#element.innerHTML;
687
696
  }
688
697
  rebind(id) {
@@ -700,12 +709,27 @@ class FrameImpl {
700
709
  this.#element.setAttribute(FRAME_ID_ATTR, id);
701
710
  }
702
711
  this.#version = undefined;
703
- this.#appliedRootValue = undefined;
704
- this.#resetStreamState(true);
712
+ this.#resetStreamState();
705
713
  if (host) host.register(id, this);
706
714
  }
707
- rebase() {
708
- this.#version = undefined;
715
+ get #live() {
716
+ return this.#liveMount ??= {
717
+ e: this.#element,
718
+ t: this.#liveTargets,
719
+ c: this.#claimTree,
720
+ k: found => this.#collectSlots(found),
721
+ s: () => this.#shows,
722
+ x: (key, record) => (this.#appliedHoles.set(key, record), tierLoads.wire.r.cancel(this.#options.host, this.#options.id)),
723
+ w: false
724
+ };
725
+ }
726
+ #recordHave(key, record) {
727
+ this.#shows = key ? Object.assign(this.#shows, {
728
+ [key]: record.digest
729
+ }, record.holes) : {
730
+ ...record.holes
731
+ };
732
+ tierLoads.wire?.r?.have(this, key, record);
709
733
  }
710
734
  dispose() {
711
735
  if (this.#disposed) return;
@@ -715,119 +739,95 @@ class FrameImpl {
715
739
  } = this.#options;
716
740
  if (host && id !== undefined) host.unregister(id, this);
717
741
  this.#disposed = true;
718
- if (this.#recordRefresh) {
719
- clearTimeout(this.#recordRefresh);
720
- this.#recordRefresh = null;
721
- }
742
+ liveFrames.delete(this);
743
+ this.#releaseHold();
744
+ this.releaseDeferHold();
722
745
  for (const key of [...this.#slotCleanups.keys()]) this.#runSlotCleanups(key);
723
746
  for (const key of this.#mountedSlots) this.#removeSlotRecord(key);
724
- for (const regions of this.#slotRegions.values()) disposeRegions(regions);
725
- this.#slotRegions.clear();
747
+ tierLoads.regions?.r?.unmount(this);
726
748
  this.#mountedSlots.clear();
727
749
  }
728
- #applyRoot(html) {
750
+ #applyRoot(html, wire) {
751
+ this.#found = undefined;
752
+ this.#liveTargets.clear();
753
+ this.#shows = {};
729
754
  const fragment = parseFragment(html);
730
- const parent = this.#parent();
755
+ const parent = this.#element;
731
756
  if (!this.#hasContent) {
732
- this.#clearContent();
757
+ parent.textContent = "";
733
758
  this.#claimTree(fragment);
734
- parent.insertBefore(fragment, this.#end);
759
+ parent.appendChild(fragment);
735
760
  this.#hasContent = true;
736
761
  } else {
737
762
  const claim = this.#claimTree;
738
763
  const ranges = new Map();
739
764
  this.#collectSlots(ranges);
740
- const grafts = [];
741
- reconcileChildren(parent, fragment, this.#start, this.#end, claim, ranges, grafts);
742
- if (ranges.size) for (const root of grafts) flushGrafts(root, ranges);
765
+ wire.morph(parent, fragment, claim, ranges);
743
766
  }
744
767
  }
745
- #applyHole(marker, html) {
746
- if (!this.#hasContent) return false;
747
- const open = findLiveTarget(this.#firstContent(), this.#end, n => n.nodeType === COMMENT_NODE && n.data === marker);
748
- if (!open) return false;
749
- const close = rangeClose(open, "lh:/" + marker.slice(3));
750
- if (!close) {
751
- return false;
752
- }
753
- reconcileChildren(open.parentNode, parseFragment(html), open, close, this.#claimTree);
754
- return true;
768
+ #claimContent() {
769
+ for (let n = this.#element.firstChild; n; n = n.nextSibling) this.#claimTree(n, false, this);
755
770
  }
756
- #applyAttrs(addr, text, removed) {
757
- if (!this.#hasContent) return false;
758
- const el = findLiveTarget(this.#firstContent(), this.#end, n => n.nodeType === ELEMENT_NODE && n.getAttribute("data-lha") === addr);
759
- if (!el) return false;
760
- const parsed = parseFragment(`<i${text}></i>`).firstChild;
761
- if (parsed) {
762
- for (let i = 0; i < parsed.attributes.length; i++) {
763
- const {
764
- name,
765
- value
766
- } = parsed.attributes[i];
767
- if (el.getAttribute(name) !== value) el.setAttribute(name, value);
771
+ #revealSegments(root) {
772
+ const version = this.#version;
773
+ let revealed = false;
774
+ for (const key of this.#content) {
775
+ const record = this.#store[key];
776
+ const name = segmentName(key);
777
+ if (name === null || !record || this.#appliedHoles.get(key) === record) continue;
778
+ if (this.#segmentReady(name, root)) {
779
+ this.#appliedHoles.set(key, record);
780
+ this.#revealSegment(name, root);
781
+ this.#applied(version, "reveal");
782
+ revealed = true;
768
783
  }
769
784
  }
770
- if (removed) for (const name of removed) el.removeAttribute(name);
771
- return true;
772
- }
773
- #clearContent() {
774
- removeUntil(this.#parent(), this.#firstContent(), this.#end);
775
- }
776
- #claimContent() {
777
- let n = this.#firstContent();
778
- while (n && n !== this.#end) {
779
- this.#claimTree(n);
780
- n = n.nextSibling;
785
+ for (const key of this.#content) {
786
+ const m = /^seg:([^:]+):fallback$/.exec(key);
787
+ if (!m || this.#appliedHoles.has(key) || this.#appliedHoles.has(`seg:${m[1]}`)) continue;
788
+ if (this.#showFallback(m[1], root)) {
789
+ this.#appliedHoles.set(key, this.#store[key]);
790
+ this.#applied(version, "reveal");
791
+ }
781
792
  }
793
+ return revealed;
782
794
  }
783
- #segmentReady(name) {
795
+ #segmentReady(name, root) {
784
796
  const content = this.#store[`seg:${name}`];
785
797
  if (!content || content.kind !== "html") return false;
786
798
  if (!this.#store[`seg:${name}:reveal`]) return false;
787
799
  const assets = this.#store[`seg:${name}:assets`];
788
- if (assets && assets.styles) {
789
- let ready = true;
790
- for (const entry of assets.styles) ready = ensureStylesheet(entry, this.#styleFlush) && ready;
791
- if (!ready) return false;
792
- }
793
- if (!this.#findPlaceholder(name)) return false;
794
- return true;
800
+ if (assets && (assets.styles || assets.inlineStyles) && !tierReady("assets")?.gate(assets.styles || [], this)) return false;
801
+ return !!this.#findPlaceholder(name, root);
795
802
  }
796
- #revealSegment(name) {
797
- const tpl = this.#findPlaceholder(name);
803
+ #revealSegment(name, root) {
804
+ const tpl = this.#findPlaceholder(name, root);
798
805
  if (!tpl) return;
799
- const assets = this.#store[`seg:${name}:assets`];
800
- if (assets && assets.inlineStyles) applyInlineStyles(assets.inlineStyles);
806
+ this.#found = undefined;
801
807
  const content = this.#store[`seg:${name}`];
802
808
  const closing = rangeClose(tpl, placeholderId(name));
803
- const parent = tpl.parentNode;
804
- removeUntil(parent, tpl.nextSibling, closing);
805
- if (this.#options.reveal) {
806
- const fallbackFrag = tpl.content.cloneNode(true);
807
- this.#claimTree(fallbackFrag);
808
- this.#options.reveal({
809
- before: closing,
810
- fallback: [...fallbackFrag.childNodes],
811
- content: () => {
812
- const materialized = this.#materialize(content);
813
- this.#syncSlots(materialized);
814
- this.#claimTree(materialized);
815
- return materialized;
816
- }
817
- });
818
- tpl.remove();
819
- this.#revealed.add(name);
809
+ if (!closing) {
820
810
  return;
821
811
  }
822
- const materialized = this.#materialize(content);
823
- this.#claimTree(materialized);
824
- parent.insertBefore(materialized, closing);
812
+ removeUntil(tpl.parentNode, tpl.nextSibling, closing);
813
+ const fallbackFrag = tpl.content.cloneNode(true);
814
+ this.#claimTree(fallbackFrag);
815
+ (this.#options.reveal || revealAtOnce)({
816
+ before: closing,
817
+ fallback: [...fallbackFrag.childNodes],
818
+ content: () => {
819
+ const materialized = this.#materialize(content);
820
+ this.#syncSlots(materialized);
821
+ this.#claimTree(materialized);
822
+ this.#revealSegments(materialized);
823
+ return materialized;
824
+ }
825
+ });
825
826
  tpl.remove();
826
- closing && closing.remove();
827
- this.#revealed.add(name);
827
+ this.#recordHave(name, content);
828
828
  }
829
- #showFallback(name) {
830
- const tpl = this.#findPlaceholder(name);
829
+ #showFallback(name, root) {
830
+ const tpl = this.#findPlaceholder(name, root);
831
831
  if (!tpl) return false;
832
832
  const closing = rangeClose(tpl, placeholderId(name));
833
833
  if (!closing) return false;
@@ -841,13 +841,13 @@ class FrameImpl {
841
841
  }
842
842
  }
843
843
  function createFrame(boundary, options) {
844
- return new FrameImpl(boundary, null, null, options);
844
+ return new FrameImpl(boundary, options);
845
845
  }
846
- const FRAME_TAG = "dx-frame";
846
+ const FRAME_TAG = "solid-frame";
847
847
  const FRAME_ID_ATTR = "data-fid";
848
848
  function createFrameElement(options) {
849
849
  const el = makeFrameElement(options.id);
850
- const frame = new FrameImpl(el, null, null, options);
850
+ const frame = new FrameImpl(el, options);
851
851
  return {
852
852
  element: el,
853
853
  frame,
@@ -863,30 +863,20 @@ function makeFrameElement(id) {
863
863
  if (id !== undefined) el.setAttribute(FRAME_ID_ATTR, id);
864
864
  return el;
865
865
  }
866
- function isFrameElement(node) {
867
- return node.nodeType === ELEMENT_NODE && node.hasAttribute(FRAME_ID_ATTR);
868
- }
869
866
  function segmentName(key) {
870
867
  const m = /^seg:([^:]+)$/.exec(key);
871
868
  return m ? m[1] : null;
872
869
  }
873
- function isAsyncLike(v) {
874
- return !!v && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
875
- }
876
870
  function propOf(occurrence) {
877
871
  const hash = occurrence.indexOf("#");
878
872
  return hash === -1 ? occurrence : occurrence.slice(0, hash);
879
873
  }
880
- function isDataRef(value) {
881
- return !!value && typeof value.$ref === "string";
882
- }
883
- function isFrameRef(value) {
884
- return !!value && typeof value.$frame === "string";
874
+ function isCalled(occurrence) {
875
+ return occurrence.indexOf("#") !== -1;
885
876
  }
886
- function disposeRegions(regions) {
887
- for (const {
888
- frame
889
- } of regions.values()) frame?.dispose();
877
+ function revealAtOnce(seam) {
878
+ seam.before.parentNode.insertBefore(seam.content(), seam.before);
879
+ seam.before.remove();
890
880
  }
891
881
  function removeUntil(parent, n, stop) {
892
882
  while (n && n !== stop) {
@@ -900,56 +890,6 @@ function parseFragment(html) {
900
890
  template.innerHTML = html;
901
891
  return template.content;
902
892
  }
903
- function findHeadElement(selector, attr, value) {
904
- for (const node of document.head.querySelectorAll(selector)) {
905
- if (node.getAttribute(attr) === value) return node;
906
- }
907
- return null;
908
- }
909
- function ensureStylesheet(entry, onSettle) {
910
- const href = typeof entry === "string" ? entry : entry.href;
911
- let link = findHeadElement('link[rel="stylesheet"]', "href", href);
912
- if (!link) {
913
- link = document.createElement("link");
914
- link.rel = "stylesheet";
915
- if (typeof entry !== "string" && entry.attrs) {
916
- for (const name in entry.attrs) link.setAttribute(name, entry.attrs[name]);
917
- }
918
- link.href = href;
919
- const waiters = new Set();
920
- link._$frWaiters = waiters;
921
- const settle = () => {
922
- link._$frWaiters = null;
923
- for (const fn of waiters) fn();
924
- };
925
- link.addEventListener("load", settle);
926
- link.addEventListener("error", settle);
927
- document.head.appendChild(link);
928
- }
929
- const waiters = link._$frWaiters;
930
- if (waiters == null) return true;
931
- waiters.add(onSettle);
932
- return false;
933
- }
934
- function ensureModulePreload(href) {
935
- if (findHeadElement('link[rel="modulepreload"]', "href", href)) return;
936
- const link = document.createElement("link");
937
- link.rel = "modulepreload";
938
- link.href = href;
939
- document.head.appendChild(link);
940
- }
941
- function applyInlineStyles(inlineStyles) {
942
- for (const entry of inlineStyles) {
943
- if (findHeadElement("style[data-asset]", "data-asset", entry.id)) continue;
944
- const el = document.createElement("style");
945
- el.setAttribute("data-asset", entry.id);
946
- if (entry.attrs) {
947
- for (const name in entry.attrs) el.setAttribute(name, entry.attrs[name]);
948
- }
949
- el.textContent = entry.content || "";
950
- document.head.appendChild(el);
951
- }
952
- }
953
893
  function isPlaceholderStart(node, id) {
954
894
  return node.tagName === "TEMPLATE" && node.id === id;
955
895
  }
@@ -961,20 +901,6 @@ function rangeClose(start, id) {
961
901
  }
962
902
  return null;
963
903
  }
964
- function findLiveTarget(n, end, test) {
965
- while (n && n !== end) {
966
- if (n.nodeType === ELEMENT_NODE) {
967
- const fid = isFrameElement(n) ? n.getAttribute(FRAME_ID_ATTR) : null;
968
- if (fid === null || fid.includes(".")) {
969
- if (test(n)) return n;
970
- const found = findLiveTarget(n.firstChild, null, test);
971
- if (found) return found;
972
- }
973
- } else if (test(n)) return n;
974
- n = n.nextSibling;
975
- }
976
- return null;
977
- }
978
904
  function findPlaceholder(n, end, id) {
979
905
  while (n && n !== end) {
980
906
  if (isPlaceholderStart(n, id)) return n;
@@ -986,40 +912,26 @@ function findPlaceholder(n, end, id) {
986
912
  }
987
913
  return null;
988
914
  }
989
- function collectSlots(n, end, out) {
990
- while (n && n !== end) {
915
+ function collectSlots(root, out) {
916
+ const w = root.ownerDocument.createTreeWalker(root, 0x80);
917
+ let n, p;
918
+ while (n = w.nextNode()) {
919
+ if (!n.data.startsWith("slot:")) continue;
991
920
  const id = slotStartId(n);
992
- if (id !== null) {
993
- if (!out.has(id)) out.set(id, n);
994
- n = afterRange(n, id);
921
+ if (!id) continue;
922
+ for (p = n.parentNode; p !== root; p = p.parentNode) if (p.hasAttribute(FRAME_ID_ATTR)) break;
923
+ if (p !== root) continue;
924
+ if (!out.has(id)) out.set(id, n);
925
+ const end = findMarker(n, slotEnd(id));
926
+ if (end) {
927
+ w.currentNode = end;
995
928
  continue;
996
929
  }
997
- if (n.nodeType === ELEMENT_NODE && !isFrameElement(n)) collectSlots(n.firstChild, null, out);
998
- n = n.nextSibling;
999
- }
1000
- }
1001
- function collectRegionElements(node, regions) {
1002
- if (node.nodeType !== ELEMENT_NODE) return;
1003
- if (isFrameElement(node)) {
1004
- const childId = node.getAttribute(FRAME_ID_ATTR);
1005
- if (childId && childId.includes(".")) {
1006
- const argKey = childId.slice(childId.lastIndexOf(".") + 1);
1007
- if (!regions.has(argKey)) {
1008
- regions.set(argKey, {
1009
- childId,
1010
- element: node,
1011
- frame: undefined,
1012
- adopt: true
1013
- });
1014
- }
1015
- }
1016
- return;
930
+ p = n.parentNode;
931
+ if (p === root) return;
932
+ while (p.lastChild) p = p.lastChild;
933
+ w.currentNode = p;
1017
934
  }
1018
- for (let c = node.firstChild; c; c = c.nextSibling) collectRegionElements(c, regions);
1019
- }
1020
- function renameRegion(entry, childId) {
1021
- entry.childId = childId;
1022
- if (entry.frame) entry.frame.rebind(childId);else entry.element.setAttribute(FRAME_ID_ATTR, childId);
1023
935
  }
1024
936
  function eachInRange(start, key, cb) {
1025
937
  const end = slotEnd(key);
@@ -1031,277 +943,97 @@ function eachInRange(start, key, cb) {
1031
943
  }
1032
944
  return n;
1033
945
  }
1034
- function clearStreamRecords(records, root) {
1035
- for (const key in records) {
1036
- if (/^(seg|hole|attr):/.test(key) || key === ":error" || root && key === "") {
1037
- delete records[key];
1038
- }
1039
- }
1040
- }
1041
- function argsEquivalent(a, b) {
1042
- if (a === b) return true;
1043
- if (!a || !b) return false;
1044
- const ka = Object.keys(a);
1045
- const kb = Object.keys(b);
1046
- if (ka.length !== kb.length) return false;
1047
- for (const key of ka) {
1048
- const va = a[key];
1049
- const vb = b[key];
1050
- if (va === vb) continue;
1051
- if (isFrameRef(va) && va.$frame === vb?.$frame) continue;
1052
- return false;
1053
- }
1054
- return true;
1055
- }
1056
946
  function slotStartId(node) {
1057
947
  if (node.nodeType !== COMMENT_NODE) return null;
1058
948
  const m = SLOT_START.exec(node.data);
1059
949
  return m ? m[1] : null;
1060
950
  }
1061
- function isSlotMarker(node) {
1062
- if (node.nodeType !== COMMENT_NODE) return false;
1063
- const data = node.data;
1064
- return SLOT_START.test(data) || SLOT_END.test(data);
1065
- }
1066
- function compatible(a, b) {
1067
- if (a.nodeType !== b.nodeType) return false;
1068
- if (a.nodeType === ELEMENT_NODE) return a.nodeName === b.nodeName && a.getAttribute("_key") === b.getAttribute("_key");
1069
- return a.nodeType === TEXT_NODE || a.nodeType === COMMENT_NODE;
1070
- }
1071
- function preservesOpen(el) {
1072
- const t = el.tagName;
1073
- return t === "DETAILS" || t === "DIALOG";
1074
- }
1075
- function morphAttributes(oldEl, newEl, claim) {
1076
- let reclaim = false;
1077
- let changed = false;
1078
- const keepOpen = preservesOpen(oldEl);
1079
- const oldAttrs = oldEl.attributes;
1080
- for (let i = oldAttrs.length - 1; i >= 0; i--) {
1081
- const name = oldAttrs[i].name;
1082
- if (keepOpen && name === "open") continue;
1083
- if (!newEl.hasAttribute(name)) {
1084
- oldEl.removeAttribute(name);
1085
- changed = true;
1086
- reclaim ||= claimedAttr(name);
1087
- }
1088
- }
1089
- const newAttrs = newEl.attributes;
1090
- for (let i = 0; i < newAttrs.length; i++) {
1091
- const attr = newAttrs[i];
1092
- if (keepOpen && attr.name === "open") continue;
1093
- if (oldEl.getAttribute(attr.name) !== attr.value) {
1094
- oldEl.setAttribute(attr.name, attr.value);
1095
- changed = true;
1096
- reclaim ||= claimedAttr(attr.name);
1097
- }
1098
- }
1099
- if (claim && (reclaim || changed && oldEl.matches(CLAIMED_ELEMENTS))) claim(oldEl, true);
1100
- }
1101
- function morphNode(oldNode, newNode, claim, ranges, grafts) {
1102
- if (oldNode.nodeType === ELEMENT_NODE) {
1103
- if (oldNode.hasAttribute("data-preserve")) return;
1104
- morphAttributes(oldNode, newNode, claim);
1105
- reconcileChildren(oldNode, newNode, null, null, claim, ranges, grafts);
1106
- } else if (oldNode.data !== newNode.data) {
1107
- oldNode.data = newNode.data;
1108
- }
1109
- }
1110
- function afterRange(start, id) {
1111
- const end = slotEnd(id);
951
+ function findMarker(start, end) {
1112
952
  let n = start.nextSibling;
1113
953
  while (n) {
1114
- if (n.nodeType === COMMENT_NODE && n.data === end) return n.nextSibling;
954
+ if (n.nodeType === COMMENT_NODE && n.data === end) return n;
1115
955
  n = n.nextSibling;
1116
956
  }
1117
957
  return null;
1118
958
  }
1119
- function findRangeStart(from, id, bound) {
1120
- const target = `slot:${id}:start`;
1121
- let n = from;
1122
- while (n && n !== bound) {
1123
- if (n.nodeType === COMMENT_NODE && n.data === target) return n;
1124
- n = n.nextSibling;
1125
- }
1126
- return null;
1127
- }
1128
- function moveRangeBefore(parent, start, id, ref) {
1129
- const end = slotEnd(id);
1130
- let n = start;
1131
- while (n) {
1132
- const next = n.nextSibling;
1133
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1134
- parent.insertBefore(n, ref);
1135
- if (isEnd) break;
1136
- n = next;
1137
- }
1138
- }
1139
- function placeRange(parent, range, id, ref) {
1140
- if (range.nodeType === 11 ) {
1141
- parent.insertBefore(range, ref);
1142
- } else {
1143
- moveRangeBefore(parent, range, id, ref);
1144
- }
1145
- }
1146
- function adoptRange(parent, start, id, ref, claim) {
1147
- const end = slotEnd(id);
1148
- let n = start;
1149
- let after = null;
1150
- while (n) {
1151
- const next = n.nextSibling;
1152
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1153
- parent.insertBefore(n, ref);
1154
- if (claim) claim(n);
1155
- if (isEnd) {
1156
- after = next;
1157
- break;
1158
- }
1159
- n = next;
1160
- }
1161
- return after;
1162
- }
1163
- function reconcileChildren(parent, source, boundStart = null, boundEnd = null, claim = null, ranges = null, grafts = null) {
1164
- let oldChild = boundStart ? boundStart.nextSibling : parent.firstChild;
1165
- let newChild = source.firstChild;
1166
- while (newChild) {
1167
- const nextNew = newChild.nextSibling;
1168
- const pid = slotStartId(newChild);
1169
- const old = oldChild === boundEnd ? null : oldChild;
1170
- if (pid !== null) {
1171
- if (old && slotStartId(old) === pid) {
1172
- oldChild = afterRange(old, pid);
1173
- newChild = afterRange(newChild, pid);
1174
- } else {
1175
- const displaced = ranges && ranges.get(pid);
1176
- const existing = displaced || findRangeStart(old, pid, boundEnd);
1177
- if (existing) {
1178
- if (ranges) ranges.delete(pid);
1179
- placeRange(parent, existing, pid, old ?? boundEnd);
1180
- newChild = afterRange(newChild, pid);
1181
- } else {
1182
- newChild = adoptRange(parent, newChild, pid, old ?? boundEnd, claim);
1183
- }
1184
- }
1185
- continue;
1186
- }
1187
- if (!old) {
1188
- parent.insertBefore(newChild, boundEnd);
1189
- if (claim) claim(newChild);
1190
- if (grafts) grafts.push(newChild);
1191
- newChild = nextNew;
1192
- continue;
1193
- }
1194
- if (isSlotMarker(old)) {
1195
- parent.insertBefore(newChild, old);
1196
- if (claim) claim(newChild);
1197
- if (grafts) grafts.push(newChild);
1198
- newChild = nextNew;
1199
- continue;
1200
- }
1201
- if (compatible(old, newChild)) {
1202
- morphNode(old, newChild, claim, ranges, grafts);
1203
- oldChild = old.nextSibling;
1204
- newChild = nextNew;
1205
- continue;
1206
- }
1207
- if (newChild.nodeType === 1) {
1208
- let ahead = old.nextSibling;
1209
- while (ahead && ahead !== boundEnd && !compatible(ahead, newChild)) {
1210
- const aheadPid = slotStartId(ahead);
1211
- ahead = aheadPid !== null ? afterRange(ahead, aheadPid) : ahead.nextSibling;
1212
- }
1213
- if (ahead && ahead !== boundEnd) {
1214
- parent.insertBefore(ahead, old);
1215
- morphNode(ahead, newChild, claim, ranges, grafts);
1216
- newChild = nextNew;
1217
- continue;
1218
- }
1219
- }
1220
- parent.insertBefore(newChild, old);
1221
- if (claim) claim(newChild);
1222
- if (grafts) grafts.push(newChild);
1223
- newChild = nextNew;
1224
- }
1225
- while (oldChild && oldChild !== boundEnd) {
1226
- const next = oldChild.nextSibling;
1227
- const pid = ranges ? slotStartId(oldChild) : null;
1228
- if (pid !== null && ranges.get(pid) === oldChild) {
1229
- const frag = document.createDocumentFragment();
1230
- const after = stashRange(frag, oldChild, pid);
1231
- ranges.set(pid, frag);
1232
- oldChild = after;
1233
- continue;
1234
- }
1235
- parent.removeChild(oldChild);
1236
- oldChild = next;
1237
- }
1238
- }
1239
- function flushGrafts(node, ranges) {
1240
- if (node.nodeType !== ELEMENT_NODE || isFrameElement(node)) return;
1241
- let n = node.firstChild;
1242
- while (n) {
1243
- const id = slotStartId(n);
1244
- if (id !== null) {
1245
- const next = afterRange(n, id);
1246
- const displaced = ranges.get(id);
1247
- if (displaced) {
1248
- ranges.delete(id);
1249
- placeRange(node, displaced, id, n);
1250
- stashRange(document.createDocumentFragment(), n, id);
1251
- }
1252
- n = next;
1253
- continue;
1254
- }
1255
- flushGrafts(n, ranges);
1256
- n = n.nextSibling;
1257
- }
1258
- }
1259
- function stashRange(frag, start, id) {
1260
- const end = slotEnd(id);
1261
- let n = start;
1262
- while (n) {
1263
- const next = n.nextSibling;
1264
- const isEnd = n.nodeType === COMMENT_NODE && n.data === end;
1265
- frag.appendChild(n);
1266
- if (isEnd) return next;
1267
- n = next;
1268
- }
1269
- return null;
1270
- }
1271
959
 
1272
960
  const FRAME_STREAM_HEADER = "X-Frame-Stream";
961
+ const FRAME_TIERS_HEADER = "X-Frame-Tiers";
1273
962
  function isFrameStreamResponse(response) {
1274
963
  return response.headers.has(FRAME_STREAM_HEADER);
1275
964
  }
1276
- async function applyFrameResponse(response, host, options = {}) {
965
+ const applyFrameResponse = applyFrames;
966
+ const ends = msg => !!msg.r && (":complete" in msg.r || ":error" in msg.r);
967
+ const readsData = msg => {
968
+ 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;
969
+ return false;
970
+ };
971
+ function applyFrames(response, host, options = {}, observation) {
1277
972
  const rootId = response.headers.get(FRAME_STREAM_HEADER) ?? "";
973
+ response.headers.get(FRAME_TIERS_HEADER)?.split(",").forEach(prepareTier);
1278
974
  const as = options.as;
1279
975
  const version = options.version;
1280
976
  const perFrame = typeof version === "function" ? new Map() : null;
1281
- const reader = new ChunkReader(response.body);
1282
- let result = await reader.next();
1283
- while (!result.done) {
1284
- const chunk = JSON.parse(result.value);
1285
- if (chunk.type === "outcome") {
1286
- if (options.onOutcome) options.onOutcome(chunk.payload);
1287
- } else {
1288
- if (as !== undefined && chunk.id === rootId) chunk.id = as;
1289
- if (perFrame) {
1290
- let v = perFrame.get(chunk.id);
1291
- if (v === undefined) perFrame.set(chunk.id, v = version(chunk.id));
1292
- chunk.version = v;
1293
- } else if (version !== undefined) chunk.version = version;
1294
- if (chunk.type === "data" && host.prepareData) await host.prepareData();
1295
- host.apply(chunk);
977
+ const reader = options[LIVE_WIRE] || new ChunkReader(response.body);
978
+ const open = new Map();
979
+ const errorRecord = (id, error) => ({
980
+ id,
981
+ version: open.get(id),
982
+ r: {
983
+ ":error": {
984
+ message: String(error && error.message)
985
+ }
1296
986
  }
1297
- result = await reader.next();
1298
- }
1299
- return as !== undefined ? as : rootId;
987
+ });
988
+ const drain = async () => {
989
+ let result = await reader.next();
990
+ while (!result.done) {
991
+ const chunk = JSON.parse(result.value);
992
+ if (chunk.type === "outcome") {
993
+ if (options.onOutcome) options.onOutcome(chunk.payload);
994
+ } else {
995
+ chunk.id;
996
+ if (as !== undefined && chunk.id === rootId) chunk.id = as;
997
+ if (perFrame) {
998
+ let v = perFrame.get(chunk.id);
999
+ if (v === undefined) perFrame.set(chunk.id, v = version(chunk.id));
1000
+ chunk.version = v;
1001
+ } else if (version !== undefined) chunk.version = version;
1002
+ if (chunk.type === "start") open.set(chunk.id, chunk.version);else if (ends(chunk)) open.delete(chunk.id);
1003
+ const needs = chunk.tiers?.map(prepareTier) || [];
1004
+ if (chunk.type === "data" || readsData(chunk)) await Promise.all([host.prepareData?.(), ...needs]);
1005
+ host.apply(chunk);
1006
+ }
1007
+ result = await reader.next();
1008
+ }
1009
+ };
1010
+ const end = error => {
1011
+ if (error === undefined) for (const id of open.keys()) host.apply(errorRecord(id, new Error("Frame stream ended before the frame completed.")));
1012
+ };
1013
+ return drain().then(() => {
1014
+ end(undefined);
1015
+ return as !== undefined ? as : rootId;
1016
+ }, error => {
1017
+ end(error);
1018
+ throw error;
1019
+ });
1020
+ }
1021
+ const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("solid.server-component");
1022
+ const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("solid.server-component-address");
1023
+ const COMPONENT_BINDING = /*#__PURE__*/Symbol.for("solid.component-binding");
1024
+ const CONTENT_TOKEN = "\u0000";
1025
+ function contentAddress(token) {
1026
+ return token.split(CONTENT_TOKEN)[0];
1300
1027
  }
1301
- const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("dom-expressions.server-component");
1302
- const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("dom-expressions.server-component-address");
1303
- const COMPONENT_BINDING = /*#__PURE__*/Symbol.for("dom-expressions.component-binding");
1028
+ const stagedContent = {
1029
+ preview() {},
1030
+ commit() {}
1031
+ };
1304
1032
  let resolveServerComponent;
1033
+ const calls = new Map();
1034
+ function callFor(address) {
1035
+ return calls.get(address);
1036
+ }
1305
1037
  function parseServerComponent(value, ctx) {
1306
1038
  return {
1307
1039
  id: ctx.parse(value[SERVER_COMPONENT]),
@@ -1309,7 +1041,7 @@ function parseServerComponent(value, ctx) {
1309
1041
  };
1310
1042
  }
1311
1043
  const ServerComponentPlugin = {
1312
- tag: "dom-expressions/server-component",
1044
+ tag: "solid/server-component",
1313
1045
  test(value) {
1314
1046
  return typeof value === "function" && SERVER_COMPONENT in value;
1315
1047
  },
@@ -1347,10 +1079,7 @@ function flightCodec(codec) {
1347
1079
  function createServerComponentHandler({
1348
1080
  host,
1349
1081
  component,
1350
- onStream,
1351
- intercept,
1352
- consumer = getFlightDataConsumer,
1353
- codec = getServerFunctionsCodec
1082
+ intercept
1354
1083
  }) {
1355
1084
  const byFn = new Map();
1356
1085
  const componentFor = fnId => {
@@ -1372,19 +1101,79 @@ function createServerComponentHandler({
1372
1101
  }
1373
1102
  return binding;
1374
1103
  };
1375
- resolveServerComponent = (id, address) => bindingFor(address, id);
1104
+ const staged = new Map();
1105
+ const latest = new Map();
1106
+ const stage = (address, base, version) => {
1107
+ if (!base) return undefined;
1108
+ let committed = false;
1109
+ const chunks = [];
1110
+ const token = address + CONTENT_TOKEN + version;
1111
+ const entry = {
1112
+ token,
1113
+ prepareData: host.prepareData,
1114
+ apply(chunk) {
1115
+ if (committed || chunk.type === "data") host.apply(chunk);else chunks.push(chunk);
1116
+ },
1117
+ preview() {
1118
+ if (host.preview) for (const chunk of chunks) host.preview(chunk);
1119
+ },
1120
+ commit() {
1121
+ committed = true;
1122
+ staged.delete(address);
1123
+ for (const chunk of chunks) host.apply(chunk);
1124
+ }
1125
+ };
1126
+ staged.set(address, entry);
1127
+ const comp = base[COMPONENT_BINDING].component;
1128
+ const binding = props => comp(props, () => token);
1129
+ binding[COMPONENT_BINDING] = {
1130
+ component: comp,
1131
+ address: token
1132
+ };
1133
+ latest.set(address, binding);
1134
+ return entry;
1135
+ };
1136
+ const settled = (address, binding) => latest.get(address) || binding;
1137
+ const showing = address => {
1138
+ const frame = host.get(address);
1139
+ return frame !== undefined && frame.error === undefined;
1140
+ };
1141
+ const named = (token, half) => {
1142
+ const entry = staged.get(contentAddress(token));
1143
+ if (entry && entry.token === token) entry[half]();
1144
+ };
1145
+ stagedContent.preview = token => named(token, "preview");
1146
+ stagedContent.commit = token => named(token, "commit");
1147
+ resolveServerComponent = (id, address) => settled(address, bindingFor(address, id));
1376
1148
  const versions = new Map();
1377
1149
  const bump = address => {
1378
1150
  const version = (versions.get(address) || 0) + 1;
1379
1151
  versions.set(address, version);
1152
+ staged.delete(address);
1153
+ tierLoads.wire?.r?.cancel(host, address);
1380
1154
  return version;
1381
1155
  };
1156
+ const begin = (address, version) => host.apply({
1157
+ type: "start",
1158
+ id: address,
1159
+ version
1160
+ });
1382
1161
  return {
1383
1162
  intercept: intercept && (info => {
1384
1163
  const hit = intercept(info);
1385
- if (hit === undefined) return undefined;
1386
- return bindingFor(frameAddress(info.id, info.args), info.id);
1164
+ if (hit === undefined) return void prepareMorph();
1165
+ const address = frameAddress(info.id, info.args);
1166
+ if (!info.meta?.live) calls.set(address, info);
1167
+ const binding = () => bindingFor(address, info.id);
1168
+ if (typeof hit.then === "function") return hit.then(landed => landed ? binding() : undefined);
1169
+ return binding();
1387
1170
  }),
1171
+ onLive() {
1172
+ prepareTier("wire");
1173
+ },
1174
+ resume(info) {
1175
+ return tierLoads.wire?.r?.resume(host, info, versions);
1176
+ },
1388
1177
  handle(response, ctx) {
1389
1178
  if (!isFrameStreamResponse(response)) return undefined;
1390
1179
  const address = frameAddress(ctx.id, ctx.args);
@@ -1392,30 +1181,29 @@ function createServerComponentHandler({
1392
1181
  if (response.headers.has(SINGLE_FLIGHT_HEADER)) {
1393
1182
  return applyFlightResponse(response, address, binding);
1394
1183
  }
1184
+ const wire = ctx[LIVE_WIRE];
1185
+ if (wire) return prepareTier("wire").then(() => tierLoads.wire.r.connect(response, wire, address, binding, host, bump, begin));
1186
+ calls.set(address, ctx);
1395
1187
  const version = bump(address);
1396
- if (onStream) onStream(address, version, response);
1397
- applyFrameResponse(response, host, {
1188
+ const entry = showing(address) ? stage(address, binding, version) : undefined;
1189
+ if (!entry) begin(address, version);
1190
+ const target = entry || host;
1191
+ const applied = applyFrameResponse(response, target, {
1398
1192
  as: address,
1399
- version
1400
- }).catch(err => host.apply({
1401
- type: "error",
1193
+ version: frameId => frameId === address ? version : bump(frameId)
1194
+ }).catch(err => target.apply({
1402
1195
  id: address,
1403
1196
  version,
1404
- error: {
1405
- message: String(err && err.message)
1197
+ r: {
1198
+ ":error": {
1199
+ message: String(err && err.message)
1200
+ }
1406
1201
  }
1407
1202
  }));
1408
- return binding;
1203
+ return entry ? applied.then(() => settled(address, binding)) : binding;
1409
1204
  },
1410
1205
  showing(address, functionId) {
1411
1206
  bindingFor(address, functionId);
1412
- const comp = componentFor(functionId);
1413
- if (comp && (typeof comp === "function" || typeof comp === "object") && !comp[COMPONENT_BINDING]) {
1414
- comp[COMPONENT_BINDING] = {
1415
- component: comp,
1416
- address
1417
- };
1418
- }
1419
1207
  }
1420
1208
  };
1421
1209
  async function applyFlightResponse(response, address, binding) {
@@ -1427,13 +1215,28 @@ function createServerComponentHandler({
1427
1215
  feed = controller;
1428
1216
  }
1429
1217
  });
1430
- const payload = deserializeStream(new Response(source), flightCodec(codec()));
1218
+ const payload = deserializeStream(new Response(source), flightCodec(getServerFunctionsCodec()));
1431
1219
  let carried = false;
1432
- await applyFrameResponse(response, host, {
1220
+ const regions = new Map();
1221
+ const regionOf = id => {
1222
+ for (const [root, entry] of regions) if (id === root || id.startsWith(root + ".")) return entry;
1223
+ };
1224
+ const target = {
1225
+ apply: chunk => {
1226
+ const entry = regionOf(chunk.id);
1227
+ if (entry) entry.apply(chunk);else host.apply(chunk);
1228
+ },
1229
+ prepareData: host.prepareData
1230
+ };
1231
+ await applyFrameResponse(response, target, {
1433
1232
  as,
1434
1233
  version: frameId => {
1435
1234
  const version = bump(frameId);
1436
- if (onStream) onStream(frameId, version, response);
1235
+ let entry = regionOf(frameId);
1236
+ if (!entry && showing(frameId)) {
1237
+ entry = stage(frameId, frameId === as ? binding : byAddress.get(frameId), version);
1238
+ if (entry) regions.set(frameId, entry);
1239
+ }
1437
1240
  return version;
1438
1241
  },
1439
1242
  onOutcome: text => {
@@ -1444,54 +1247,19 @@ function createServerComponentHandler({
1444
1247
  feed.close();
1445
1248
  if (!carried) throw new Error("Single-flight frame response carried no outcome");
1446
1249
  const envelope = await payload;
1447
- const deliver = consumer();
1448
- if (deliver) await deliver(envelope.data, {
1449
- response
1450
- });
1451
- if (response.headers.has(ERROR_HEADER) && !response.headers.has("Location") && !response.headers.has(REVALIDATE_HEADER)) {
1250
+ await deliverFlightData(response, envelope.data);
1251
+ if (response.headers.has(ERROR_HEADER) && !hasFlightMetadata(response)) {
1452
1252
  throw envelope.value;
1453
1253
  }
1454
- return rootId ? binding : envelope.value;
1455
- }
1456
- }
1457
-
1458
- const STATE = Symbol.for("dom-expressions.container-trace-state");
1459
- const state = globalThis[STATE] || (globalThis[STATE] = {
1460
- materialized: new WeakMap(),
1461
- materializedValues: new WeakSet()
1462
- });
1463
- function setContainerTraceMaterializer(fn) {
1464
- state.materializeTrace = fn;
1465
- }
1466
- function materialize(marker) {
1467
- let value = state.materialized.get(marker.$tr);
1468
- if (value === undefined) {
1469
- value = state.materializeTrace(marker);
1470
- state.materialized.set(marker.$tr, value);
1471
- if (value !== null && typeof value === "object") state.materializedValues.add(value);
1472
- }
1473
- return value;
1474
- }
1475
- function isMaterializedContainer(value) {
1476
- return value !== null && typeof value === "object" && state.materializedValues.has(value);
1477
- }
1478
- function isContainerTraceMarker(value) {
1479
- if (value == null || typeof value !== "object" || value.$tr == null) return false;
1480
- const tr = value.$tr;
1481
- return tr.__SEROVAL_STREAM__ === true || typeof tr[Symbol.asyncIterator] === "function";
1482
- }
1483
- function reviveContainerTraces(value) {
1484
- if (!state.materializeTrace || value == null || typeof value !== "object") return value;
1485
- if (isContainerTraceMarker(value)) return materialize(value);
1486
- if (Array.isArray(value)) {
1487
- for (let i = 0; i < value.length; i++) value[i] = reviveContainerTraces(value[i]);
1488
- } else if (Object.getPrototypeOf(value) === Object.prototype) {
1489
- for (const key of Object.keys(value)) value[key] = reviveContainerTraces(value[key]);
1254
+ return rootId ? settled(address, binding) : envelope.value;
1490
1255
  }
1491
- return value;
1492
1256
  }
1493
1257
 
1494
- setContainerTraceMaterializer(materializeContainerTrace);
1258
+ const TRACE_STATE = Symbol.for("solid.container-trace-state");
1259
+ tierLoaders.trace = () => import('@solidjs/web/frames/trace');
1260
+ tierLoaders.regions = () => import('@solidjs/web/frames/regions');
1261
+ tierLoaders.assets = () => import('@solidjs/web/frames/assets');
1262
+ tierLoaders.wire = () => import('@solidjs/web/frames/wire');
1495
1263
  function asyncArg(value) {
1496
1264
  return value;
1497
1265
  }
@@ -1504,117 +1272,140 @@ function loadCodec() {
1504
1272
  });
1505
1273
  }
1506
1274
  const tables = new Map();
1507
- function ensureTable(root) {
1508
- let table = tables.get(root);
1509
- if (!table && codec) tables.set(root, table = codec.createJSONDataTable());
1510
- return table;
1275
+ function tableFor(id, version, current) {
1276
+ let byVersion = tables.get(id);
1277
+ if (!byVersion) tables.set(id, byVersion = new Map());else for (const v of byVersion.keys()) if (v < current) byVersion.delete(v);
1278
+ let t = byVersion.get(version);
1279
+ if (!t && codec) byVersion.set(version, t = codec.createJSONDataTable());
1280
+ return t;
1281
+ }
1282
+ function followAddress(host, frame, binding) {
1283
+ createRenderEffect(() => {
1284
+ const token = binding();
1285
+ stagedContent.preview(token);
1286
+ return token;
1287
+ }, token => {
1288
+ stagedContent.commit(token);
1289
+ frame.rebind(contentAddress(token));
1290
+ });
1511
1291
  }
1512
- function tableFor(id) {
1513
- if (tables.has(id)) return ensureTable(id);
1514
- for (const root of tables.keys()) if (id.startsWith(root + ".")) return ensureTable(root);
1515
- return undefined;
1292
+ function landing(host, address, value, failed) {
1293
+ let frame, thrown;
1294
+ const errored = () => (frame = host.get(address))?.error !== undefined && (thrown === (thrown = frame.version) ? 1 : 2);
1295
+ errored();
1296
+ return createMemo(() => {
1297
+ failed();
1298
+ const state = errored();
1299
+ if (state > 1) throw frame.error;
1300
+ const wait = host.landing(address);
1301
+ if (!wait) return value;
1302
+ const landed = (state ? reask(address, wait) : wait).then(() => value);
1303
+ return landed;
1304
+ });
1305
+ }
1306
+ function reask(address, wait) {
1307
+ const call = callFor(address);
1308
+ return call ? call.retry().then(() => wait) : wait;
1516
1309
  }
1517
- function beginStream(frameId) {
1518
- tables.set(frameId, undefined);
1310
+ function failing() {
1311
+ const [failed, setFailed] = createSignal(0, {
1312
+ ownedWrite: true
1313
+ });
1314
+ return [failed, info => info.reason === "error" && setFailed(n => n + 1)];
1519
1315
  }
1520
1316
  function getFrameHost() {
1521
1317
  if (!sharedHost) {
1522
1318
  sharedHost = createFrameHost({
1523
1319
  prepareData: loadCodec,
1524
- applyData: c => tableFor(c.id)?.apply(c),
1525
- resolve: (ref, id) => tableFor(id)?.resolve(ref),
1526
- revive: reviveContainerTraces,
1527
- isContainer: isMaterializedContainer,
1528
- delegate: delegateEvents
1320
+ applyData: (c, current) => tableFor(c.id, c.version, current)?.apply(c),
1321
+ resolve: (ref, id, version, current) => tableFor(id, version, current)?.resolve(ref),
1322
+ closeData: (id, version, error) => tables.get(id)?.get(version)?.close(error)
1529
1323
  });
1530
1324
  }
1531
1325
  return sharedHost;
1532
1326
  }
1533
- function normalizeSlotContent(value) {
1534
- while (typeof value === "function") value = value();
1535
- if (Array.isArray(value)) {
1536
- const out = [];
1537
- for (const v of value) {
1538
- const n = normalizeSlotContent(v);
1539
- Array.isArray(n) ? out.push(...n) : out.push(n);
1327
+ function claimScope(el) {
1328
+ const registry = sharedConfig.registry;
1329
+ const buckets = new Map();
1330
+ const bucketOf = key => key.slice(0, key.lastIndexOf("-") + 1);
1331
+ const index = root => {
1332
+ if (registry) for (const n of root.querySelectorAll("[_hk]")) {
1333
+ const p = bucketOf(n.getAttribute("_hk"));
1334
+ const b = buckets.get(p);
1335
+ b ? b.push(n) : buckets.set(p, [n]);
1540
1336
  }
1541
- return out;
1542
- }
1543
- if (value == null || typeof value === "boolean") return document.createTextNode("");
1544
- return value instanceof Node ? value : document.createTextNode(String(value));
1545
- }
1546
- function gatherClaims(el, registry) {
1547
- if (el.hasAttribute("_hk")) registry.set(el.getAttribute("_hk"), el);
1548
- if (el.hasAttribute(FRAME_ID_ATTR)) return;
1549
- for (let c = el.firstElementChild; c; c = c.nextElementSibling) gatherClaims(c, registry);
1550
- }
1551
- function hasPendingFragment(existing) {
1552
- for (const n of existing) {
1553
- if (n.nodeType !== 1) continue;
1554
- const el = n;
1555
- if (el.tagName === "TEMPLATE" && el.id.startsWith("pl-")) return true;
1556
- if (el.querySelector?.('template[id^="pl-"]')) return true;
1557
- }
1558
- return false;
1337
+ };
1338
+ index(el);
1339
+ return {
1340
+ registry,
1341
+ gather(id) {
1342
+ for (const n of buckets.get(bucketOf(id)) || []) {
1343
+ const k = n.getAttribute("_hk");
1344
+ if (k.startsWith(id) && n.isConnected && !registry.has(k)) registry.set(k, n);
1345
+ }
1346
+ },
1347
+ index
1348
+ };
1559
1349
  }
1560
- function claimRender(prefix, existing, render) {
1350
+ function claimRender(prefix, owner, existing, render, scope, bound) {
1561
1351
  const sc = sharedConfig;
1562
- if (!sc.getNextContextId) return render();
1563
- const registry = new Map();
1564
- for (const n of existing) {
1565
- if (n.nodeType !== 1) continue;
1566
- gatherClaims(n, registry);
1567
- }
1568
- if (!registry.size && !hasPendingFragment(existing)) return render();
1569
- const prevRegistry = sc.registry;
1570
- const prevHydrating = sc.hydrating;
1571
- const prevClaimRoots = sc.claimRoots;
1572
- if (prevRegistry) for (const key of registry.keys()) prevRegistry.delete(key);
1573
- sc.registry = registry;
1574
- sc.hydrating = true;
1352
+ if (!sc.hydrateWindow || !sc.registry) return runWithOwner(owner, render);
1353
+ const prevRoots = sc.claimRoots;
1575
1354
  sc.claimRoots = existing;
1576
1355
  try {
1577
- return runWithOwner(createOwner({
1578
- id: prefix
1579
- }), render);
1356
+ return runWithOwner(owner, () => sc.hydrateWindow(bound ? undefined : prefix, render, scope));
1580
1357
  } finally {
1581
- sc.registry = prevRegistry;
1582
- sc.hydrating = prevHydrating;
1583
- sc.claimRoots = prevClaimRoots;
1358
+ sc.claimRoots = prevRoots;
1584
1359
  }
1585
1360
  }
1586
1361
  function liveSlotProps(initial, ctx) {
1587
- const [args, setArgs] = createSignal(initial);
1362
+ const [args, setArgs] = createSignal(initial, {
1363
+ ownedWrite: true
1364
+ });
1588
1365
  ctx.onUpdate(next => setArgs(() => next));
1589
1366
  return slotArgsProxy(args);
1590
1367
  }
1591
- function isAsyncValue(v) {
1592
- return v !== null && typeof v === "object" && (typeof v.then === "function" || typeof v[Symbol.asyncIterator] === "function");
1368
+ function sameArg(a, b) {
1369
+ if (a === b) return true;
1370
+ if (!a || !b || typeof a !== "object" || typeof b !== "object") return false;
1371
+ if (a instanceof Boxed || b instanceof Boxed) return a instanceof Boxed && b instanceof Boxed && a.c === b.c;
1372
+ if (isAsyncValue(a) || isAsyncValue(b) || a instanceof Node || b instanceof Node) return false;
1373
+ try {
1374
+ return JSON.stringify(a) === JSON.stringify(b);
1375
+ } catch {
1376
+ return false;
1377
+ }
1378
+ }
1379
+ class Boxed {
1380
+ constructor(c) {
1381
+ this.c = c;
1382
+ }
1593
1383
  }
1594
1384
  function slotArgsProxy(args) {
1595
1385
  const owner = getOwner();
1596
- const asyncReads = new Map();
1386
+ const reads = new Map();
1597
1387
  return new Proxy({}, {
1598
1388
  get: (_, key) => {
1599
- const v = args()[key];
1600
- if (isMaterializedContainer(v)) return v;
1601
- if (!isAsyncValue(v)) return v;
1602
- let read = asyncReads.get(key);
1389
+ let read = reads.get(key);
1603
1390
  if (!read) {
1604
1391
  const make = () => createMemo(() => {
1605
1392
  const raw = args()[key];
1393
+ if (globalThis[TRACE_STATE]?.materializedValues.has(raw)) return new Boxed(raw);
1606
1394
  if (raw != null && typeof raw.then === "function") {
1607
1395
  if (raw.s === 1) return raw.v;
1608
1396
  if (raw.s === 2) throw raw.v;
1609
1397
  }
1610
1398
  return raw;
1611
1399
  }, {
1612
- transparent: true
1400
+ transparent: true,
1401
+ equals: sameArg
1613
1402
  });
1614
1403
  read = owner ? runWithOwner(owner, make) : make();
1615
- asyncReads.set(key, read);
1404
+ reads.set(key, read);
1616
1405
  }
1617
- return read();
1406
+ const v = read();
1407
+ if (v instanceof Element) tierLoads.regions.r.place(v);
1408
+ return v instanceof Boxed ? v.c : v;
1618
1409
  },
1619
1410
  has: (_, key) => key in args(),
1620
1411
  ownKeys: () => Reflect.ownKeys(args()),
@@ -1624,75 +1415,51 @@ function slotArgsProxy(args) {
1624
1415
  } : undefined
1625
1416
  });
1626
1417
  }
1627
- function isReactiveContent(value) {
1628
- if (typeof value === "function") return true;
1629
- if (Array.isArray(value)) {
1630
- for (const v of value) if (isReactiveContent(v)) return true;
1631
- }
1632
- return false;
1633
- }
1634
- function slotsFor(props) {
1635
- const bindings = new Map();
1418
+ function slotsFor(props, scope) {
1636
1419
  const fillScopes = new Map();
1637
1420
  return new Proxy({}, {
1638
1421
  get(_, prop) {
1639
1422
  if (typeof prop !== "string" || !(prop in props)) return undefined;
1640
- return (slotProps, ctx) => {
1423
+ const mount = (slotProps, ctx) => {
1641
1424
  const key = ctx && ctx.key;
1642
- const prev = key !== undefined && bindings.get(key);
1643
- if (prev) {
1644
- bindings.delete(key);
1645
- prev.dispose();
1646
- }
1647
1425
  const prevFill = key !== undefined && fillScopes.get(key);
1648
1426
  if (prevFill) {
1649
1427
  fillScopes.delete(key);
1650
1428
  prevFill.dispose();
1651
1429
  }
1430
+ const range = ctx && ctx.range;
1431
+ if (!range) return undefined;
1652
1432
  const fillOwner = streamInvoke ? createOwner() : null;
1653
- if (fillOwner && key !== undefined && ctx) {
1654
- fillScopes.set(key, fillOwner);
1655
- ctx.onCleanup(() => {
1656
- if (fillScopes.get(key) === fillOwner) fillScopes.delete(key);
1657
- fillOwner.dispose();
1658
- });
1659
- }
1660
- const settle = out => {
1661
- const existing = ctx && ctx.existing || [];
1662
- if (existing.length) {
1663
- const list = Array.isArray(out) ? out : [out];
1664
- const inPlace = list.every(n => existing.some(e => e === n || e.nodeType === 1 && e.contains(n)));
1665
- if (inPlace) return undefined;
1666
- }
1667
- return out;
1668
- };
1433
+ const owner = fillOwner || createOwner({
1434
+ transparent: true
1435
+ });
1436
+ fillScopes.set(key, owner);
1437
+ ctx.onCleanup(() => {
1438
+ if (fillScopes.get(key) === owner) fillScopes.delete(key);
1439
+ owner.dispose();
1440
+ });
1669
1441
  const evaluate = () => {
1670
1442
  const v = props[prop];
1671
1443
  if (typeof v === "function" && ctx && ctx.invoked) {
1672
- return v(ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps));
1444
+ const fillProps = ctx.onUpdate ? liveSlotProps(slotProps, ctx) : slotArgsProxy(() => slotProps);
1445
+ return untrack(() => v(fillProps), undefined);
1673
1446
  }
1674
1447
  return v;
1675
1448
  };
1676
1449
  const adopted = !!(ctx && ctx.frame && ctx.adopted && ctx.existing && ctx.existing.length);
1677
1450
  const prefix = ctx && ctx.frame ? `sc-${ctx.frame}-${ctx.key}-` : "";
1678
- const value = fillOwner ? runWithOwner(fillOwner, () => adopted ? claimRender(prefix, ctx.existing, evaluate) : evaluate()) : adopted ? claimRender(prefix, ctx.existing, evaluate) : evaluate();
1679
- if (!isReactiveContent(value)) {
1680
- return settle(normalizeSlotContent(value));
1681
- }
1682
- if (ctx && ctx.range) {
1683
- const source = value;
1684
- const owner = createOwner();
1685
- bindings.set(key, owner);
1686
- ctx.onCleanup(() => {
1687
- if (bindings.get(key) === owner) bindings.delete(key);
1688
- owner.dispose();
1689
- });
1690
- const end = ctx.range.end;
1691
- const bind = () => insert(end.parentNode, () => typeof source === "function" ? source() : source, end, [...ctx.existing]);
1692
- runWithOwner(owner, () => adopted ? claimRender(prefix, ctx.existing, bind) : bind());
1693
- return undefined;
1694
- }
1695
- return settle(normalizeSlotContent(value));
1451
+ const claim = adopted && runWithOwner(owner, () => createOwner({
1452
+ id: prefix
1453
+ }));
1454
+ const value = adopted ? claimRender(prefix, claim, ctx.existing, evaluate, scope) : fillOwner ? runWithOwner(fillOwner, evaluate) : evaluate();
1455
+ const end = range.end;
1456
+ const bind = () => insert(end.parentNode, value, end, [...ctx.existing]);
1457
+ adopted ? claimRender(prefix, claim, ctx.existing, bind, scope, true) : runWithOwner(owner, bind);
1458
+ return undefined;
1459
+ };
1460
+ return (slotProps, ctx) => {
1461
+ const R = tierLoads.regions?.r;
1462
+ R ? R.nest(mount, slotProps, ctx) : mount(slotProps, ctx);
1696
1463
  };
1697
1464
  }
1698
1465
  });
@@ -1715,12 +1482,8 @@ function boundaryScope(owner) {
1715
1482
  function boundaryComponent(host, fnId) {
1716
1483
  return (props, binding) => {
1717
1484
  const owner = getOwner();
1718
- const id = binding ? binding() : fnId;
1719
- let applied = !tables.has(id);
1720
- let release;
1721
- const arm = () => new Promise(r => release = r);
1722
- const mountGate = applied ? undefined : arm();
1723
- let setGate;
1485
+ const id = binding ? contentAddress(binding()) : fnId;
1486
+ const [failed, onApply] = failing();
1724
1487
  const {
1725
1488
  element,
1726
1489
  frame,
@@ -1729,33 +1492,14 @@ function boundaryComponent(host, fnId) {
1729
1492
  host,
1730
1493
  id,
1731
1494
  slots: slotsFor(props),
1732
- props,
1733
1495
  ownerScope: boundaryScope(owner),
1734
1496
  reveal: revealSeam(owner),
1735
- onApply: () => {
1736
- applied = true;
1737
- if (release) {
1738
- release();
1739
- release = undefined;
1740
- }
1741
- setGate && setGate(undefined);
1742
- }
1497
+ onApply
1743
1498
  });
1744
- const [gatePromise, setGatePromise] = createSignal(applied ? undefined : mountGate);
1745
- setGate = setGatePromise;
1746
- if (binding) {
1747
- createRenderEffect(binding, (address, prev) => {
1748
- if (prev !== undefined && address !== prev && tables.has(address)) {
1749
- applied = false;
1750
- setGatePromise(arm());
1751
- }
1752
- frame.rebind(address);
1753
- });
1754
- }
1755
1499
  onCleanup(dispose);
1756
- if (applied && !binding) return element;
1757
- const gate = createMemo(() => gatePromise());
1758
- return createMemo(() => (gate(), element));
1500
+ if (!binding) return landing(host, id, element, failed);
1501
+ followAddress(host, frame, binding);
1502
+ return createMemo(() => landing(host, contentAddress(binding()), element, failed));
1759
1503
  };
1760
1504
  }
1761
1505
  const claimedBoundaries = new Set();
@@ -1770,7 +1514,12 @@ function pumpLiveChannel() {
1770
1514
  const pump = () => reader.read().then(r => {
1771
1515
  if (r.done) return;
1772
1516
  const op = r.value;
1773
- liveOps.set(`${op.type}:${op.fid || ""}:${op.key || ""}`, op);
1517
+ for (const key in op.r) liveOps.set(`${op.fid || ""}:${key}`, {
1518
+ fid: op.fid,
1519
+ r: {
1520
+ [key]: op.r[key]
1521
+ }
1522
+ });
1774
1523
  for (const apply of liveAppliers) apply(op);
1775
1524
  return pump();
1776
1525
  });
@@ -1780,202 +1529,390 @@ function pumpLiveChannel() {
1780
1529
  let boundaryIndex = null;
1781
1530
  const isBoundaryId = id => !id.includes(".");
1782
1531
  function indexBoundaries(root) {
1783
- root.querySelectorAll(`[${FRAME_ID_ATTR}]`).forEach(el => {
1532
+ root.querySelectorAll(FRAME_SELECTOR).forEach(el => {
1784
1533
  const key = el.getAttribute(FRAME_ID_ATTR);
1785
1534
  if (key && isBoundaryId(key) && !boundaryIndex.has(key)) boundaryIndex.set(key, el);
1786
1535
  });
1787
1536
  }
1788
- function findBoundaryElement(id) {
1537
+ function findBoundaryElement(id, address) {
1789
1538
  if (!boundaryIndex) {
1790
1539
  boundaryIndex = new Map();
1791
1540
  if (typeof document !== "undefined" && document.body) indexBoundaries(document.body);
1792
1541
  }
1793
- return boundaryIndex.get(id);
1542
+ const args = address && address.slice(id.length + 1);
1543
+ let first, el;
1544
+ for (let n = 0;; n++) {
1545
+ const key = n ? id + "~" + (n + 1) : id;
1546
+ if (claimedBoundaries.has(key)) continue;
1547
+ if (!(el = boundaryIndex.get(key)) || !args || el.dataset.fa == args) return el || first;
1548
+ first = first || el;
1549
+ }
1550
+ }
1551
+ const arrivals = new Map();
1552
+ const FRAME_SELECTOR = `[${FRAME_ID_ATTR}]`;
1553
+ const disposedFrames = new WeakSet();
1554
+ function awaitBoundary(id) {
1555
+ let arrival = arrivals.get(id);
1556
+ if (!arrival) {
1557
+ let resolve;
1558
+ const promise = new Promise(r => resolve = r);
1559
+ if (!resolve) return promise;
1560
+ arrivals.set(id, arrival = {
1561
+ promise,
1562
+ resolve
1563
+ });
1564
+ onHydrationEnd(releaseArrivals);
1565
+ }
1566
+ return arrival.promise;
1567
+ }
1568
+ function releaseArrivals() {
1569
+ if (!arrivals.size) return;
1570
+ const exhausted = !boundaryMayArrive();
1571
+ for (const [id, arrival] of arrivals) {
1572
+ const el = boundaryIndex && boundaryIndex.get(id);
1573
+ if (!el && !exhausted) continue;
1574
+ arrivals.delete(id);
1575
+ arrival.resolve(!!el);
1576
+ }
1794
1577
  }
1795
- const boundaryWaiters = new Map();
1796
1578
  function boundaryMayArrive() {
1797
1579
  const hy = globalThis._$HY;
1798
1580
  if (!hy) return false;
1799
- return !hy.done || !!(hy.fr && hy.fr.pending());
1581
+ return !(hy.done || sharedConfig.done) || !!(hy.fr && hy.fr.pending());
1800
1582
  }
1801
1583
  function installRevealHook() {
1584
+ installServerComponentHydration();
1802
1585
  const hy = globalThis._$HY;
1803
1586
  if (!hy || hy.$sc || !hy.fr) return;
1804
1587
  hy.$sc = true;
1588
+ hy.fa = pl => {
1589
+ const el = pl.closest(FRAME_SELECTOR);
1590
+ return !!el && !disposedFrames.has(el);
1591
+ };
1805
1592
  hy.fr.subscribe((_id, parent) => {
1806
1593
  if (!boundaryIndex) return;
1807
1594
  const root = parent || (typeof document !== "undefined" ? document.body : null);
1808
1595
  if (root) indexBoundaries(root);
1809
- if (!boundaryWaiters.size) return;
1810
- const exhausted = hy.done && !hy.fr.pending();
1811
- for (const [id, notify] of boundaryWaiters) {
1812
- const el = boundaryIndex && boundaryIndex.get(id);
1813
- if (!el && !exhausted) continue;
1814
- boundaryWaiters.delete(id);
1815
- notify(el);
1816
- }
1596
+ releaseArrivals();
1817
1597
  });
1818
1598
  }
1819
1599
  function documentBoundary(host, id, props, binding) {
1820
1600
  installRevealHook();
1821
- const claimed = claimedBoundaries.has(id);
1822
- const el = !claimed ? findBoundaryElement(id) : undefined;
1601
+ const address = binding && contentAddress(binding());
1602
+ const el = findBoundaryElement(id, address);
1823
1603
  if (el) return adoptBoundary(host, id, el, props, binding);
1824
- if (!claimed && !boundaryWaiters.has(id) && boundaryMayArrive()) {
1604
+ if (!claimedBoundaries.has(id) && boundaryMayArrive()) {
1825
1605
  const owner = getOwner();
1826
- const arrival = new Promise(resolve => boundaryWaiters.set(id, resolve));
1827
- onCleanup(() => boundaryWaiters.delete(id));
1828
- return createMemo(() => arrival.then(node => runWithOwner(owner, () =>
1829
- node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding))));
1606
+ let live = true;
1607
+ onCleanup(() => live = false);
1608
+ return createMemo(() => awaitBoundary(id).then(() => live && runWithOwner(owner, () => {
1609
+ const node = findBoundaryElement(id, address);
1610
+ return node ? adoptBoundary(host, id, node, props, binding) : boundaryComponent(host, id)(props, binding);
1611
+ })));
1830
1612
  }
1831
1613
  return boundaryComponent(host, id)(props, binding);
1832
1614
  }
1833
- function documentAddress(id) {
1834
- const records = globalThis._$SC?.a;
1835
- if (records) {
1836
- for (const address in records) if (records[address] === id) return address;
1837
- }
1838
- return id;
1839
- }
1840
1615
  function adoptBoundary(host, id, el, props, binding) {
1841
- claimedBoundaries.add(id);
1842
- const address = binding ? binding() : documentAddress(id);
1616
+ const siteId = el.getAttribute(FRAME_ID_ATTR);
1617
+ claimedBoundaries.add(siteId);
1618
+ edgeRoots.set(siteId, el);
1619
+ const address = binding ? contentAddress(binding()) : id;
1843
1620
  const appliedRecords = new Set();
1844
- const claimedFragments = new Set();
1845
- const claimRegionFragments = root => {
1846
- const fr = globalThis._$HY?.fr;
1847
- if (!fr || !fr.claim) return;
1848
- root.querySelectorAll('template[id^="pl-"]').forEach(tpl => {
1849
- const fragId = tpl.id.slice(3);
1850
- if (claimedFragments.has(fragId)) return;
1851
- claimedFragments.add(fragId);
1852
- fr.claim(fragId);
1853
- });
1854
- };
1855
1621
  const drainRecords = () => {
1856
1622
  const hy = globalThis._$HY;
1857
1623
  if (!hy || !hy.r) return;
1858
1624
  pumpLiveChannel();
1859
- const slotPrefix = `sc:slot:${id}:`;
1625
+ const slotPrefix = `sc:slot:${siteId}:`;
1860
1626
  for (const key of Object.keys(hy.r)) {
1861
1627
  if (appliedRecords.has(key)) continue;
1862
1628
  if (key.startsWith(slotPrefix)) {
1863
1629
  appliedRecords.add(key);
1864
- host.apply({
1865
- type: "slot",
1630
+ const apply = args => host.apply({
1866
1631
  id: address,
1867
1632
  version: 0,
1868
- key: key.slice(slotPrefix.length),
1869
- args: hy.r[key]
1633
+ r: {
1634
+ [`slot:${key.slice(slotPrefix.length)}`]: {
1635
+ kind: "slot",
1636
+ args
1637
+ }
1638
+ }
1870
1639
  });
1640
+ const value = hy.r[key];
1641
+ if (value && typeof value.then === "function") {
1642
+ if (value.s === 1) apply(value.v);else if (value.s === 2) value.then(undefined, () => {});else value.then(apply, () => {});
1643
+ } else apply(value);
1871
1644
  } else if (key.startsWith("sc:region:")) {
1872
1645
  const childId = key.slice("sc:region:".length);
1873
- if (childId.startsWith(id + ".")) {
1646
+ if (childId.startsWith(siteId + ".")) {
1874
1647
  appliedRecords.add(key);
1875
1648
  const val = hy.r[key];
1876
1649
  const apply = html => host.apply({
1877
- type: "html",
1878
1650
  id: childId,
1879
1651
  version: 0,
1880
- html
1652
+ r: {
1653
+ "": {
1654
+ kind: "html",
1655
+ value: html
1656
+ }
1657
+ }
1881
1658
  });
1882
1659
  val && typeof val.then === "function" ? val.then(apply) : apply(val);
1883
1660
  }
1884
1661
  }
1885
1662
  }
1886
1663
  };
1887
- claimRegionFragments(el);
1664
+ const scope = claimScope(el);
1888
1665
  const fr = globalThis._$HY?.fr;
1666
+ let frame;
1889
1667
  const unsubscribe = fr ? fr.subscribe((_fragId, parent) => {
1890
- if (fr.claim && parent && el.contains(parent)) claimRegionFragments(parent);
1668
+ const inside = !!parent && el.contains(parent);
1669
+ inside && scope.index(parent);
1891
1670
  drainRecords();
1671
+ if (inside && frame) frame.apply({
1672
+ version: frame.version ?? 0,
1673
+ r: {}
1674
+ });
1892
1675
  }) : undefined;
1893
1676
  const applyLiveOp = op => {
1894
- if (op.type === "slot" && op.fid !== id) return;
1677
+ if (op.fid && op.fid !== siteId) return;
1895
1678
  host.apply({
1896
- ...op,
1897
1679
  id: address,
1898
- version: 0
1680
+ version: 0,
1681
+ r: op.r
1899
1682
  });
1900
1683
  };
1901
1684
  liveAppliers.add(applyLiveOp);
1902
1685
  onCleanup(() => {
1903
1686
  liveAppliers.delete(applyLiveOp);
1904
1687
  unsubscribe && unsubscribe();
1905
- if (fr && fr.release) for (const fragId of claimedFragments) fr.release(fragId);
1906
1688
  });
1907
1689
  drainRecords();
1908
1690
  for (const op of liveOps.values()) applyLiveOp(op);
1909
1691
  const owner = getOwner();
1910
- let release;
1911
- let setGate;
1912
- const frame = createFrame(el, {
1692
+ const sc = sharedConfig;
1693
+ const [failed, onApply] = failing();
1694
+ frame = createFrame(el, {
1913
1695
  adopt: true,
1696
+ defer: true,
1914
1697
  host,
1915
1698
  id: address,
1916
- slots: slotsFor(props),
1917
- props,
1699
+ slots: slotsFor(props, scope),
1918
1700
  ownerScope: boundaryScope(owner),
1919
1701
  reveal: revealSeam(owner),
1920
- onApply: () => {
1921
- if (release) {
1922
- release();
1923
- release = undefined;
1924
- }
1925
- setGate && setGate(undefined);
1926
- },
1702
+ onApply,
1703
+ hold: () => sc.isHydrationInProgress?.() ? runWithOwner(owner, () => untrack(() => sc.holdBoundary("sc:" + siteId))) : () => {},
1927
1704
  ...{
1928
- recordsPending: () => {
1929
- if (document.readyState === "loading") return true;
1930
- const hy = globalThis._$HY;
1931
- return !!(hy && hy.fr && hy.fr.pending());
1932
- },
1933
- drainRecords,
1934
- claimScope: id
1705
+ claimScope: siteId
1935
1706
  }
1936
1707
  });
1937
1708
  if (binding) {
1938
- const arm = () => new Promise(r => release = r);
1939
- const [gatePromise, setGatePromise] = createSignal(undefined);
1940
- setGate = setGatePromise;
1941
- const gate = createMemo(() => gatePromise());
1942
- createRenderEffect(binding, (address, prev) => {
1943
- if (prev !== undefined && address !== prev && tables.has(address)) {
1944
- setGatePromise(arm());
1945
- }
1946
- frame.rebind(address);
1947
- });
1948
- createRenderEffect(() => (gate(), undefined), () => {});
1709
+ followAddress(host, frame, binding);
1710
+ const source = createMemo(() => landing(host, contentAddress(binding()), true, failed));
1711
+ createRenderEffect(() => source()(), () => {});
1949
1712
  }
1950
- onCleanup(() => frame.dispose());
1713
+ onCleanup(() => {
1714
+ frame.dispose();
1715
+ disposedFrames.add(el);
1716
+ el.querySelectorAll(FRAME_SELECTOR).forEach(e => disposedFrames.add(e));
1717
+ });
1951
1718
  return el;
1952
1719
  }
1953
- function installServerComponents(host = getFrameHost()) {
1720
+ const DEFER_EVENTS = ["click", "input", "change", "keydown", "pointerdown", "submit", "focusin"];
1721
+ const DEFER_BUDGET = 8;
1722
+ let mounting = false;
1723
+ const idleTick = () => new Promise(r => typeof requestIdleCallback === "function" ? requestIdleCallback(() => r(), {
1724
+ timeout: 100
1725
+ }) : setTimeout(r, 0));
1726
+ function wakeAt(e) {
1727
+ const target = e.target;
1728
+ if (!target || mounting) return;
1729
+ mounting = true;
1730
+ try {
1731
+ for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1732
+ } finally {
1733
+ mounting = false;
1734
+ }
1735
+ deferDone();
1736
+ }
1737
+ function mountAllDeferred() {
1738
+ if (mounting || sharedConfig.hydrating) return;
1739
+ mounting = true;
1740
+ try {
1741
+ for (let frames; (frames = deferredFrames()).length;) for (const f of frames) f.mountDeferred();
1742
+ } finally {
1743
+ mounting = false;
1744
+ }
1745
+ deferDone();
1746
+ }
1747
+ const edgeRoots = new Map();
1748
+ let edgeIndex;
1749
+ const DEPS = "sc:deps:";
1750
+ function buildEdgeIndex() {
1751
+ const r = globalThis._$HY?.r;
1752
+ if (!r) return undefined;
1753
+ const idx = {
1754
+ readers: new Map(),
1755
+ wide: new Set(),
1756
+ untracked: [],
1757
+ sites: new Set(),
1758
+ starts: new Map()
1759
+ };
1760
+ for (const site of edgeRoots.keys()) for (let n = 0, batch; batch = r[DEPS + site + ":" + n]; n++) {
1761
+ if (typeof batch !== "object") return undefined;
1762
+ idx.sites.add(site);
1763
+ for (const sid in batch) {
1764
+ const occs = unpackOccurrences(batch[sid]);
1765
+ if (sid === "*") occs.forEach(w => idx.wide.add(w));else if (sid === "!") occs.forEach(o => idx.untracked.push([site, o]));else {
1766
+ let list = idx.readers.get(sid);
1767
+ if (!list) idx.readers.set(sid, list = []);
1768
+ for (const o of occs) list.push([site, o]);
1769
+ }
1770
+ }
1771
+ }
1772
+ return idx;
1773
+ }
1774
+ function unpackOccurrences(packed) {
1775
+ const out = [];
1776
+ for (const part of packed.split(" ")) {
1777
+ const m = /^(.*)#(\d+)-(\d+)$/.exec(part);
1778
+ if (!m) part && out.push(part);else for (let i = +m[2]; i <= +m[3]; i++) out.push(m[1] + "#" + i);
1779
+ }
1780
+ return out;
1781
+ }
1782
+ function startOf(idx, site, occ) {
1783
+ let m = idx.starts.get(site);
1784
+ if (!m) {
1785
+ idx.starts.set(site, m = new Map());
1786
+ const root = edgeRoots.get(site);
1787
+ if (root) {
1788
+ const w = document.createTreeWalker(root, 128 );
1789
+ for (let c = w.nextNode(); c; c = w.nextNode()) {
1790
+ const d = c.data;
1791
+ if (d.startsWith("slot:") && d.endsWith(":start")) m.set(d.slice(5, -6), c);
1792
+ }
1793
+ }
1794
+ }
1795
+ return m.get(occ);
1796
+ }
1797
+ function edgesCover(idx) {
1798
+ outer: for (const f of deferredFrames()) {
1799
+ for (const [site, root] of edgeRoots) if (idx.sites.has(site) && root.contains(f.el)) continue outer;
1800
+ return false;
1801
+ }
1802
+ return true;
1803
+ }
1804
+ function mountForWrite(node) {
1805
+ if (mounting || sharedConfig.hydrating) return;
1806
+ const sid = signalName(node) ?? storeName(node);
1807
+ if (sid === undefined || document.readyState === "loading") return mountAllDeferred();
1808
+ const idx = edgeIndex ||= buildEdgeIndex();
1809
+ if (!idx || idx.wide.has(sid) || !edgesCover(idx)) return mountAllDeferred();
1810
+ const readers = idx.readers.get(sid);
1811
+ if (!readers && !idx.untracked.length) return;
1812
+ mounting = true;
1813
+ try {
1814
+ for (const list of [readers || [], idx.untracked]) for (const [site, occ] of list) {
1815
+ const root = edgeRoots.get(site);
1816
+ if (root && deferredFrames().some(f => root.contains(f.el) && f.mountOccurrence(occ))) continue;
1817
+ const start = startOf(idx, site, occ);
1818
+ const target = start && (start.nextSibling || start);
1819
+ if (target) for (let f; (f = liveFrameAt(target)) && f.mountEnclosing(target););
1820
+ }
1821
+ } finally {
1822
+ mounting = false;
1823
+ }
1824
+ deferDone();
1825
+ }
1826
+ let idlePass;
1827
+ function mountIdle() {
1828
+ return idlePass ||= (async () => {
1829
+ if (document.readyState !== "complete") await new Promise(r => addEventListener("load", r, {
1830
+ once: true
1831
+ }));
1832
+ globalThis._$HY?.r?.["sc:tiers"]?.forEach(prepareTier);
1833
+ await Promise.all(Object.values(tierLoads)).catch(() => {});
1834
+ for (let frames; (frames = deferredFrames()).length;) {
1835
+ await idleTick();
1836
+ const deadline = performance.now() + DEFER_BUDGET;
1837
+ mounting = true;
1838
+ try {
1839
+ for (const f of frames) if (!f.mountDeferred(deadline) || performance.now() > deadline) break;
1840
+ } finally {
1841
+ mounting = false;
1842
+ }
1843
+ }
1844
+ idlePass = undefined;
1845
+ deferDone();
1846
+ })();
1847
+ }
1848
+ function deferDone() {
1849
+ if (deferredFrames().length) return;
1850
+ if (deferring) {
1851
+ deferring = false;
1852
+ edgeIndex = undefined;
1853
+ setWriteHook(null);
1854
+ DEFER_EVENTS.forEach(t => document.removeEventListener(t, wakeAt, true));
1855
+ }
1856
+ releaseDeferHolds();
1857
+ }
1858
+ let deferHydration = true;
1859
+ function setDeferredHydration(on) {
1860
+ deferHydration = on;
1861
+ setDeferDriver(on && typeof document !== "undefined" ? deferFrame : null);
1862
+ setSignalIdentities(on && typeof document !== "undefined");
1863
+ }
1864
+ let deferring = false;
1865
+ function deferFrame(frame) {
1866
+ if (!deferring) {
1867
+ deferring = true;
1868
+ setWriteHook(mountForWrite);
1869
+ DEFER_EVENTS.forEach(t => document.addEventListener(t, wakeAt, true));
1870
+ }
1871
+ const queued = sharedConfig.events;
1872
+ if (queued && queued.length) for (const [el, e] of queued) if (frame.el.contains(el)) wakeAt({
1873
+ target: e.target ?? el
1874
+ });
1875
+ mountIdle();
1876
+ }
1877
+ function installServerComponents(host = getFrameHost(), options) {
1954
1878
  const g = globalThis;
1879
+ Object.assign(tierLoaders, options?.tiers);
1880
+ g._$HY?.r?.["sc:tiers"]?.forEach(prepareTier);
1955
1881
  if (!g._$SC) {
1956
1882
  g._$SC = {
1957
1883
  c: {},
1958
1884
  a: {},
1885
+ b: {},
1959
1886
  r(i, a) {
1960
- if (a) {
1961
- g._$SC.a[a] = i;
1962
- g._$SC.reg && g._$SC.reg(a, i);
1963
- }
1964
- return g._$SC.c[i] || (g._$SC.c[i] = (p, b) => g._$SC.impl(i, p, b));
1887
+ const c = g._$SC.c[i] || (g._$SC.c[i] = (p, b) => g._$SC.impl(i, p, b));
1888
+ if (!a) return c;
1889
+ g._$SC.a[a] = i;
1890
+ g._$SC.reg && g._$SC.reg(a, i);
1891
+ return g._$SC.b[a] || (g._$SC.b[a] = Object.assign(p => c(p, () => a), {
1892
+ [COMPONENT_BINDING]: {
1893
+ component: c,
1894
+ address: a
1895
+ }
1896
+ }));
1965
1897
  }
1966
1898
  };
1967
1899
  }
1968
1900
  g._$SC.impl = (id, props, binding) => documentBoundary(host, id, props, binding);
1969
1901
  installRevealHook();
1902
+ if (typeof document !== "undefined" && deferHydration) {
1903
+ setDeferDriver(deferFrame);
1904
+ setSignalIdentities(true);
1905
+ }
1970
1906
  const handler = createServerComponentHandler({
1971
1907
  host,
1972
1908
  component: fnId => g._$SC.r(fnId),
1973
- onStream: address => beginStream(address),
1974
1909
  intercept: ({
1975
1910
  id
1976
1911
  }) => {
1977
- if (claimedBoundaries.has(id) || !findBoundaryElement(id)) return undefined;
1978
- return g._$SC.r(id);
1912
+ if (findBoundaryElement(id)) return true;
1913
+ if (claimedBoundaries.has(id) || !boundaryMayArrive()) return undefined;
1914
+ installRevealHook();
1915
+ return awaitBoundary(id);
1979
1916
  }
1980
1917
  });
1981
1918
  const showing = (address, id) => handler.showing(address, id);
@@ -1987,4 +1924,4 @@ function installServerComponents(host = getFrameHost()) {
1987
1924
  });
1988
1925
  }
1989
1926
 
1990
- export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isFrameStreamResponse };
1927
+ export { FRAME_APPLIED_EVENT, FRAME_STREAM_HEADER, applyFrameResponse, asyncArg, createFrame, createFrameElement, createFrameHost, createServerComponentHandler, getFrameHost, installServerComponents, isFrameStreamResponse, setDeferredHydration };