@shadow-js/web 1.0.1 → 1.0.2

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 (208) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/dev/attributes.d.ts +10 -3
  3. package/dist/dev/attributes.js +27 -49
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +6 -2
  6. package/dist/dev/class-style.js +24 -7
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.d.ts +11 -2
  9. package/dist/dev/control-flow/dynamic.js +56 -39
  10. package/dist/dev/control-flow/dynamic.js.map +1 -1
  11. package/dist/dev/control-flow/portal.js +2 -0
  12. package/dist/dev/control-flow/portal.js.map +1 -1
  13. package/dist/dev/element.js +1 -1
  14. package/dist/dev/element.js.map +1 -1
  15. package/dist/dev/events.js +15 -44
  16. package/dist/dev/events.js.map +1 -1
  17. package/dist/dev/insert.d.ts +15 -5
  18. package/dist/dev/insert.js +35 -13
  19. package/dist/dev/insert.js.map +1 -1
  20. package/dist/dev/internal/claim.d.ts +2 -1
  21. package/dist/dev/internal/claim.js +18 -2
  22. package/dist/dev/internal/claim.js.map +1 -1
  23. package/dist/dev/internal/diagnostics.d.ts +7 -3
  24. package/dist/dev/internal/diagnostics.js +14 -4
  25. package/dist/dev/internal/diagnostics.js.map +1 -1
  26. package/dist/dev/internal/early-events.js +20 -2
  27. package/dist/dev/internal/early-events.js.map +1 -1
  28. package/dist/dev/internal/react-names.js +25 -61
  29. package/dist/dev/internal/react-names.js.map +1 -1
  30. package/dist/dev/internal/reconcile.js +3 -6
  31. package/dist/dev/internal/reconcile.js.map +1 -1
  32. package/dist/dev/jsx/global.d.ts +5 -2
  33. package/dist/dev/jsx/html.d.ts +1 -0
  34. package/dist/dev/resource-hints.js +4 -2
  35. package/dist/dev/resource-hints.js.map +1 -1
  36. package/dist/dev/select-value.js +5 -15
  37. package/dist/dev/select-value.js.map +1 -1
  38. package/dist/dev/server/attributes.d.ts +3 -0
  39. package/dist/dev/server/attributes.js +5 -1
  40. package/dist/dev/server/attributes.js.map +1 -1
  41. package/dist/dev/server/element.js +8 -4
  42. package/dist/dev/server/element.js.map +1 -1
  43. package/dist/dev/server/errors.js +7 -1
  44. package/dist/dev/server/errors.js.map +1 -1
  45. package/dist/dev/server/escape.js +14 -6
  46. package/dist/dev/server/escape.js.map +1 -1
  47. package/dist/dev/server/form-controls.js +5 -2
  48. package/dist/dev/server/form-controls.js.map +1 -1
  49. package/dist/dev/server/index.d.ts +2 -1
  50. package/dist/dev/server/index.js +2 -1
  51. package/dist/dev/server/raw-text.d.ts +28 -0
  52. package/dist/dev/server/raw-text.js +66 -0
  53. package/dist/dev/server/raw-text.js.map +1 -0
  54. package/dist/dev/server/render.d.ts +2 -1
  55. package/dist/dev/server/render.js +2 -2
  56. package/dist/dev/server/render.js.map +1 -1
  57. package/dist/dev/server/stream.d.ts +1 -1
  58. package/dist/dev/server/stream.js +2 -2
  59. package/dist/dev/server/stream.js.map +1 -1
  60. package/dist/dev/server.d.ts +2 -1
  61. package/dist/dev/server.js +2 -1
  62. package/dist/dev/spread.js +7 -54
  63. package/dist/dev/spread.js.map +1 -1
  64. package/dist/prod/attributes.js +1 -1
  65. package/dist/prod/attributes.js.map +1 -1
  66. package/dist/prod/class-style.js +1 -1
  67. package/dist/prod/class-style.js.map +1 -1
  68. package/dist/prod/control-flow/dynamic.js +1 -1
  69. package/dist/prod/control-flow/dynamic.js.map +1 -1
  70. package/dist/prod/control-flow/portal.js +1 -1
  71. package/dist/prod/control-flow/portal.js.map +1 -1
  72. package/dist/prod/element.js +1 -1
  73. package/dist/prod/element.js.map +1 -1
  74. package/dist/prod/events.js +1 -1
  75. package/dist/prod/events.js.map +1 -1
  76. package/dist/prod/insert.js +1 -1
  77. package/dist/prod/insert.js.map +1 -1
  78. package/dist/prod/internal/claim.js +1 -1
  79. package/dist/prod/internal/claim.js.map +1 -1
  80. package/dist/prod/internal/diagnostics.js +1 -1
  81. package/dist/prod/internal/diagnostics.js.map +1 -1
  82. package/dist/prod/internal/early-events.js +1 -1
  83. package/dist/prod/internal/early-events.js.map +1 -1
  84. package/dist/prod/internal/react-names.js +1 -1
  85. package/dist/prod/internal/react-names.js.map +1 -1
  86. package/dist/prod/internal/reconcile.js +1 -1
  87. package/dist/prod/internal/reconcile.js.map +1 -1
  88. package/dist/prod/resource-hints.js +1 -1
  89. package/dist/prod/resource-hints.js.map +1 -1
  90. package/dist/prod/select-value.js +1 -1
  91. package/dist/prod/select-value.js.map +1 -1
  92. package/dist/prod/server/attributes.js +1 -1
  93. package/dist/prod/server/attributes.js.map +1 -1
  94. package/dist/prod/server/element.js +1 -1
  95. package/dist/prod/server/element.js.map +1 -1
  96. package/dist/prod/server/errors.js +1 -1
  97. package/dist/prod/server/errors.js.map +1 -1
  98. package/dist/prod/server/escape.js +1 -1
  99. package/dist/prod/server/escape.js.map +1 -1
  100. package/dist/prod/server/form-controls.js +2 -2
  101. package/dist/prod/server/form-controls.js.map +1 -1
  102. package/dist/prod/server/index.js +1 -1
  103. package/dist/prod/server/raw-text.js +2 -0
  104. package/dist/prod/server/raw-text.js.map +1 -0
  105. package/dist/prod/server/render.js +1 -1
  106. package/dist/prod/server/render.js.map +1 -1
  107. package/dist/prod/server/stream.js +1 -1
  108. package/dist/prod/server/stream.js.map +1 -1
  109. package/dist/prod/server.js +1 -1
  110. package/dist/prod/spread.js +1 -1
  111. package/dist/prod/spread.js.map +1 -1
  112. package/dist/server/attributes.js +1 -1
  113. package/dist/server/attributes.js.map +1 -1
  114. package/dist/server/class-style.js +1 -1
  115. package/dist/server/class-style.js.map +1 -1
  116. package/dist/server/control-flow/dynamic.js +1 -1
  117. package/dist/server/control-flow/dynamic.js.map +1 -1
  118. package/dist/server/control-flow/portal.js +1 -1
  119. package/dist/server/control-flow/portal.js.map +1 -1
  120. package/dist/server/element.js +1 -1
  121. package/dist/server/element.js.map +1 -1
  122. package/dist/server/events.js +1 -1
  123. package/dist/server/events.js.map +1 -1
  124. package/dist/server/insert.js +1 -1
  125. package/dist/server/insert.js.map +1 -1
  126. package/dist/server/internal/claim.js +1 -1
  127. package/dist/server/internal/claim.js.map +1 -1
  128. package/dist/server/internal/diagnostics.js +1 -1
  129. package/dist/server/internal/diagnostics.js.map +1 -1
  130. package/dist/server/internal/early-events.js +1 -1
  131. package/dist/server/internal/early-events.js.map +1 -1
  132. package/dist/server/internal/react-names.js +1 -1
  133. package/dist/server/internal/react-names.js.map +1 -1
  134. package/dist/server/internal/reconcile.js +1 -1
  135. package/dist/server/internal/reconcile.js.map +1 -1
  136. package/dist/server/resource-hints.js +1 -1
  137. package/dist/server/resource-hints.js.map +1 -1
  138. package/dist/server/select-value.js +1 -1
  139. package/dist/server/select-value.js.map +1 -1
  140. package/dist/server/server/attributes.js +1 -1
  141. package/dist/server/server/attributes.js.map +1 -1
  142. package/dist/server/server/element.js +1 -1
  143. package/dist/server/server/element.js.map +1 -1
  144. package/dist/server/server/errors.js +1 -1
  145. package/dist/server/server/errors.js.map +1 -1
  146. package/dist/server/server/escape.js +1 -1
  147. package/dist/server/server/escape.js.map +1 -1
  148. package/dist/server/server/form-controls.js +2 -2
  149. package/dist/server/server/form-controls.js.map +1 -1
  150. package/dist/server/server/index.js +1 -1
  151. package/dist/server/server/raw-text.js +2 -0
  152. package/dist/server/server/raw-text.js.map +1 -0
  153. package/dist/server/server/render.js +1 -1
  154. package/dist/server/server/render.js.map +1 -1
  155. package/dist/server/server/stream.js +1 -1
  156. package/dist/server/server/stream.js.map +1 -1
  157. package/dist/server/server.js +1 -1
  158. package/dist/server/spread.js +1 -1
  159. package/dist/server/spread.js.map +1 -1
  160. package/dist/server-dev/attributes.js +27 -49
  161. package/dist/server-dev/attributes.js.map +1 -1
  162. package/dist/server-dev/class-style.js +24 -7
  163. package/dist/server-dev/class-style.js.map +1 -1
  164. package/dist/server-dev/control-flow/dynamic.js +22 -10
  165. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  166. package/dist/server-dev/control-flow/portal.js +2 -0
  167. package/dist/server-dev/control-flow/portal.js.map +1 -1
  168. package/dist/server-dev/element.js +3 -1
  169. package/dist/server-dev/element.js.map +1 -1
  170. package/dist/server-dev/events.js +15 -44
  171. package/dist/server-dev/events.js.map +1 -1
  172. package/dist/server-dev/insert.js +35 -13
  173. package/dist/server-dev/insert.js.map +1 -1
  174. package/dist/server-dev/internal/claim.js +18 -2
  175. package/dist/server-dev/internal/claim.js.map +1 -1
  176. package/dist/server-dev/internal/diagnostics.js +14 -4
  177. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  178. package/dist/server-dev/internal/early-events.js +20 -2
  179. package/dist/server-dev/internal/early-events.js.map +1 -1
  180. package/dist/server-dev/internal/react-names.js +25 -61
  181. package/dist/server-dev/internal/react-names.js.map +1 -1
  182. package/dist/server-dev/internal/reconcile.js +3 -6
  183. package/dist/server-dev/internal/reconcile.js.map +1 -1
  184. package/dist/server-dev/resource-hints.js +4 -2
  185. package/dist/server-dev/resource-hints.js.map +1 -1
  186. package/dist/server-dev/select-value.js +5 -15
  187. package/dist/server-dev/select-value.js.map +1 -1
  188. package/dist/server-dev/server/attributes.js +5 -1
  189. package/dist/server-dev/server/attributes.js.map +1 -1
  190. package/dist/server-dev/server/element.js +8 -4
  191. package/dist/server-dev/server/element.js.map +1 -1
  192. package/dist/server-dev/server/errors.js +7 -1
  193. package/dist/server-dev/server/errors.js.map +1 -1
  194. package/dist/server-dev/server/escape.js +14 -6
  195. package/dist/server-dev/server/escape.js.map +1 -1
  196. package/dist/server-dev/server/form-controls.js +5 -2
  197. package/dist/server-dev/server/form-controls.js.map +1 -1
  198. package/dist/server-dev/server/index.js +2 -1
  199. package/dist/server-dev/server/raw-text.js +86 -0
  200. package/dist/server-dev/server/raw-text.js.map +1 -0
  201. package/dist/server-dev/server/render.js +2 -2
  202. package/dist/server-dev/server/render.js.map +1 -1
  203. package/dist/server-dev/server/stream.js +2 -2
  204. package/dist/server-dev/server/stream.js.map +1 -1
  205. package/dist/server-dev/server.js +2 -1
  206. package/dist/server-dev/spread.js +7 -54
  207. package/dist/server-dev/spread.js.map +1 -1
  208. package/package.json +3 -2
@@ -2,10 +2,12 @@ import { checkClaimedText } from "./internal/claim.js";
2
2
  import { claims } from "./internal/hydration-hooks.js";
3
3
  import { reconcileNodes } from "./internal/reconcile.js";
4
4
  import { useRenderEffect } from "@shadow-js/core";
5
- import { createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
5
+ import { addCleanup, createComputation, currentOwner, disposeOwner, readComputation } from "@shadow-js/core/extend";
6
6
  // src/insert.ts
7
7
  /** Longest chain of accessors a single value may hold (a function returning a function ...). */
8
8
  const MAX_ACCESSOR_DEPTH = 1e4;
9
+ /** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */
10
+ const tails = /* @__PURE__ */ new WeakMap();
9
11
  /** The document a node belongs to (a Document is its own document). */
10
12
  function documentOf(node) {
11
13
  return node instanceof Document ? node : node.ownerDocument ?? document;
@@ -57,9 +59,7 @@ function flatten(root, call = (fn) => fn()) {
57
59
  item = call(item);
58
60
  }
59
61
  if (item === null || item === void 0 || typeof item === "boolean") continue;
60
- if (typeof item === "string") parts.push(item);
61
- else if (typeof item === "number") parts.push(String(item));
62
- else if (item instanceof DocumentFragment) for (const child of item.childNodes) parts.push(child);
62
+ if (item instanceof DocumentFragment) for (const child of item.childNodes) parts.push(child);
63
63
  else if (item instanceof Node) parts.push(item);
64
64
  else if (Array.isArray(item)) {
65
65
  if (active.has(item)) throw new TypeError("insert(): a value contains itself.");
@@ -113,10 +113,9 @@ function materialize(region, parts) {
113
113
  nodes.length = count;
114
114
  return nodes;
115
115
  }
116
- /** The node after the region: its anchor, or the node after its last attached child, or its marker. */
117
- function endOf(region, attached) {
116
+ /** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */
117
+ function endOf(region, last) {
118
118
  if (region.anchor !== null) return region.anchor;
119
- const last = attached.at(-1);
120
119
  if (last !== void 0) return last.nextSibling;
121
120
  const marker = region.marker;
122
121
  if (marker === null) return region.parent.firstChild;
@@ -127,7 +126,7 @@ function endOf(region, attached) {
127
126
  function reconcileRegion(region, next) {
128
127
  const parent = region.parent;
129
128
  const attached = region.nodes.filter((node) => node.parentNode === parent);
130
- const end = endOf(region, attached);
129
+ const end = endOf(region, attached.at(-1));
131
130
  const first = attached[0];
132
131
  if (next.length === 0 && first !== void 0) region.marker = first.previousSibling;
133
132
  reconcileNodes(parent, attached, next, end);
@@ -160,7 +159,7 @@ function commitValue(region, raw) {
160
159
  } else if (nodes.length === 0) {
161
160
  const created = documentOf(region.parent).createTextNode(text);
162
161
  addText(region, created);
163
- region.parent.insertBefore(created, endOf(region, nodes));
162
+ region.parent.insertBefore(created, endOf(region, void 0));
164
163
  region.nodes = [created];
165
164
  return;
166
165
  }
@@ -197,6 +196,24 @@ function createRegion(parent, anchorNode, initial) {
197
196
  return region;
198
197
  }
199
198
  /**
199
+ * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive
200
+ * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then
201
+ * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling
202
+ * region can replace: the order of the calls holds however the regions change. A region with static content
203
+ * between it and this one needs nothing, because its marker and its end are the static nodes.
204
+ */
205
+ function linkRegion(region) {
206
+ const parent = region.parent;
207
+ const tail = tails.get(parent);
208
+ region.owner = currentOwner();
209
+ tails.set(parent, region);
210
+ const start = region.nodes[0] ?? null;
211
+ if (tail === void 0 || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start) return;
212
+ const text = anchor(parent, start);
213
+ tail.anchor = region.marker = text;
214
+ if (tail.owner) addCleanup(tail.owner, () => text.remove());
215
+ }
216
+ /**
200
217
  * True when a function appears anywhere in `root`, at any array depth. Scans without calling
201
218
  * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).
202
219
  */
@@ -256,15 +273,17 @@ function createCallCache(owner) {
256
273
  /**
257
274
  * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an
258
275
  * array with accessor members) runs inside a render effect, so its reads are tracked. Anything
259
- * else is inserted once.
276
+ * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps
277
+ * its place among the other such regions of its parent (see `linkRegion`).
260
278
  * @internal
261
279
  */
262
- function bindRegion(region, value) {
280
+ function bindRegion(region, value, ordered) {
263
281
  if (!containsFunction(value)) {
264
282
  commitValue(region, value);
265
283
  return value instanceof DocumentFragment ? [...region.nodes] : value;
266
284
  }
267
285
  let latest;
286
+ if (ordered === true) linkRegion(region);
268
287
  useRenderEffect(typeof value === "function" ? value : () => value, (raw) => {
269
288
  latest = raw;
270
289
  if (containsFunction(raw)) {
@@ -319,7 +338,10 @@ function anchor(parent, before) {
319
338
  * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused
320
339
  * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a
321
340
  * snapshot of its children. Arrays are flattened, nested arrays included.
322
- * - Content goes before `anchorNode`, or at the end when it is null or omitted.
341
+ * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an
342
+ * anchor on one parent keep the order of the calls, whatever they show and however often a sibling
343
+ * region replaces its nodes: when a reactive region is created right where the previous one ends, the
344
+ * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).
323
345
  * - Arrays are reconciled in place: nodes that remain are never removed and re-added.
324
346
  * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.
325
347
  * - During `hydrate()`, a region that adopted server text is compared with its first commit: in
@@ -349,7 +371,7 @@ function anchor(parent, before) {
349
371
  */
350
372
  function insert(parent, value, anchorNode, initial) {
351
373
  const resolvedAnchor = anchorNode ?? null;
352
- return bindRegion(createRegion(parent, resolvedAnchor, initial === void 0 ? claims.current.takeRegion(parent, resolvedAnchor) : initial), value);
374
+ return bindRegion(createRegion(parent, resolvedAnchor, initial === void 0 ? claims.current.takeRegion(parent, resolvedAnchor) : initial), value, resolvedAnchor === null);
353
375
  }
354
376
  export { anchor, bindRegion, createRegion, insert, removeRegion };
355
377
 
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n readonly anchor: Node | null;\n marker: Node | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call: (fn: () => unknown) => unknown = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (typeof item === \"string\") parts.push(item);\n else if (typeof item === \"number\") parts.push(String(item));\n else if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(String(item));\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child, or its marker. */\nfunction endOf(region: Region, attached: readonly Node[]): Node | null {\n if (region.anchor !== null) return region.anchor;\n const last = attached.at(-1);\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached);\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, nodes));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = { parent, anchor: anchorNode, marker, nodes, texts: null };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() ?? [];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once.\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted.\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value);\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,qBAAqB;;AA0B3B,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,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,QAAQ;EACjC,SAAS;EACT,IAAI,iBAAiB,GAAG,GAAG;GACzB,MAAM,QAAQ,gBAAgB,aAAa,CAAC;GAC5C,sBACQ;IACJ,MAAM,MAAM;IACZ,MAAM,QAAQ,QAAQ,KAAK,MAAM,IAAI;IACrC,MAAM,MAAM;IACZ,OAAO;GACT,IACC,UAAU;IACT,OAAO,QAAQ,KAAK;GACtB,CACF;EACF,OACE,YAAY,QAAQ,GAAG;CAE3B,CAAC;CACD,OAAO;AACT;;;;;;AAOA,SAAgB,aAAa,QAAsB;CACjD,KAAK,MAAM,QAAQ,OAAO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,KAAK;AACjC"}
1
+ {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call: (fn: () => unknown) => unknown = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached.at(-1));\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes.\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() ?? [];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;AAkBA,MAAM,qBAAqB;;AA+B3B,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,IAAI,IAAI,CAAC,OAAO,IAAI,CAAC;AAC/D;;AAGA,SAAS,WAAW,QAAgB,MAA6B;CAC/D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM;CACpB,IAAI,iBAAiB,KAAK;EACxB,MAAM,OAAO,IAAI,IAAU,IAAI;EAC/B,KAAK,MAAM,QAAQ,OACjB,IAAI,CAAC,KAAK,IAAI,IAAI,GAAG,MAAM,OAAO,IAAI;CAE1C,OAAO,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG,OAAO,QAAQ;AACnD;;;;;AAMA,SAAS,QAAQ,MAAe,QAAwC,OAAO,GAAG,GAAW;CAC3F,MAAM,QAAgB,CAAC;CACvB,MAAM,SAAsB,CAAC,CAAC,IAAI,CAAC;CACnC,MAAM,UAAoB,CAAC,CAAC;CAC5B,MAAM,yBAAS,IAAI,IAAe;CAClC,OAAO,OAAO,SAAS,GAAG;EACxB,MAAM,MAAM,OAAO,SAAS;EAC5B,MAAM,QAAQ,OAAO;EACrB,MAAM,SAAS,QAAQ,QAAQ;EAC/B,IAAI,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,aAAa,QAAsB;CACjD,KAAK,MAAM,QAAQ,OAAO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
@@ -211,6 +211,21 @@ function checkClaimedText(claimed, parts) {
211
211
  console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);
212
212
  devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, void 0, void 0);
213
213
  }
214
+ /** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */
215
+ const TEXT_ONLY = /* @__PURE__ */ new Set([
216
+ "script",
217
+ "style",
218
+ "title",
219
+ "textarea"
220
+ ]);
221
+ /**
222
+ * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no
223
+ * parent, so the server writes the children of such a tag without region markers even where the page parses it as
224
+ * an SVG `title` or `style`. Its whole content is then the one region.
225
+ */
226
+ function isTextOnly(node) {
227
+ return node.nodeType === 1 && TEXT_ONLY.has(node.localName);
228
+ }
214
229
  /**
215
230
  * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes
216
231
  * that sat between the region's markers are put back before `anchorNode` and returned, so a custom
@@ -219,7 +234,8 @@ function checkClaimedText(claimed, parts) {
219
234
  * @param parent An element returned by {@link claimElement} (or one of its descendants).
220
235
  * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.
221
236
  * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region
222
- * left to adopt (the caller then inserts fresh nodes).
237
+ * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no
238
+ * markers (the server writes its text as the parser reads it): its current children are the region.
223
239
  * @example
224
240
  * import { takeRegion } from "@shadow-js/web/extend";
225
241
  *
@@ -237,7 +253,7 @@ function takeRegion(parent, anchorNode) {
237
253
  const current = state;
238
254
  if (current === null) return void 0;
239
255
  const content = current.pending.get(parent)?.shift();
240
- if (content === void 0) return void 0;
256
+ if (content === void 0) return isTextOnly(parent) ? Array.from(parent.childNodes) : void 0;
241
257
  for (const node of content) parent.insertBefore(node, anchorNode);
242
258
  return content;
243
259
  }
@@ -1 +1 @@
1
- {"version":3,"file":"claim.js","names":[],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop();\n if (parent === undefined) break;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `&lt;` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes).\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":";;AAcA,IAAI,QAA+B;;AAGnC,SAAgB,cACd,UACA,aACM;CACN,QAAQ;EAAE;EAAU;EAAa,yBAAS,IAAI,QAAQ;EAAG,QAAQ,CAAC;CAAE;AACtE;;AAGA,SAAgB,cAAoB;CAClC,QAAQ;AACV;;;;;;;;;;;;;;;;;AAkBA,SAAgB,aAAsB;CACpC,OAAO,UAAU;AACnB;AAEA,SAAS,SAAS,MAAY,MAAuB;CACnD,IAAI,KAAK,aAAa,GAAG,OAAO;CAChC,MAAM,OAAQ,KAAiB;CAE/B,OAAO,SAAS,QAAS,SAAS,OAAO,KAAK,WAAW,KAAK;AAChE;;;;;;;AAQA,SAAS,QAAQ,MAAe,SAAkC,QAAwB;CACxF,MAAM,QAAmB,CAAC,IAAI;CAC9B,OAAO,MAAM,SAAS,GAAG;EACvB,MAAM,SAAS,MAAM,IAAI;EACzB,IAAI,WAAW,KAAA,GAAW;EAC1B,IAAI,QAA0B,OAAO;EACrC,OAAO,UAAU,MAAM;GACrB,MAAM,YAA8B,MAAM;GAC1C,IAAI,SAAS,OAAO,GAAG,GAAG;IACxB,MAAM,UAAkB,CAAC;IACzB,IAAI,QAAQ;IACZ,IAAI,SAA2B,MAAM;IACrC,OAAO,WAAW,MAAM;KACtB,IAAI,SAAS,QAAQ,GAAG,GAAG,SAAS;UAC/B,IAAI,SAAS,QAAQ,GAAG,GAAG;MAC9B,SAAS;MACT,IAAI,UAAU,GAAG;KACnB;KACA,QAAQ,KAAK,MAAM;KACnB,SAAS,OAAO;IAClB;IACA,MAAM,QAA0B,WAAW,OAAO,OAAO,OAAO;IAChE,OAAO,KAAK,OAAO;IACnB,KAAK,MAAM,QAAQ,SAAS,OAAO,YAAY,IAAI;IACnD,OAAO,YAAY,KAAK;IACxB,IAAI,WAAW,MAAM,OAAO,YAAY,MAAM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\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop();\n if (parent === undefined) break;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `&lt;` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/** HTML elements whose content is text and nothing else: no comment can mark a region inside them. */\nconst TEXT_ONLY = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for a `script`, `style`, `title` or `textarea`, in whichever namespace the parser put it: `Dynamic` knows no\n * parent, so the server writes the children of such a tag without region markers even where the page parses it as\n * an SVG `title` or `style`. Its whole content is then the one region.\n */\nfunction isTextOnly(node: Node): boolean {\n return node.nodeType === 1 && TEXT_ONLY.has((node as Element).localName);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes). A `script`, `style`, `title` or `textarea` has no\n * markers (the server writes its text as the parser reads it): its current children are the region.\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return isTextOnly(parent) ? Array.from(parent.childNodes) : undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":";;AAcA,IAAI,QAA+B;;AAGnC,SAAgB,cACd,UACA,aACM;CACN,QAAQ;EAAE;EAAU;EAAa,yBAAS,IAAI,QAAQ;EAAG,QAAQ,CAAC;CAAE;AACtE;;AAGA,SAAgB,cAA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/C,KAAK,MAAM,QAAQ,SAAS;EAC1B,IAAI,KAAK,aAAa,GAAG;EACzB,MAAM,UAAU;EAChB,MAAM,MAAM,QAAQ,aAAa,SAAS;EAC1C,IAAI,QAAQ,MAAM,QAAQ,SAAS,IAAI,KAAK,OAAO;EACnD,KAAK,MAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB,WAAW,CAAC,GAAG;GACrE,MAAM,KAAK,MAAM,aAAa,SAAS;GACvC,IAAI,OAAO,MAAM,QAAQ,SAAS,IAAI,IAAI,KAAK;EACjD;CACF;CACA,OAAO;AACT;;;;;;;AAQA,SAAgB,wBAAwB,MAAkB;CACxD,MAAM,QAAQ,MAAM,KAAK,KAAK,UAAU;CACxC,KAAK,IAAI,OAAO,GAAG,OAAO,MAAM,QAAQ,QAAQ,GAAG;EACjD,MAAM,UAAU,MAAM;EACtB,IAAI,YAAY,KAAA,KAAa,QAAQ,aAAa,GAAG;EACrD,MAAM,OAAQ,QAAoB;EAClC,IAAI,CAAC,KAAK,WAAW,WAAW,GAAG;EACnC,MAAM,QAAQ,MAAM,WACjB,MAAM,UACL,QAAQ,QAAQ,UAAU,MAAM,eAAe,KAAK,MAAM,CAAkB,CAAC,CACjF;EACA,MAAM,OAAO,UAAU,KAAK,OAAO;EACnC,KAAK,MAAM,QAAQ,MAAM,MAAM,MAAM,OAAO,CAAC,GAC3C,IAAI,KAAK,eAAe,MAAM,KAAK,YAAY,IAAI;EAErD,OAAO;CACT;AACF;AAEA,SAAS,UAAU,MAAY,MAAuB;CACpD,OAAO,KAAK,aAAa,KAAM,KAAiB,SAAS;AAC3D;AAEA,SAAS,eAAe,SAA2B;CACjD,OAAO,QAAQ,SAAS,OAAO,QAAQ,SAAS;AAClD"}
@@ -1,4 +1,5 @@
1
1
  // src/internal/diagnostics.ts
2
+ /** The codes reported, and the `code:key` pairs of the warnings that pass a key. */
2
3
  const seen = /* @__PURE__ */ new Set();
3
4
  /**
4
5
  * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the
@@ -7,6 +8,8 @@ const seen = /* @__PURE__ */ new Set();
7
8
  *
8
9
  * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.
9
10
  * @param detail The text after the code.
11
+ * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a
12
+ * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.
10
13
  * @example
11
14
  * import { isUnsafeUrlAttribute, warnOnce } from "@shadow-js/web/extend";
12
15
  *
@@ -19,12 +22,19 @@ const seen = /* @__PURE__ */ new Set();
19
22
  * }
20
23
  * @since 1.0.0
21
24
  */
22
- function warnOnce(code, detail) {
23
- if (seen.has(code)) return;
24
- seen.add(code);
25
+ function warnOnce(code, detail, key) {
26
+ const id = key === void 0 ? code : `${code}:${key}`;
27
+ if (seen.has(id)) return;
28
+ seen.add(id);
25
29
  console.warn(`[shadow ${code}] ${detail}`);
26
30
  }
27
31
  /**
32
+ * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML
33
+ * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.
34
+ * @internal
35
+ */
36
+ const SRCDOC_DYNAMIC_DETAIL = "A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.";
37
+ /**
28
38
  * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;
29
39
  * production keeps the code and the name (the same split as core's messages).
30
40
  * @internal
@@ -32,6 +42,6 @@ function warnOnce(code, detail) {
32
42
  function invalidAttributeName(name) {
33
43
  return /* @__PURE__ */ new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] "${name}" is not a valid attribute name.`);
34
44
  }
35
- export { invalidAttributeName, warnOnce };
45
+ export { SRCDOC_DYNAMIC_DETAIL, invalidAttributeName, warnOnce };
36
46
 
37
47
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":[],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\";\n\nconst seen = new Set<WebWarningCode>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":";AAWA,MAAM,uBAAO,IAAI,IAAoB;;;;;;;;;;;;;;;;;;;;AAqBrC,SAAgB,SAAS,MAAsB,QAAsB;CAEnE,IAAI,KAAK,IAAI,IAAI,GAAG;CACpB,KAAK,IAAI,IAAI;CACb,QAAQ,KAAK,WAAW,KAAK,IAAI,QAAQ;AAC3C;;;;;;AAYA,SAAgB,qBAAqB,MAAyB;CAE5D,uBAAO,IAAI,UAAU,oCAAoC,KAAK,iCAAiC;AACjG"}
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one)\n * `SRCDOC_DYNAMIC` (a value computed at run time was written to `srcdoc`, an HTML sink) and\n * `DYNAMIC_SVG_CASE` (`Dynamic` was given an SVG element name in a case SVG does not spell it in).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\"\n | \"SRCDOC_DYNAMIC\"\n | \"DYNAMIC_SVG_CASE\";\n\n/** The codes reported, and the `code:key` pairs of the warnings that pass a key. */\nconst seen = new Set<string>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @param key Optional. With a key the warning is once per `code` and `key` instead of once per code, for a\n * warning about a name where each name deserves a report. Pass a bounded set of keys: each is remembered.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string, key?: string): void {\n if (!__DEV__) return;\n const id = key === undefined ? code : `${code}:${key}`;\n if (seen.has(id)) return;\n seen.add(id);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/**\n * The text of the `SRCDOC_DYNAMIC` warning, shared by the client and the server writer. `srcdoc` is a whole HTML\n * document the frame runs, so it has the trust of `innerHTML`, not of a URL: no scheme check applies to it.\n * @internal\n */\nexport const SRCDOC_DYNAMIC_DETAIL =\n 'A computed value was written to \"srcdoc\". It is an HTML document the frame runs, with the trust of innerHTML: sanitize it, and add the sandbox attribute to the frame.';\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":";;AAgBA,MAAM,uBAAO,IAAI,IAAY;;;;;;;;;;;;;;;;;;;;;;AAuB7B,SAAgB,SAAS,MAAsB,QAAgB,KAAoB;CAEjF,MAAM,KAAK,QAAQ,KAAA,IAAY,OAAO,GAAG,KAAK,GAAG;CACjD,IAAI,KAAK,IAAI,EAAE,GAAG;CAClB,KAAK,IAAI,EAAE;CACX,QAAQ,KAAK,WAAW,KAAK,IAAI,QAAQ;AAC3C;;;;;;AAOA,MAAa,wBACX;;;;;;AAYF,SAAgB,qBAAqB,MAAyB;CAE5D,uBAAO,IAAI,UAAU,oCAAoC,KAAK,iCAAiC;AACjG"}
@@ -19,7 +19,7 @@ const EVENT_NAME = /^[a-z]+$/;
19
19
  * @internal
20
20
  */
21
21
  function captureScriptBody(names) {
22
- return "(function(){var d=document,n=" + JSON.stringify(names.filter((name) => EVENT_NAME.test(name))) + `,q=[];function c(e){q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`;
22
+ return "(function(){var d=document,n=" + JSON.stringify(names.filter((name) => EVENT_NAME.test(name))) + `,q=[];function c(e){if(q.length<100)q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`;
23
23
  }
24
24
  /** The capture the script left on the window, validated, or undefined. */
25
25
  function readCapture() {
@@ -67,9 +67,27 @@ function replayEarlyEvents() {
67
67
  for (const name of capture.names) document.removeEventListener(name, capture.listener, true);
68
68
  for (const event of capture.queue) {
69
69
  const target = event.target;
70
- if (target instanceof Node) target.dispatchEvent(reissue(event));
70
+ if (target instanceof Node) target.dispatchEvent(withoutDefaultAction(reissue(event)));
71
71
  }
72
72
  }
73
+ /**
74
+ * The replayed event runs the page's handlers, not the browser's default action: the real event
75
+ * already ran it when the user made it. A dispatched `click` on a link follows the link, so without
76
+ * this a link was followed twice. The native flag is set right away, which cancels the default action,
77
+ * and the handlers still see `defaultPrevented` as false (a router skips a click that is already
78
+ * prevented) until one of them prevents it itself.
79
+ */
80
+ function withoutDefaultAction(event) {
81
+ event.preventDefault();
82
+ let prevented = false;
83
+ Object.defineProperties(event, {
84
+ defaultPrevented: { get: () => prevented },
85
+ preventDefault: { value: () => {
86
+ prevented = true;
87
+ } }
88
+ });
89
+ return event;
90
+ }
73
91
  export { DEFAULT_EARLY_EVENTS, EARLY_CAPTURE_KEY, captureScriptBody, replayEarlyEvents };
74
92
 
75
93
  //# sourceMappingURL=early-events.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"early-events.js","names":[],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n \",q=[];function c(e){q.push(e)}\" +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(reissue(event));\n }\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,uBAA0C,CAAC,SAAS,OAAO;;AAGxE,MAAa,oBAAoB;;AAGjC,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,OAAkC;CAElE,OACE,kCAFW,KAAK,UAAU,MAAM,QAAQ,SAAS,WAAW,KAAK,IAAI,CAAC,CAGnE,IACH,mGAEU,kBAAkB;AAEhC;;AASA,SAAS,cAAmC;CAC1C,MAAM,QAAiB,QAAQ,IAAI,YAAY,iBAAiB;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,QAAiB,QAAQ,IAAI,OAAO,OAAO;CACjD,MAAM,QAAiB,QAAQ,IAAI,OAAO,OAAO;CACjD,MAAM,WAAoB,QAAQ,IAAI,OAAO,UAAU;CACvD,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,QAAQ,KAAK,KAAK,OAAO,aAAa,YACxE;CAIF,OAAO;EAAE,OAFM,MAAM,QAAQ,SAAwB,gBAAgB,KAEhD;EAAG,OADV,MAAM,QAAQ,SAAyB,OAAO,SAAS,QAClC;EAAa;CAAmC;AACrF;;AAGA,SAAS,QAAQ,OAAqB;CACpC,MAAM,OAAkB;EAAE,SAAS;EAAM,YAAY,MAAM;EAAY,UAAU;CAAK;CACtF,IAAI,iBAAiB,YACnB,OAAO,IAAI,WAAW,MAAM,MAAM;EAChC,GAAG;EACH,SAAS,MAAM;EACf,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,SAAS,MAAM;EACf,UAAU,MAAM;CAClB,CAAC;CAEH,OAAO,IAAI,MAAM,MAAM,MAAM,IAAI;AACnC;;;;;;AAOA,SAAgB,oBAA0B;CACxC,MAAM,UAAU,YAAY;CAC5B,IAAI,YAAY,KAAA,GAAW;CAC3B,QAAQ,eAAe,YAAY,iBAAiB;CACpD,KAAK,MAAM,QAAQ,QAAQ,OAAO,SAAS,oBAAoB,MAAM,QAAQ,UAAU,IAAI;CAC3F,KAAK,MAAM,SAAS,QAAQ,OAAO;EACjC,MAAM,SAAS,MAAM;EACrB,IAAI,kBAAkB,MAAM,OAAO,cAAc,QAAQ,KAAK,CAAC;CACjE;AACF"}
1
+ {"version":3,"file":"early-events.js","names":[],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/**\n * The most events the capture script keeps. A page whose bundle never loads would otherwise hold every\n * click and keystroke of the visit; the first ones are the ones worth replaying. @internal\n */\nexport const MAX_EARLY_EVENTS = 100;\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n `,q=[];function c(e){if(q.length<${MAX_EARLY_EVENTS})q.push(e)}` +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(withoutDefaultAction(reissue(event)));\n }\n}\n\n/**\n * The replayed event runs the page's handlers, not the browser's default action: the real event\n * already ran it when the user made it. A dispatched `click` on a link follows the link, so without\n * this a link was followed twice. The native flag is set right away, which cancels the default action,\n * and the handlers still see `defaultPrevented` as false (a router skips a click that is already\n * prevented) until one of them prevents it itself.\n */\nfunction withoutDefaultAction(event: Event): Event {\n event.preventDefault();\n let prevented = false;\n Object.defineProperties(event, {\n defaultPrevented: { get: () => prevented },\n preventDefault: {\n value: () => {\n prevented = true;\n },\n },\n });\n return event;\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,uBAA0C,CAAC,SAAS,OAAO;;AAGxE,MAAa,oBAAoB;;AASjC,MAAM,aAAa;;;;;;;AAQnB,SAAgB,kBAAkB,OAAkC;CAElE,OACE,kCAFW,KAAK,UAAU,MAAM,QAAQ,SAAS,WAAW,KAAK,IAAI,CAAC,CAGnE,IACH,mHAEU,kBAAkB;AAEhC;;AASA,SAAS,cAAmC;CAC1C,MAAM,QAAiB,QAAQ,IAAI,YAAY,iBAAiB;CAChE,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO,KAAA;CACxD,MAAM,QAAiB,QAAQ,IAAI,OAAO,OAAO;CACjD,MAAM,QAAiB,QAAQ,IAAI,OAAO,OAAO;CACjD,MAAM,WAAoB,QAAQ,IAAI,OAAO,UAAU;CACvD,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,QAAQ,KAAK,KAAK,OAAO,aAAa,YACxE;CAIF,OAAO;EAAE,OAFM,MAAM,QAAQ,SAAwB,gBAAgB,KAEhD;EAAG,OADV,MAAM,QAAQ,SAAy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