@shadow-js/web 1.1.0 → 1.1.1

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 (222) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/dev/attributes.d.ts +1 -2
  4. package/dist/dev/autofocus.d.ts +1 -2
  5. package/dist/dev/class-style.d.ts +1 -2
  6. package/dist/dev/component.d.ts +1 -2
  7. package/dist/dev/control-flow/activity.d.ts +1 -2
  8. package/dist/dev/control-flow/client-only.d.ts +1 -2
  9. package/dist/dev/control-flow/dynamic.d.ts +1 -2
  10. package/dist/dev/control-flow/error-boundary.d.ts +1 -2
  11. package/dist/dev/control-flow/for.d.ts +1 -2
  12. package/dist/dev/control-flow/fragment.d.ts +1 -2
  13. package/dist/dev/control-flow/index-list.d.ts +1 -2
  14. package/dist/dev/control-flow/lazy.d.ts +1 -2
  15. package/dist/dev/control-flow/no-hydration.d.ts +1 -2
  16. package/dist/dev/control-flow/portal.d.ts +1 -2
  17. package/dist/dev/control-flow/portal.js.map +1 -1
  18. package/dist/dev/control-flow/root-errors.d.ts +2 -3
  19. package/dist/dev/control-flow/show.d.ts +1 -2
  20. package/dist/dev/control-flow/suspense-list.d.ts +2 -3
  21. package/dist/dev/control-flow/suspense.d.ts +1 -2
  22. package/dist/dev/control-flow/switch.d.ts +1 -2
  23. package/dist/dev/derived.d.ts +1 -2
  24. package/dist/dev/element.d.ts +1 -2
  25. package/dist/dev/events.d.ts +1 -2
  26. package/dist/dev/extend.d.ts +9 -0
  27. package/dist/dev/head/components.d.ts +1 -2
  28. package/dist/dev/head/server-head.d.ts +2 -3
  29. package/dist/dev/head/use-head.d.ts +1 -2
  30. package/dist/dev/head/validate.d.ts +1 -2
  31. package/dist/dev/hmr.d.ts +1 -2
  32. package/dist/dev/hmr.js.map +1 -1
  33. package/dist/dev/hydration.d.ts +1 -2
  34. package/dist/dev/insert.d.ts +1 -2
  35. package/dist/dev/insert.js.map +1 -1
  36. package/dist/dev/internal/claim.d.ts +1 -2
  37. package/dist/dev/internal/diagnostics.d.ts +1 -2
  38. package/dist/dev/internal/hydration-hooks.d.ts +1 -2
  39. package/dist/dev/internal/hydration-scope.d.ts +1 -2
  40. package/dist/dev/internal/names.d.ts +1 -2
  41. package/dist/dev/internal/portal-context.d.ts +1 -2
  42. package/dist/dev/internal/reconcile.d.ts +1 -2
  43. package/dist/dev/internal/reconcile.js.map +1 -1
  44. package/dist/dev/internal/stream-context.d.ts +1 -2
  45. package/dist/dev/jsx/aria.d.ts +7 -2
  46. package/dist/dev/jsx/component.d.ts +7 -2
  47. package/dist/dev/jsx/events.d.ts +1 -2
  48. package/dist/dev/jsx/global.d.ts +11 -2
  49. package/dist/dev/jsx/html.d.ts +8 -2
  50. package/dist/dev/jsx/intrinsic.d.ts +10 -2
  51. package/dist/dev/jsx/mathml.d.ts +8 -2
  52. package/dist/dev/jsx/svg.d.ts +13 -2
  53. package/dist/dev/jsx/types.d.ts +1 -2
  54. package/dist/dev/jsx-dev-runtime.d.ts +6 -0
  55. package/dist/dev/jsx-runtime.d.ts +13 -2
  56. package/dist/dev/reactive.d.ts +1 -2
  57. package/dist/dev/render.d.ts +1 -2
  58. package/dist/dev/resource-hints.d.ts +1 -2
  59. package/dist/dev/select-value.d.ts +1 -2
  60. package/dist/dev/server/attributes.d.ts +1 -2
  61. package/dist/dev/server/class-style.d.ts +1 -2
  62. package/dist/dev/server/component.d.ts +1 -2
  63. package/dist/dev/server/derived.d.ts +1 -2
  64. package/dist/dev/server/element.d.ts +1 -2
  65. package/dist/dev/server/errors.js.map +1 -1
  66. package/dist/dev/server/escape.d.ts +1 -2
  67. package/dist/dev/server/form-controls.d.ts +1 -2
  68. package/dist/dev/server/hydration-script.d.ts +1 -2
  69. package/dist/dev/server/index.d.ts +7 -2
  70. package/dist/dev/server/index.js +2 -2
  71. package/dist/dev/server/node.d.ts +1 -2
  72. package/dist/dev/server/node.js.map +1 -1
  73. package/dist/dev/server/portals.d.ts +1 -2
  74. package/dist/dev/server/portals.js.map +1 -1
  75. package/dist/dev/server/raw-text.d.ts +1 -2
  76. package/dist/dev/server/render.d.ts +1 -2
  77. package/dist/dev/server/serialize.d.ts +1 -2
  78. package/dist/dev/server/stream.d.ts +1 -2
  79. package/dist/dev/server/stream.js.map +1 -1
  80. package/dist/dev/server.d.ts +1 -0
  81. package/dist/dev/spread.d.ts +1 -2
  82. package/dist/dev/template.d.ts +1 -2
  83. package/dist/dev/view-transition.d.ts +1 -2
  84. package/dist/prod/attributes.js.map +1 -1
  85. package/dist/prod/autofocus.js.map +1 -1
  86. package/dist/prod/class-style.js.map +1 -1
  87. package/dist/prod/component.js.map +1 -1
  88. package/dist/prod/control-flow/activity.js.map +1 -1
  89. package/dist/prod/control-flow/branch.js.map +1 -1
  90. package/dist/prod/control-flow/client-only.js.map +1 -1
  91. package/dist/prod/control-flow/dynamic.js.map +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/for.js.map +1 -1
  94. package/dist/prod/control-flow/fragment.js.map +1 -1
  95. package/dist/prod/control-flow/hot-link.js.map +1 -1
  96. package/dist/prod/control-flow/index-list.js.map +1 -1
  97. package/dist/prod/control-flow/lazy.js.map +1 -1
  98. package/dist/prod/control-flow/no-hydration.js.map +1 -1
  99. package/dist/prod/control-flow/portal.js.map +1 -1
  100. package/dist/prod/control-flow/root-errors.js.map +1 -1
  101. package/dist/prod/control-flow/show.js.map +1 -1
  102. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  103. package/dist/prod/control-flow/suspense.js.map +1 -1
  104. package/dist/prod/control-flow/switch.js.map +1 -1
  105. package/dist/prod/derived.js.map +1 -1
  106. package/dist/prod/element.js.map +1 -1
  107. package/dist/prod/events.js.map +1 -1
  108. package/dist/prod/head/components.js.map +1 -1
  109. package/dist/prod/head/registry.js.map +1 -1
  110. package/dist/prod/head/server-head.js.map +1 -1
  111. package/dist/prod/head/sink.js.map +1 -1
  112. package/dist/prod/head/use-head.js.map +1 -1
  113. package/dist/prod/head/validate.js.map +1 -1
  114. package/dist/prod/hmr.js.map +1 -1
  115. package/dist/prod/hydration.js.map +1 -1
  116. package/dist/prod/insert.js.map +1 -1
  117. package/dist/prod/internal/accessor.js.map +1 -1
  118. package/dist/prod/internal/claim.js.map +1 -1
  119. package/dist/prod/internal/css-units.js.map +1 -1
  120. package/dist/prod/internal/diagnostics.js.map +1 -1
  121. package/dist/prod/internal/early-events.js.map +1 -1
  122. package/dist/prod/internal/hydration-hooks.js.map +1 -1
  123. package/dist/prod/internal/hydration-scope.js.map +1 -1
  124. package/dist/prod/internal/portal-context.js.map +1 -1
  125. package/dist/prod/internal/react-names.js.map +1 -1
  126. package/dist/prod/internal/reconcile.js.map +1 -1
  127. package/dist/prod/internal/stream-context.js.map +1 -1
  128. package/dist/prod/reactive.js.map +1 -1
  129. package/dist/prod/render.js.map +1 -1
  130. package/dist/prod/resource-hints.js.map +1 -1
  131. package/dist/prod/select-value.js.map +1 -1
  132. package/dist/prod/server/attributes.js.map +1 -1
  133. package/dist/prod/server/class-style.js.map +1 -1
  134. package/dist/prod/server/component.js.map +1 -1
  135. package/dist/prod/server/derived.js.map +1 -1
  136. package/dist/prod/server/element.js.map +1 -1
  137. package/dist/prod/server/errors.js.map +1 -1
  138. package/dist/prod/server/escape.js.map +1 -1
  139. package/dist/prod/server/form-controls.js.map +1 -1
  140. package/dist/prod/server/hydration-script.js.map +1 -1
  141. package/dist/prod/server/node.js.map +1 -1
  142. package/dist/prod/server/portals.js.map +1 -1
  143. package/dist/prod/server/raw-text.js.map +1 -1
  144. package/dist/prod/server/render.js.map +1 -1
  145. package/dist/prod/server/serialize.js.map +1 -1
  146. package/dist/prod/server/stream.js.map +1 -1
  147. package/dist/prod/spread.js.map +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js.map +1 -1
  150. package/dist/server/attributes.js.map +1 -1
  151. package/dist/server/autofocus.js.map +1 -1
  152. package/dist/server/class-style.js.map +1 -1
  153. package/dist/server/component.js.map +1 -1
  154. package/dist/server/control-flow/activity.js.map +1 -1
  155. package/dist/server/control-flow/branch.js.map +1 -1
  156. package/dist/server/control-flow/client-only.js.map +1 -1
  157. package/dist/server/control-flow/dynamic.js.map +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/for.js.map +1 -1
  160. package/dist/server/control-flow/fragment.js.map +1 -1
  161. package/dist/server/control-flow/index-list.js.map +1 -1
  162. package/dist/server/control-flow/lazy.js.map +1 -1
  163. package/dist/server/control-flow/no-hydration.js.map +1 -1
  164. package/dist/server/control-flow/portal.js.map +1 -1
  165. package/dist/server/control-flow/root-errors.js.map +1 -1
  166. package/dist/server/control-flow/show.js.map +1 -1
  167. package/dist/server/control-flow/suspense-list.js.map +1 -1
  168. package/dist/server/control-flow/suspense.js.map +1 -1
  169. package/dist/server/control-flow/switch.js.map +1 -1
  170. package/dist/server/derived.js.map +1 -1
  171. package/dist/server/element.js.map +1 -1
  172. package/dist/server/events.js.map +1 -1
  173. package/dist/server/head/components.js.map +1 -1
  174. package/dist/server/head/registry.js.map +1 -1
  175. package/dist/server/head/server-head.js.map +1 -1
  176. package/dist/server/head/sink.js.map +1 -1
  177. package/dist/server/head/use-head.js.map +1 -1
  178. package/dist/server/head/validate.js.map +1 -1
  179. package/dist/server/hydration.js.map +1 -1
  180. package/dist/server/insert.js.map +1 -1
  181. package/dist/server/internal/accessor.js.map +1 -1
  182. package/dist/server/internal/claim.js.map +1 -1
  183. package/dist/server/internal/css-units.js.map +1 -1
  184. package/dist/server/internal/diagnostics.js.map +1 -1
  185. package/dist/server/internal/early-events.js.map +1 -1
  186. package/dist/server/internal/hydration-hooks.js.map +1 -1
  187. package/dist/server/internal/hydration-scope.js.map +1 -1
  188. package/dist/server/internal/portal-context.js.map +1 -1
  189. package/dist/server/internal/react-names.js.map +1 -1
  190. package/dist/server/internal/reconcile.js.map +1 -1
  191. package/dist/server/internal/stream-context.js.map +1 -1
  192. package/dist/server/reactive.js.map +1 -1
  193. package/dist/server/render.js.map +1 -1
  194. package/dist/server/resource-hints.js.map +1 -1
  195. package/dist/server/select-value.js.map +1 -1
  196. package/dist/server/server/attributes.js.map +1 -1
  197. package/dist/server/server/class-style.js.map +1 -1
  198. package/dist/server/server/component.js.map +1 -1
  199. package/dist/server/server/derived.js.map +1 -1
  200. package/dist/server/server/element.js.map +1 -1
  201. package/dist/server/server/errors.js.map +1 -1
  202. package/dist/server/server/escape.js.map +1 -1
  203. package/dist/server/server/form-controls.js.map +1 -1
  204. package/dist/server/server/hydration-script.js.map +1 -1
  205. package/dist/server/server/node.js.map +1 -1
  206. package/dist/server/server/portals.js.map +1 -1
  207. package/dist/server/server/raw-text.js.map +1 -1
  208. package/dist/server/server/render.js.map +1 -1
  209. package/dist/server/server/serialize.js.map +1 -1
  210. package/dist/server/server/stream.js.map +1 -1
  211. package/dist/server/spread.js.map +1 -1
  212. package/dist/server/template.js.map +1 -1
  213. package/dist/server/view-transition.js.map +1 -1
  214. package/dist/server-dev/control-flow/portal.js.map +1 -1
  215. package/dist/server-dev/insert.js.map +1 -1
  216. package/dist/server-dev/internal/reconcile.js.map +1 -1
  217. package/dist/server-dev/server/errors.js.map +1 -1
  218. package/dist/server-dev/server/index.js +2 -2
  219. package/dist/server-dev/server/node.js.map +1 -1
  220. package/dist/server-dev/server/portals.js.map +1 -1
  221. package/dist/server-dev/server/stream.js.map +1 -1
  222. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"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() as Element;\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":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU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IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUlC,EAAM6B,EAAe3B,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMyC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMnC,KAAQgC,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvC3C,EAAK,aAAe+B,GAAMA,EAAK,YAAY/B,CAAI,EAErD,EAAO2C,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOlC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASmC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
1
+ {"version":3,"file":"claim.js","names":["state","beginClaiming","registry","recoverable","endClaiming","isClaiming","isMarker","node","data","text","prepare","root","pending","lifted","stack","parent","child","following","content","depth","cursor","after","queue","claimElement","key","current","element","TEXT_ONLY","isTextOnly","takeRegion","anchorNode","liftedRegions","withoutClaiming","fn","saved","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"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() as Element;\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":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACdC,EACAC,EACM,CACNH,EAAQ,CAAEE,WAAUC,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClCJ,EAAQ,IACV,CAkBA,SAAgBK,GAAsB,CACpC,OAAOL,IAAU,IACnB,CAEA,SAASM,EAASC,EAAYC,EAAuB,CACnD,GAAID,EAAK,WAAa,EAAG,MAAO,GAChC,IAAME,EAAQF,EAAiB,KAE/B,OAAOE,IAASD,GAASA,IAAS,KAAOC,EAAK,WAAW,KAAK,CAChE,CAQA,SAASC,EAAQC,EAAeC,EAAkCC,EAAwB,CACxF,IAAMC,EAAmB,CAACH,CAAI,EAC9B,KAAOG,EAAM,OAAS,GAAG,CACvB,IAAMC,EAASD,EAAM,IAAI,EACrBE,EAA0BD,EAAO,WACrC,KAAOC,IAAU,MAA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}
@@ -1 +1 @@
1
- {"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","value","property","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":"AAQA,MAAMA,EACJ,oaASF,SAAgBC,EAAa,EAAkB,EAAwB,CACrE,GAAI,OAAOC,GAAU,UAAYA,IAAU,GAAKC,EAAS,WAAW,IAAI,EAAG,OAAO,OAAOD,CAAK,EAC9F,IAAME,EAAOD,EAAS,QAAQ,yBAA0B,EAAE,EAC1D,OAAOH,EAAS,KAAKI,CAAI,EAAI,OAAOF,CAAK,EAAI,GAAGA,EAAM,GACxD,C"}
1
+ {"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","property","value","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS =\n /^(?:animation-iteration-count|aspect-ratio|border-image-(?:outset|slice|width)|box-(?:flex(?:-group)?|ordinal-group)|column-count|columns|flex(?:-(?:grow|positive|shrink|negative|order))?|grid-(?:area|(?:row|column)(?:-(?:end|span|start))?)|font-weight|line-(?:clamp|height)|opacity|order|orphans|scale|tab-size|widows|z-index|zoom|(?:fill|flood|stop|stroke)-opacity|stroke-(?:dasharray|dashoffset|miterlimit|width))$/;\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.test(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":"AAQA,MAAMA,EACJ,oaASF,SAAgBC,EAAaC,EAAkBC,EAAwB,CACrE,GAAI,OAAOA,GAAU,UAAYA,IAAU,GAAKD,EAAS,WAAW,IAAI,EAAG,OAAO,OAAOC,CAAK,EAC9F,IAAMC,EAAOF,EAAS,QAAQ,yBAA0B,EAAE,EAC1D,OAAOF,EAAS,KAAKI,CAAI,EAAI,OAAOD,CAAK,EAAI,GAAGA,EAAM,GACxD,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"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":"AAuCA,SAAgBA,EAAS,EAAsB,EAAgB,EAAoB,CAMnF,CAoBA,SAAgBC,EAAqB,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCC,EAAK,EAAE,CAE/E,C"}
1
+ {"version":3,"file":"diagnostics.js","names":["warnOnce","code","detail","key","invalidAttributeName","name"],"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":"AAuCA,SAAgBA,EAASC,EAAsBC,EAAgBC,EAAoB,CAMnF,CAoBA,SAAgBC,EAAqBC,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCA,EAAK,EAAE,CAE/E,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target","withoutDefaultAction","prevented"],"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":"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AAQ,MAAO,CACjC,IAAMC,EAASH,EAAM,OACjBG,aAAkB,MAAMA,EAAO,cAAcC,EAAqBN,EAAQE,CAAK,CAAC,CAAC,CACvF,CALoD,CAMtD,CASA,SAASI,EAAqB,EAAqB,CACjDJ,EAAM,eAAe,EACrB,IAAIK,EAAY,GAShB,OARA,OAAO,iBAAiBL,EAAO,CAC7B,iBAAkB,CAAE,QAAWK,CAAU,EACzC,eAAgB,CACd,UAAa,CACX,EAAY,EACd,CACF,CACF,CAAC,EACML,CACT,C"}
1
+ {"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","event","init","replayEarlyEvents","capture","target","withoutDefaultAction","prevented"],"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,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAS3BC,EAAa,WAQnB,SAAgBC,EAAkBC,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUA,EAAM,OAAQC,GAASH,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mHAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQE,GAAwBA,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQC,GAAyB,OAAOA,GAAS,QAClC,EAAaI,UAAmC,CACrF,CAGA,SAASE,EAAQC,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYD,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGC,EACH,QAASD,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMC,CAAI,CACnC,CAOA,SAAgBC,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMH,KAASG,EAAQ,MAAO,CACjC,IAAMC,EAASJ,EAAM,OACjBI,aAAkB,MAAMA,EAAO,cAAcC,EAAqBN,EAAQC,CAAK,CAAC,CAAC,CACvF,CALoD,CAMtD,CASA,SAASK,EAAqBL,EAAqB,CACjDA,EAAM,eAAe,EACrB,IAAIM,EAAY,GAShB,OARA,OAAO,iBAAiBN,EAAO,CAC7B,iBAAkB,CAAE,QAAWM,CAAU,EACzC,eAAgB,CACd,UAAa,CACXA,EAAY,EACd,CACF,CACF,CAAC,EACMN,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-hooks.js","names":["claims","fn"],"sources":["../../../src/internal/hydration-hooks.ts"],"sourcesContent":["/**\n * The claiming half of hydration, as a hook. `hydrate()` installs the real implementation for the\n * length of its pass; outside a pass the hooks are idle: nothing is claimed, and the renderer builds\n * the same DOM it builds on a fresh page. Templates, regions, `Dynamic`, `Portal` and `NoHydration`\n * call through {@link claims}, so only code that reaches `hydrate()` carries the claiming code (the\n * registry, the server-block lifting and the portal scan). A custom renderer reads the same hook.\n * @since 1.0.0\n */\nexport interface Claims {\n /** Claims the server element for `key` (see `claimElement`). */\n claimElement(key: string | undefined): Element | null;\n /** Adopts the next server region of `parent` (see `takeRegion`). */\n takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined;\n /** The content of every region lifted out of a claimed element (see `liftedRegions`). */\n liftedRegions(): readonly (readonly Node[])[] | undefined;\n /** Adopts the server block of a portal (see `claimPortal`). */\n claimPortal(key: string | undefined): Node[] | undefined;\n /** True while a hydration pass claims server DOM (see `isClaiming`). */\n isClaiming(): boolean;\n /** Runs `fn` with claiming off (see `withoutClaiming`). */\n withoutClaiming<T>(fn: () => T): T;\n}\n\nconst idle: Claims = {\n claimElement: () => null,\n takeRegion: () => undefined,\n liftedRegions: () => undefined,\n claimPortal: () => undefined,\n isClaiming: () => false,\n withoutClaiming: (fn) => fn(),\n};\n\n/**\n * The claims in effect. Read at each call (never captured), so a region that is updated after its\n * hydration pass ended builds fresh DOM. Only `hydrate()` replaces it, and restores it in `finally`.\n * Outside a hydration pass every method is a no-op.\n *\n * @example\n * import { claims, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createCard(): Element {\n * // Adopts the server's element during hydrate(); builds a new one otherwise.\n * return claims.current.claimElement(nextKey()) ?? document.createElement(\"article\");\n * }\n * @see Claims\n * @since 1.0.0\n */\nexport const claims: { current: Claims } = { current: idle };\n"],"mappings":"AA+CA,MAAaA,EAA8B,CAAE,QAAS,CAvBpD,iBAAoB,KACpB,eAAkB,IAAA,GAClB,kBAAqB,IAAA,GACrB,gBAAmB,IAAA,GACnB,eAAkB,GAClB,gBAAkB,GAAOC,EAAG,CAkBwB,CAAK,E"}
1
+ {"version":3,"file":"hydration-hooks.js","names":["claims","fn"],"sources":["../../../src/internal/hydration-hooks.ts"],"sourcesContent":["/**\n * The claiming half of hydration, as a hook. `hydrate()` installs the real implementation for the\n * length of its pass; outside a pass the hooks are idle: nothing is claimed, and the renderer builds\n * the same DOM it builds on a fresh page. Templates, regions, `Dynamic`, `Portal` and `NoHydration`\n * call through {@link claims}, so only code that reaches `hydrate()` carries the claiming code (the\n * registry, the server-block lifting and the portal scan). A custom renderer reads the same hook.\n * @since 1.0.0\n */\nexport interface Claims {\n /** Claims the server element for `key` (see `claimElement`). */\n claimElement(key: string | undefined): Element | null;\n /** Adopts the next server region of `parent` (see `takeRegion`). */\n takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined;\n /** The content of every region lifted out of a claimed element (see `liftedRegions`). */\n liftedRegions(): readonly (readonly Node[])[] | undefined;\n /** Adopts the server block of a portal (see `claimPortal`). */\n claimPortal(key: string | undefined): Node[] | undefined;\n /** True while a hydration pass claims server DOM (see `isClaiming`). */\n isClaiming(): boolean;\n /** Runs `fn` with claiming off (see `withoutClaiming`). */\n withoutClaiming<T>(fn: () => T): T;\n}\n\nconst idle: Claims = {\n claimElement: () => null,\n takeRegion: () => undefined,\n liftedRegions: () => undefined,\n claimPortal: () => undefined,\n isClaiming: () => false,\n withoutClaiming: (fn) => fn(),\n};\n\n/**\n * The claims in effect. Read at each call (never captured), so a region that is updated after its\n * hydration pass ended builds fresh DOM. Only `hydrate()` replaces it, and restores it in `finally`.\n * Outside a hydration pass every method is a no-op.\n *\n * @example\n * import { claims, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createCard(): Element {\n * // Adopts the server's element during hydrate(); builds a new one otherwise.\n * return claims.current.claimElement(nextKey()) ?? document.createElement(\"article\");\n * }\n * @see Claims\n * @since 1.0.0\n */\nexport const claims: { current: Claims } = { current: idle };\n"],"mappings":"AA+CA,MAAaA,EAA8B,CAAE,QAAS,CAvBpD,iBAAoB,KACpB,eAAkB,IAAA,GAClB,kBAAqB,IAAA,GACrB,gBAAmB,IAAA,GACnB,eAAkB,GAClB,gBAAkBC,GAAOA,EAAG,CAkBwB,CAAK,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"hydration-scope.js","names":["current","createRootScope","renderId","currentScope","withScope","previous","scope","fn","enterComponent","parent","nextKey","resourceKey","explicit","childScope","key"],"sources":["../../../src/internal/hydration-scope.ts"],"sourcesContent":["/**\n * A hydration scope: the deterministic source of hydration keys shared by the server renderer and\n * the client hydrator. Keys depend only on the nesting and order of component calls, never on owners,\n * effects or memos, so server and client agree as long as they run the same components. Scopes are\n * created by {@link createRootScope}, {@link enterComponent} and {@link childScope}; treat their\n * fields as read-only.\n *\n * @since 1.0.0\n */\nexport interface HydrationScope {\n /** Prefix of every key allocated in this scope, ending with `-` (`\"0-\"` for a root, `\"0-3-\"` below). */\n readonly id: string;\n /** Next number handed out by this scope: component scopes and template root keys share it. */\n count: number;\n /** Number of auto-keyed resources created directly in this scope so far. */\n resources: number;\n}\n\nlet current: HydrationScope | null = null;\n\n/**\n * Creates the scope a render or a hydration starts from: what `renderToString` and `hydrate()` put in\n * effect around the app. A custom renderer that hands out hydration keys does the same.\n *\n * @param renderId The prefix of every key of this render. Default: `\"0\"`, the default `renderId` of\n * the renderers.\n * @returns A fresh scope whose `id` is `` `${renderId}-` ``.\n * @example\n * import { createRootScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * const keys = withScope(createRootScope(\"app\"), () => [nextKey(), nextKey()]);\n * // [\"app-0\", \"app-1\"]\n * @see withScope\n * @since 1.0.0\n */\nexport function createRootScope(renderId = \"0\"): HydrationScope {\n return { id: `${renderId}-`, count: 0, resources: 0 };\n}\n\n/**\n * Returns the hydration scope in effect.\n *\n * @returns The current scope; `null` outside a server render, a hydration, or a {@link withScope}\n * call.\n * @example\n * import { currentScope } from \"@shadow-js/web/extend\";\n *\n * function scopeLabel(): string {\n * return currentScope()?.id ?? \"no scope\";\n * }\n * @since 1.0.0\n */\nexport function currentScope(): HydrationScope | null {\n return current;\n}\n\n/**\n * Runs `fn` with `scope` in effect, so the keys `fn` draws come from it. The previous scope is\n * restored when `fn` returns or throws.\n *\n * @param scope The scope to put in effect; `null` runs `fn` with no scope (no keys are drawn).\n * @param fn The code to run, synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { childScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * // The keys of an isolated subtree, independent of its siblings.\n * const first = withScope(childScope(\"0-4\"), () => nextKey()); // \"0-4-0\"\n * @see createRootScope\n * @since 1.0.0\n */\nexport function withScope<T>(scope: HydrationScope | null, fn: () => T): T {\n const previous = current;\n current = scope;\n try {\n return fn();\n } finally {\n current = previous;\n }\n}\n\n/**\n * Runs a component call in a scope of its own, so the keys it draws depend only on its position\n * among its parent's calls: what `createComponent` does on the client and on the server. The\n * component's scope takes the next number of the parent scope.\n *\n * @param fn The component call, run synchronously, once.\n * @returns What `fn` returns. Without a scope in effect, `fn` simply runs.\n * @example\n * import { createRootScope, enterComponent, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * withScope(createRootScope(), () => {\n * nextKey(); // \"0-0\"\n * return enterComponent(() => nextKey()); // \"0-1-0\": the component's first key\n * });\n * @since 1.0.0\n */\nexport function enterComponent<T>(fn: () => T): T {\n const parent = current;\n if (parent === null) return fn();\n return withScope({ id: `${parent.id}${parent.count++}-`, count: 0, resources: 0 }, fn);\n}\n\n/**\n * Draws the key of the next template root in the current scope: what `template()` and\n * `ssrHydrationKey()` call, in the same order on the server and the client. Each call advances the\n * scope.\n *\n * @returns The key (`\"0-0\"`, `\"0-1\"`, ...); undefined outside a scope.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createBadge(): Element {\n * return claimElement(nextKey()) ?? document.createElement(\"span\");\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function nextKey(): string | undefined {\n const scope = current;\n if (scope === null) return undefined;\n return `${scope.id}${scope.count++}`;\n}\n\n/**\n * Returns the key a resource's value is stored under in the server data, the same on the server and\n * the client: the explicit key when there is one, else one drawn from the current scope.\n *\n * @param explicit The resource's own key. When given, the result is `` `k:${explicit}` ``, a prefix\n * no generated key has. Undefined draws the next resource key of the scope.\n * @returns `` `k:${explicit}` ``; otherwise the scope id, `r` and the creation index (`\"0-1-r0\"`);\n * `\"r\"` outside a scope.\n * @example\n * import { createRootScope, resourceKey, withScope } from \"@shadow-js/web/extend\";\n *\n * withScope(createRootScope(), () => [resourceKey(undefined), resourceKey(\"user\")]);\n * // [\"0-r0\", \"k:user\"]\n * @since 1.0.0\n */\nexport function resourceKey(explicit: string | undefined): string {\n if (explicit !== undefined) return `k:${explicit}`;\n const scope = current;\n if (scope === null) return \"r\";\n return `${scope.id}r${scope.resources++}`;\n}\n\n/**\n * Creates a fresh scope for an isolated part of the tree, such as a Suspense boundary's content or\n * fallback, or a portal's content: its keys depend only on `key`, not on the siblings around it.\n *\n * @param key The key of the boundary (from `nextKey()`); undefined means no scope.\n * @returns A scope whose `id` is `` `${key}-` ``; `null` when `key` is undefined.\n * @example\n * import { childScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * function renderIsolated<T>(build: () => T): T {\n * return withScope(childScope(nextKey()), build);\n * }\n * @see withScope\n * @since 1.0.0\n */\nexport function childScope(key: string | undefined): HydrationScope | null {\n return key === undefined ? null : { id: `${key}-`, count: 0, resources: 0 };\n}\n"],"mappings":"AAkBA,IAAIA,EAAiC,KAiBrC,SAAgBC,EAAgB,EAAW,IAAqB,CAC9D,MAAO,CAAE,GAAI,GAAGC,EAAS,GAAI,MAAO,EAAG,UAAW,CAAE,CACtD,CAeA,SAAgBC,GAAsC,CACpD,OAAOH,CACT,CAiBA,SAAgBI,EAAa,EAA8B,EAAgB,CACzE,IAAMC,EAAWL,EACjB,EAAUM,EACV,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACR,EAAUF,CACZ,CACF,CAkBA,SAAgBG,EAAkB,EAAgB,CAChD,IAAMC,EAAST,EAEf,OADIS,IAAW,KAAaF,EAAG,EACxBH,EAAU,CAAE,GAAI,GAAGK,EAAO,KAAK,EAAO,QAAQ,GAAI,MAAO,EAAG,UAAW,CAAE,EAAGF,CAAE,CACvF,CAiBA,SAAgBG,GAA8B,CAC5C,IAAMJ,EAAQN,EACd,GAAIM,IAAU,KACd,MAAO,GAAGA,EAAM,KAAK,EAAM,SAC7B,CAiBA,SAAgBK,EAAY,EAAsC,CAChE,GAAIC,IAAa,IAAA,GAAW,MAAO,KAAKA,IACxC,IAAMN,EAAQN,EAEd,OADIM,IAAU,KAAa,IACpB,GAAGA,EAAM,GAAG,GAAG,EAAM,aAC9B,CAiBA,SAAgBO,EAAW,EAAgD,CACzE,OAAOC,IAAQ,IAAA,GAAY,KAAO,CAAE,GAAI,GAAGA,EAAI,GAAI,MAAO,EAAG,UAAW,CAAE,CAC5E,C"}
1
+ {"version":3,"file":"hydration-scope.js","names":["current","createRootScope","renderId","currentScope","withScope","scope","fn","previous","enterComponent","parent","nextKey","resourceKey","explicit","childScope","key"],"sources":["../../../src/internal/hydration-scope.ts"],"sourcesContent":["/**\n * A hydration scope: the deterministic source of hydration keys shared by the server renderer and\n * the client hydrator. Keys depend only on the nesting and order of component calls, never on owners,\n * effects or memos, so server and client agree as long as they run the same components. Scopes are\n * created by {@link createRootScope}, {@link enterComponent} and {@link childScope}; treat their\n * fields as read-only.\n *\n * @since 1.0.0\n */\nexport interface HydrationScope {\n /** Prefix of every key allocated in this scope, ending with `-` (`\"0-\"` for a root, `\"0-3-\"` below). */\n readonly id: string;\n /** Next number handed out by this scope: component scopes and template root keys share it. */\n count: number;\n /** Number of auto-keyed resources created directly in this scope so far. */\n resources: number;\n}\n\nlet current: HydrationScope | null = null;\n\n/**\n * Creates the scope a render or a hydration starts from: what `renderToString` and `hydrate()` put in\n * effect around the app. A custom renderer that hands out hydration keys does the same.\n *\n * @param renderId The prefix of every key of this render. Default: `\"0\"`, the default `renderId` of\n * the renderers.\n * @returns A fresh scope whose `id` is `` `${renderId}-` ``.\n * @example\n * import { createRootScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * const keys = withScope(createRootScope(\"app\"), () => [nextKey(), nextKey()]);\n * // [\"app-0\", \"app-1\"]\n * @see withScope\n * @since 1.0.0\n */\nexport function createRootScope(renderId = \"0\"): HydrationScope {\n return { id: `${renderId}-`, count: 0, resources: 0 };\n}\n\n/**\n * Returns the hydration scope in effect.\n *\n * @returns The current scope; `null` outside a server render, a hydration, or a {@link withScope}\n * call.\n * @example\n * import { currentScope } from \"@shadow-js/web/extend\";\n *\n * function scopeLabel(): string {\n * return currentScope()?.id ?? \"no scope\";\n * }\n * @since 1.0.0\n */\nexport function currentScope(): HydrationScope | null {\n return current;\n}\n\n/**\n * Runs `fn` with `scope` in effect, so the keys `fn` draws come from it. The previous scope is\n * restored when `fn` returns or throws.\n *\n * @param scope The scope to put in effect; `null` runs `fn` with no scope (no keys are drawn).\n * @param fn The code to run, synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { childScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * // The keys of an isolated subtree, independent of its siblings.\n * const first = withScope(childScope(\"0-4\"), () => nextKey()); // \"0-4-0\"\n * @see createRootScope\n * @since 1.0.0\n */\nexport function withScope<T>(scope: HydrationScope | null, fn: () => T): T {\n const previous = current;\n current = scope;\n try {\n return fn();\n } finally {\n current = previous;\n }\n}\n\n/**\n * Runs a component call in a scope of its own, so the keys it draws depend only on its position\n * among its parent's calls: what `createComponent` does on the client and on the server. The\n * component's scope takes the next number of the parent scope.\n *\n * @param fn The component call, run synchronously, once.\n * @returns What `fn` returns. Without a scope in effect, `fn` simply runs.\n * @example\n * import { createRootScope, enterComponent, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * withScope(createRootScope(), () => {\n * nextKey(); // \"0-0\"\n * return enterComponent(() => nextKey()); // \"0-1-0\": the component's first key\n * });\n * @since 1.0.0\n */\nexport function enterComponent<T>(fn: () => T): T {\n const parent = current;\n if (parent === null) return fn();\n return withScope({ id: `${parent.id}${parent.count++}-`, count: 0, resources: 0 }, fn);\n}\n\n/**\n * Draws the key of the next template root in the current scope: what `template()` and\n * `ssrHydrationKey()` call, in the same order on the server and the client. Each call advances the\n * scope.\n *\n * @returns The key (`\"0-0\"`, `\"0-1\"`, ...); undefined outside a scope.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createBadge(): Element {\n * return claimElement(nextKey()) ?? document.createElement(\"span\");\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function nextKey(): string | undefined {\n const scope = current;\n if (scope === null) return undefined;\n return `${scope.id}${scope.count++}`;\n}\n\n/**\n * Returns the key a resource's value is stored under in the server data, the same on the server and\n * the client: the explicit key when there is one, else one drawn from the current scope.\n *\n * @param explicit The resource's own key. When given, the result is `` `k:${explicit}` ``, a prefix\n * no generated key has. Undefined draws the next resource key of the scope.\n * @returns `` `k:${explicit}` ``; otherwise the scope id, `r` and the creation index (`\"0-1-r0\"`);\n * `\"r\"` outside a scope.\n * @example\n * import { createRootScope, resourceKey, withScope } from \"@shadow-js/web/extend\";\n *\n * withScope(createRootScope(), () => [resourceKey(undefined), resourceKey(\"user\")]);\n * // [\"0-r0\", \"k:user\"]\n * @since 1.0.0\n */\nexport function resourceKey(explicit: string | undefined): string {\n if (explicit !== undefined) return `k:${explicit}`;\n const scope = current;\n if (scope === null) return \"r\";\n return `${scope.id}r${scope.resources++}`;\n}\n\n/**\n * Creates a fresh scope for an isolated part of the tree, such as a Suspense boundary's content or\n * fallback, or a portal's content: its keys depend only on `key`, not on the siblings around it.\n *\n * @param key The key of the boundary (from `nextKey()`); undefined means no scope.\n * @returns A scope whose `id` is `` `${key}-` ``; `null` when `key` is undefined.\n * @example\n * import { childScope, nextKey, withScope } from \"@shadow-js/web/extend\";\n *\n * function renderIsolated<T>(build: () => T): T {\n * return withScope(childScope(nextKey()), build);\n * }\n * @see withScope\n * @since 1.0.0\n */\nexport function childScope(key: string | undefined): HydrationScope | null {\n return key === undefined ? null : { id: `${key}-`, count: 0, resources: 0 };\n}\n"],"mappings":"AAkBA,IAAIA,EAAiC,KAiBrC,SAAgBC,EAAgBC,EAAW,IAAqB,CAC9D,MAAO,CAAE,GAAI,GAAGA,EAAS,GAAI,MAAO,EAAG,UAAW,CAAE,CACtD,CAeA,SAAgBC,GAAsC,CACpD,OAAOH,CACT,CAiBA,SAAgBI,EAAaC,EAA8BC,EAAgB,CACzE,IAAMC,EAAWP,EACjBA,EAAUK,EACV,GAAI,CACF,OAAOC,EAAG,CACZ,QAAU,CACRN,EAAUO,CACZ,CACF,CAkBA,SAAgBC,EAAkBF,EAAgB,CAChD,IAAMG,EAAST,EAEf,OADIS,IAAW,KAAaH,EAAG,EACxBF,EAAU,CAAE,GAAI,GAAGK,EAAO,KAAKA,EAAO,QAAQ,GAAI,MAAO,EAAG,UAAW,CAAE,EAAGH,CAAE,CACvF,CAiBA,SAAgBI,GAA8B,CAC5C,IAAML,EAAQL,EACd,GAAIK,IAAU,KACd,MAAO,GAAGA,EAAM,KAAKA,EAAM,SAC7B,CAiBA,SAAgBM,EAAYC,EAAsC,CAChE,GAAIA,IAAa,IAAA,GAAW,MAAO,KAAKA,IACxC,IAAMP,EAAQL,EAEd,OADIK,IAAU,KAAa,IACpB,GAAGA,EAAM,GAAG,GAAGA,EAAM,aAC9B,CAiBA,SAAgBQ,EAAWC,EAAgD,CACzE,OAAOA,IAAQ,IAAA,GAAY,KAAO,CAAE,GAAI,GAAGA,EAAI,GAAI,MAAO,EAAG,UAAW,CAAE,CAC5E,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"portal-context.js","names":["PortalContext"],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n /**\n * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the\n * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the\n * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without\n * it receives nothing from `Portal`.\n * @param key The portal's key, `undefined` when the render has no scope (nothing is written).\n * @param children Reads the content: a thunk, because it must be built inside the portal's scope.\n */\n render?(key: string | undefined, children: () => unknown): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":"A,gDA8CA,MAAaA,EACK,kBAAiC,KAAM,CACrD,KAAM,QACR,CAAC,E"}
1
+ {"version":3,"file":"portal-context.js","names":["createContext","PortalContext"],"sources":["../../../src/internal/portal-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * Receives the markup of the portals a server render produces: what {@link PortalContext} provides\n * when the render was given a `portals` collector.\n * @since 1.0.0\n */\nexport interface PortalSink {\n /**\n * Records the markup of the portal with hydration key `key`. A key recorded again replaces the\n * earlier markup. Throws an `SsrError` whose `code` is `SSR_PORTAL_LIMIT` past 256 portals in one\n * render.\n */\n add(key: string, html: string): void;\n /**\n * Renders a `Portal`'s content into this sink under hydration key `key`. The collectors the\n * renderers provide have it; `Portal` calls it instead of importing the markup writer, so the\n * browser bundle of an app that uses `Portal` does not carry server rendering code. A sink without\n * it receives nothing from `Portal`.\n * @param key The portal's key, `undefined` when the render has no scope (nothing is written).\n * @param children Reads the content: a thunk, because it must be built inside the portal's scope.\n */\n render?(key: string | undefined, children: () => unknown): void;\n}\n\n/**\n * The context through which a server render hands portals their collector: the renderers provide it\n * when they are given a `portals` option (see `createServerPortals`). A custom portal reads it on the\n * server and records its markup under its hydration key, so the client's `claimPortal` adopts it.\n * Its value is `null` for every other render, and in the browser, where a portal writes nothing on\n * the server.\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { nextKey, PortalContext } from \"@shadow-js/web/extend\";\n * import { escape } from \"@shadow-js/web/server\";\n *\n * function ServerToast(props: { text: string }): null {\n * const key = nextKey();\n * const sink = useContext(PortalContext);\n * if (sink !== null && key !== undefined) sink.add(key, `<div role=\"status\">${escape(props.text)}</div>`);\n * return null;\n * }\n * @see claimPortal\n * @since 1.0.0\n */\nexport const PortalContext: Context<PortalSink | null> =\n /* @__PURE__ */ createContext<PortalSink | null>(null, {\n name: \"Portal\",\n });\n"],"mappings":"A,gDA8CA,MAAaC,EACKD,kBAAiC,KAAM,CACrD,KAAM,QACR,CAAC,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","RENAMED","attributeName","renamed","name","svg","prefixed","letter","IGNORED_KEYS","REACT_EVENTS","CHANGE_ON_TYPES","eventPlan","reactSpelling","attribute","capture","lower","planned","tag","type","isFlagAttribute","value"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: RegExp = /^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/;\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES = /^(?:checkbox|radio|file)$/;\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.test(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only. The server and the client share this test, so a value that\n * renders a flag on one side renders it on the other. One space-separated string, not a set of\n * strings, because every bundle that spreads props carries it. A name with a space in it can match\n * two neighbors, but such a name is not a valid attribute name and both renderers refuse it before\n * they write anything.\n */\nconst BOOLEAN_ATTRIBUTES =\n \" async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert \" +\n \"ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected \";\n\n/**\n * True when a prop written under attribute name `name` is a presence flag for `value`: one of the\n * boolean attributes, except `hidden=\"until-found\"`, a keyword that only collapses the element\n * (a bare `hidden` would hide it). The client writes the flag with truthiness, as the server does.\n * @internal\n */\nexport function isFlagAttribute(name: string, value: unknown): boolean {\n return (\n BOOLEAN_ATTRIBUTES.includes(` ${name} `) && !(name === \"hidden\" && value === \"until-found\")\n );\n}\n"],"mappings":"AAgBA,MAAMA,EACJ,mSAGIC,kBAAuC,IAAI,IAAI,CACnD,CAAC,YAAa,OAAO,EACrB,CAAC,UAAW,KAAK,EACjB,CAAC,YAAa,YAAY,EAC1B,CAAC,gBAAiB,gBAAgB,CACpC,CAAC,EAQD,SAAgBC,EAAc,EAAc,EAAsB,CAChE,IAAMC,EAAUF,EAAQ,IAAIG,CAAI,EAChC,GAAID,IAAY,IAAA,GAAW,OAAOA,EAClC,GAAI,CAACE,EAAK,OAAOD,EAAK,YAAY,EAClC,GAAIA,EAAK,SAAS,GAAG,EAAG,OAAOA,EAC/B,IAAME,EAAW,2BAA2B,KAAKF,CAAI,EAGrD,OAFIE,IAAa,KACZN,EAAoB,KAAKI,CAAI,EAC3BA,EAAK,QAAQ,SAAW,GAAW,IAAIG,EAAO,YAAY,GAAG,EADxBH,EADd,GAAGE,EAAS,GAAG,GAAGA,EAAS,EAAE,EAAE,YAAY,IAAIA,EAAS,IAGxF,CAGA,MAAaE,EAAuB,yDAU9BC,kBAA4C,IAAI,IAAI,CACxD,CAAC,QAAS,SAAS,EACnB,CAAC,OAAQ,UAAU,EACnB,CAAC,cAAe,UAAU,CAC5B,CAAC,EAEKC,EAAkB,4BASxB,SAAgBC,EAAU,EAAmB,EAAa,EAAgC,CACxF,IAAMC,EAAgB,WAAW,KAAKC,CAAS,EACzCC,EAAUF,GAAiBC,EAAU,SAAS,SAAS,EACvDE,EAAQF,EAAU,MAAM,EAAGC,EAAU,GAAoB,IAAA,EAAS,CAAC,CAAC,YAAY,EAClFE,EAAUD,EASd,OARIH,IACF,EACEG,IAAU,SACNE,IAAQ,YAAeA,IAAQ,UAAYC,IAAS,MAAQ,CAACR,EAAgB,KAAKQ,CAAI,GACpF,QACA,SACDT,EAAa,IAAIM,CAAK,GAAKA,GAE7B,CAAE,KAAMC,EAAS,UAAS,QAASJ,GAAiBG,IAAU,SAAW,CAACD,CAAQ,CAC3F,CAoBA,SAAgBK,EAAgB,EAAc,EAAyB,CACrE,MACE,oMAAmB,SAAS,IAAIf,EAAK,EAAE,IAAOA,IAAS,UAAYgB,IAAU,cAEjF,C"}
1
+ {"version":3,"file":"react-names.js","names":["SVG_PROPERTY_FAMILY","RENAMED","attributeName","name","svg","renamed","prefixed","letter","IGNORED_KEYS","REACT_EVENTS","CHANGE_ON_TYPES","eventPlan","attribute","tag","type","reactSpelling","capture","lower","planned","isFlagAttribute","value"],"sources":["../../../src/internal/react-names.ts"],"sourcesContent":["/**\n * React spellings at run time: the attribute and event names that a props object (a spread) passes\n * through. The compiler resolves the same names at build time (`packages/compiler/src/internal/\n * react-names.ts`); a test keeps the two presentation lists equal, so keep them in step.\n *\n * @internal\n */\n\n/**\n * SVG presentation attributes are CSS properties, and React spells them in camelCase (`strokeWidth` is\n * `stroke-width`). A camelCase name whose first word is one of these families is hyphenated. The\n * families are the first words of the CSS properties SVG takes as attributes, so one rule covers the\n * presentation list. The compiler's table (`packages/compiler/src/internal/react-names.ts`) lists the\n * same names, and a test checks each one. The exceptions are SVG attributes that start with a family but are\n * not CSS properties (`clipPathUnits`, `markerWidth`): they are camelCase in SVG, so they keep their case.\n */\nconst SVG_PROPERTY_FAMILY =\n /^(?!clipPathUnits|glyphRef|marker(?:Height|Units|Width)|mask(?:Content)?Units|textLength)(?:alignment|baseline|clip|color|dominant|enable|fill|flood|font|glyph|image|letter|lighting|marker|mask|mix|paint|pointer|shape|stop|stroke|text|transform|unicode|vector|white|word|writing)(?=[A-Z])/;\n\n/** React names whose attribute differs from the lower-cased key, in HTML and SVG alike. */\nconst RENAMED: ReadonlyMap<string, string> = new Map([\n [\"className\", \"class\"],\n [\"htmlFor\", \"for\"],\n [\"httpEquiv\", \"http-equiv\"],\n [\"acceptCharset\", \"accept-charset\"],\n]);\n\n/**\n * The attribute name for a props key on an element: HTML names are lower case (what the parser and\n * `setAttribute` write anyway, and what server markup needs); SVG presentation names are hyphenated,\n * `xlinkHref` and `xmlLang` take their prefix, and other SVG names keep their case (`viewBox`).\n * @internal\n */\nexport function attributeName(name: string, svg: boolean): string {\n const renamed = RENAMED.get(name);\n if (renamed !== undefined) return renamed;\n if (!svg) return name.toLowerCase();\n if (name.includes(\":\")) return name;\n const prefixed = /^(xlink|xml)([A-Z])(.*)$/.exec(name);\n if (prefixed !== null) return `${prefixed[1]}:${prefixed[2]?.toLowerCase()}${prefixed[3]}`;\n if (!SVG_PROPERTY_FAMILY.test(name)) return name;\n return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);\n}\n\n/** Props that have no DOM form: a spread ignores them (React's `key` and hydration flags). @internal */\nexport const IGNORED_KEYS: RegExp = /^(?:key|suppress(?:Hydration|ContentEditable)Warning)$/;\n\n/** The DOM event for a React-spelled prop (see the compiler's `eventPlan`). @internal */\nexport interface EventPlan {\n readonly type: string;\n readonly capture: boolean;\n readonly passive: boolean;\n}\n\n/** React events that bubble under another name. */\nconst REACT_EVENTS: ReadonlyMap<string, string> = new Map([\n [\"focus\", \"focusin\"],\n [\"blur\", \"focusout\"],\n [\"doubleclick\", \"dblclick\"],\n]);\n\nconst CHANGE_ON_TYPES = /^(?:checkbox|radio|file)$/;\n\n/**\n * Plans the DOM event for an `on*` prop. React's spellings follow React: `onChange` is the per-edit\n * `input` event on text inputs and textareas and the `change` event on other controls; `onFocus` and\n * `onBlur` bubble as `focusin` and `focusout`; a `...Capture` suffix binds the capture phase; `onWheel`\n * is passive. A lower-case `on` spelling is the native event.\n * @internal\n */\nexport function eventPlan(attribute: string, tag: string, type: string | null): EventPlan {\n const reactSpelling = /^on[A-Z]/.test(attribute);\n const capture = reactSpelling && attribute.endsWith(\"Capture\");\n const lower = attribute.slice(2, capture ? -\"Capture\".length : undefined).toLowerCase();\n let planned = lower;\n if (reactSpelling) {\n planned =\n lower === \"change\"\n ? tag === \"textarea\" || (tag === \"input\" && (type === null || !CHANGE_ON_TYPES.test(type)))\n ? \"input\"\n : \"change\"\n : (REACT_EVENTS.get(lower) ?? lower);\n }\n return { type: planned, capture, passive: reactSpelling && lower === \"wheel\" && !capture };\n}\n\n/**\n * Boolean attributes that a props object writes as presence flags (`disabled: true` gives a bare\n * `disabled`). Lower-case names only. The server and the client share this test, so a value that\n * renders a flag on one side renders it on the other. One space-separated string, not a set of\n * strings, because every bundle that spreads props carries it. A name with a space in it can match\n * two neighbors, but such a name is not a valid attribute name and both renderers refuse it before\n * they write anything.\n */\nconst BOOLEAN_ATTRIBUTES =\n \" async autofocus autoplay checked controls default defer disabled formnovalidate hidden inert \" +\n \"ismap loop multiple muted nomodule novalidate open playsinline readonly required reversed selected \";\n\n/**\n * True when a prop written under attribute name `name` is a presence flag for `value`: one of the\n * boolean attributes, except `hidden=\"until-found\"`, a keyword that only collapses the element\n * (a bare `hidden` would hide it). The client writes the flag with truthiness, as the server does.\n * @internal\n */\nexport function isFlagAttribute(name: string, value: unknown): boolean {\n return (\n BOOLEAN_ATTRIBUTES.includes(` ${name} `) && !(name === \"hidden\" && value === \"until-found\")\n );\n}\n"],"mappings":"AAgBA,MAAMA,EACJ,mSAGIC,kBAAuC,IAAI,IAAI,CACnD,CAAC,YAAa,OAAO,EACrB,CAAC,UAAW,KAAK,EACjB,CAAC,YAAa,YAAY,EAC1B,CAAC,gBAAiB,gBAAgB,CACpC,CAAC,EAQD,SAAgBC,EAAcC,EAAcC,EAAsB,CAChE,IAAMC,EAAUJ,EAAQ,IAAIE,CAAI,EAChC,GAAIE,IAAY,IAAA,GAAW,OAAOA,EAClC,GAAI,CAACD,EAAK,OAAOD,EAAK,YAAY,EAClC,GAAIA,EAAK,SAAS,GAAG,EAAG,OAAOA,EAC/B,IAAMG,EAAW,2BAA2B,KAAKH,CAAI,EAGrD,OAFIG,IAAa,KACZN,EAAoB,KAAKG,CAAI,EAC3BA,EAAK,QAAQ,SAAWI,GAAW,IAAIA,EAAO,YAAY,GAAG,EADxBJ,EADd,GAAGG,EAAS,GAAG,GAAGA,EAAS,EAAE,EAAE,YAAY,IAAIA,EAAS,IAGxF,CAGA,MAAaE,EAAuB,yDAU9BC,kBAA4C,IAAI,IAAI,CACxD,CAAC,QAAS,SAAS,EACnB,CAAC,OAAQ,UAAU,EACnB,CAAC,cAAe,UAAU,CAC5B,CAAC,EAEKC,EAAkB,4BASxB,SAAgBC,EAAUC,EAAmBC,EAAaC,EAAgC,CACxF,IAAMC,EAAgB,WAAW,KAAKH,CAAS,EACzCI,EAAUD,GAAiBH,EAAU,SAAS,SAAS,EACvDK,EAAQL,EAAU,MAAM,EAAGI,EAAU,GAAoB,IAAA,EAAS,CAAC,CAAC,YAAY,EAClFE,EAAUD,EASd,OARIF,IACFG,EACED,IAAU,SACNJ,IAAQ,YAAeA,IAAQ,UAAYC,IAAS,MAAQ,CAACJ,EAAgB,KAAKI,CAAI,GACpF,QACA,SACDL,EAAa,IAAIQ,CAAK,GAAKA,GAE7B,CAAE,KAAMC,EAASF,UAAS,QAASD,GAAiBE,IAAU,SAAW,CAACD,CAAQ,CAC3F,CAoBA,SAAgBG,EAAgBhB,EAAciB,EAAyB,CACrE,MACE,oMAAmB,SAAS,IAAIjB,EAAK,EAAE,IAAOA,IAAS,UAAYiB,IAAU,cAEjF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"reconcile.js","names":["keepFocus","root","at","active","run","removeNode","node","parent","markLongestIncreasing","tails","previous","values","index","value","low","high","middle","cursor","offset","reconcileNodes","prevLength","prev","nextLength","next","head","prevTail","nextTail","before","end","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":"AAYA,SAAgBA,EAAU,EAAU,EAAuB,CACzD,IAAMC,EAAOC,EAAG,YAAY,EACtBC,EAASF,EAAK,cACpBG,EAAI,EACAD,GAAU,MAAQF,EAAK,gBAAkBE,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,CAGA,SAASE,EAAW,EAAc,EAA8B,CAC1DC,IAAS,IAAA,IAAaA,EAAK,aAAeC,GAAQA,EAAO,YAAYD,CAAI,CAC/E,CAOA,SAASE,EAAsB,EAA2B,EAAgB,EAAyB,CAEjG,IAAMC,EAAkB,CAAC,EACnBC,EAAqBC,EAAO,QAAU,EAAE,EAC9C,IAAK,IAAIC,EAAQ,EAAGA,EAAQD,EAAO,OAAQ,GAAS,EAAG,CACrD,IAAME,EAAQF,EAAOC,GACjBE,EAAM,EACNC,EAAON,EAAM,OACjB,KAAOK,EAAMC,GAAM,CACjB,IAAMC,EAAUF,EAAMC,GAAS,EACjBJ,EAAOF,EAAMO,IACfH,EAAO,EAAMG,EAAS,EAC7B,EAAOA,CACd,CAEA,EAASJ,GAASH,EAAMK,EAAM,IAAM,GACpC,EAAMA,GAAOF,CACf,CACA,IAAIK,EAASR,EAAM,GAAG,EAAE,GAAK,GAC7B,KAAOQ,IAAW,IAChB,EAAON,EAAOM,GAAqBC,GAAU,EAC7C,EAASR,EAASO,EAEtB,CAuCA,SAAgBE,EACd,EACA,EACA,EACA,EACM,CACN,IAAMC,EAAaC,EAAK,OAClBC,EAAaC,EAAK,OAEpBC,EAAO,EACX,KAAOA,EAAOJ,GAAcI,EAA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AOiB,EAAKX,GACdoB,EAAOpB,EAAQY,KAAU,IACvBS,GAAW3B,EAAK,aAAeC,EACjCA,EAA0B,WAAWD,EAAM4B,CAAU,EAClD3B,EAAO,aAAaD,EAAM4B,CAAU,GAE3C,EAAa5B,CACf,CACIH,GAAU,MAAQF,EAAK,gBAAkBE,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,C"}
1
+ {"version":3,"file":"reconcile.js","names":["keepFocus","at","run","root","active","removeNode","parent","node","markLongestIncreasing","values","offset","marks","tails","previous","index","value","low","high","middle","cursor","reconcileNodes","prev","next","end","prevLength","nextLength","head","prevTail","nextTail","before","target","survivors","position","stable","movable","anchorNode"],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":"AAYA,SAAgBA,EAAUC,EAAUC,EAAuB,CACzD,IAAMC,EAAOF,EAAG,YAAY,EACtBG,EAASD,EAAK,cACpBD,EAAI,EACAE,GAAU,MAAQD,EAAK,gBAAkBC,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,CAGA,SAASC,EAAWC,EAAcC,EAA8B,CAC1DA,IAAS,IAAA,IAAaA,EAAK,aAAeD,GAAQA,EAAO,YAAYC,CAAI,CAC/E,CAOA,SAASC,EAAsBC,EAA2BC,EAAgBC,EAAyB,CAEjG,IAAMC,EAAkB,CAAC,EACnBC,EAAqBJ,EAAO,QAAU,EAAE,EAC9C,IAAK,IAAIK,EAAQ,EAAGA,EAAQL,EAAO,OAAQK,GAAS,EAAG,CACrD,IAAMC,EAAQN,EAAOK,GACjBE,EAAM,EACNC,EAAOL,EAAM,OACjB,KAAOI,EAAMC,GAAM,CACjB,IAAMC,EAAUF,EAAMC,GAAS,EACjBR,EAAOG,EAAMM,IACfH,EAAOC,EAAME,EAAS,EAC7BD,EAAOC,CACd,CAEAL,EAASC,GAASF,EAAMI,EAAM,IAAM,GACpCJ,EAAMI,GAAOF,CACf,CACA,IAAIK,EAASP,EAAM,GAAG,EAAE,GAAK,GAC7B,KAAOO,IAAW,IAChBR,EAAOF,EAAOU,GAAqBT,GAAU,EAC7CS,EAASN,EAASM,EAEtB,CAuCA,SAAgBC,EACdd,EACAe,EACAC,EACAC,EACM,CACN,IAAMC,EAAaH,EAAK,OAClBI,EAAaH,EAAK,OAEpBI,EAAO,EACX,KAAOA,EAAOF,GAAcE,EAAOD,GAAcJ,EAAKK,KAAUJ,EAAKI,IAAOA,GAAQ,EACpF,IAAIC,EAAWH,EACXI,EAAWH,EACf,KAAOE,EAAWD,GAAQE,EAAWF,GAAQL,EAAKM,EAAW,KAAOL,EA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E3CA,EAAa5B,CACf,CACIH,GAAU,MAAQD,EAAK,gBAAkBC,GAAQA,EAAO,MAAM,CAAE,cAAe,EAAK,CAAC,CAC3F,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"stream-context.js","names":["StreamContext"],"sources":["../../../src/internal/stream-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * A Suspense boundary whose content was not ready when the shell rendered: `renderToStream` calls\n * `rebuild` again each time a resource settles, and streams the markup once it is complete.\n * @since 1.0.0\n */\nexport interface StreamBoundary {\n /**\n * The boundary's hydration key. The shell must wrap the fallback in `<!--[b:ID-->` and `<!--]-->`\n * comments so the streamed chunk can replace it.\n */\n readonly id: string;\n /**\n * Renders the content again. Returns its final markup, or `null` when it is still pending, in which\n * case it has deferred itself again with {@link StreamSink.defer}.\n */\n rebuild(): string | null;\n}\n\n/**\n * Receives the boundaries that are still pending during a streaming render: what\n * {@link StreamContext} provides.\n * @since 1.0.0\n */\nexport interface StreamSink {\n /** Queues `boundary` to be rebuilt when the next resource settles. */\n defer(boundary: StreamBoundary): void;\n}\n\n/**\n * The context through which `renderToStream` lets a Suspense-like boundary defer its content: a\n * boundary that is pending in the shell renders its fallback between `<!--[b:ID-->` and `<!--]-->`\n * and defers a {@link StreamBoundary} to the sink. Its value is `null` for every other render (the\n * boundary then keeps its fallback).\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { StreamContext } from \"@shadow-js/web/extend\";\n *\n * function canStream(): boolean {\n * // Inside a component rendered by renderToStream.\n * return useContext(StreamContext) !== null;\n * }\n * @since 1.0.0\n */\nexport const StreamContext: Context<StreamSink | null> =\n /* @__PURE__ */ createContext<StreamSink | null>(null, {\n name: \"Stream\",\n });\n"],"mappings":"A,gDA8CA,MAAaA,EACK,kBAAiC,KAAM,CACrD,KAAM,QACR,CAAC,E"}
1
+ {"version":3,"file":"stream-context.js","names":["createContext","StreamContext"],"sources":["../../../src/internal/stream-context.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\n\n/**\n * A Suspense boundary whose content was not ready when the shell rendered: `renderToStream` calls\n * `rebuild` again each time a resource settles, and streams the markup once it is complete.\n * @since 1.0.0\n */\nexport interface StreamBoundary {\n /**\n * The boundary's hydration key. The shell must wrap the fallback in `<!--[b:ID-->` and `<!--]-->`\n * comments so the streamed chunk can replace it.\n */\n readonly id: string;\n /**\n * Renders the content again. Returns its final markup, or `null` when it is still pending, in which\n * case it has deferred itself again with {@link StreamSink.defer}.\n */\n rebuild(): string | null;\n}\n\n/**\n * Receives the boundaries that are still pending during a streaming render: what\n * {@link StreamContext} provides.\n * @since 1.0.0\n */\nexport interface StreamSink {\n /** Queues `boundary` to be rebuilt when the next resource settles. */\n defer(boundary: StreamBoundary): void;\n}\n\n/**\n * The context through which `renderToStream` lets a Suspense-like boundary defer its content: a\n * boundary that is pending in the shell renders its fallback between `<!--[b:ID-->` and `<!--]-->`\n * and defers a {@link StreamBoundary} to the sink. Its value is `null` for every other render (the\n * boundary then keeps its fallback).\n *\n * @example\n * import { useContext } from \"@shadow-js/core\";\n * import { StreamContext } from \"@shadow-js/web/extend\";\n *\n * function canStream(): boolean {\n * // Inside a component rendered by renderToStream.\n * return useContext(StreamContext) !== null;\n * }\n * @since 1.0.0\n */\nexport const StreamContext: Context<StreamSink | null> =\n /* @__PURE__ */ createContext<StreamSink | null>(null, {\n name: \"Stream\",\n });\n"],"mappings":"A,gDA8CA,MAAaC,EACKD,kBAAiC,KAAM,CACrD,KAAM,QACR,CAAC,E"}
@@ -1 +1 @@
1
- {"version":3,"file":"reactive.js","names":["effect","apply","useRenderEffect","compute","memo","useMemo","fn","use","cleanup","untrack","el","arg","onCleanup","refTo","target","holder","getOwner"],"sources":["../../src/reactive.ts"],"sourcesContent":["import {\n type Cleanup,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useRenderEffect,\n} from \"@shadow-js/core\";\n\n/**\n * Runs `fn` as a render effect: synchronously when created, and again when the signals it reads\n * change. It is the effect the compiler emits for DOM bindings; application code usually prefers\n * `useEffect`. A function returned by `fn` is its cleanup, run before the next run and when the\n * owner disposes. It never runs on the server, and in development an effect created outside an\n * owner warns `NO_OWNER_EFFECT`.\n *\n * @param fn Tracked body. Returns an optional cleanup function.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { effect } from \"@shadow-js/web\";\n *\n * const label = document.createElement(\"span\");\n * createRoot(() => {\n * const [name] = useSignal(\"Ada\");\n * effect(() => {\n * label.textContent = name(); // runs now, and again when name changes\n * });\n * });\n * @see memo\n * @since 1.0.0\n */\nexport function effect(fn: () => void | Cleanup): void;\n/**\n * Two-form render effect: `compute` is tracked and `apply` runs untracked with the new and the\n * previous value. A function returned by `apply` is its cleanup. Use it to keep the tracked reads\n * apart from the code that writes the DOM.\n *\n * @param compute Tracked. Its result is passed to `apply`.\n * @param apply Untracked. Receives the value and the previous value (`undefined` on the first run)\n * and returns an optional cleanup function.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { effect } from \"@shadow-js/web\";\n *\n * const title = document.createElement(\"h1\");\n * createRoot(() => {\n * const [text] = useSignal(\"Hello\");\n * effect(text, (value, previous) => {\n * title.textContent = value;\n * console.log(previous); // undefined on the first run\n * });\n * });\n * @see memo\n * @since 1.0.0\n */\nexport function effect<T>(\n compute: () => T,\n apply: (value: T, previous: T | undefined) => void | Cleanup,\n): void;\nexport function effect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n if (apply === undefined) useRenderEffect(compute);\n else useRenderEffect(compute, apply);\n}\n\n/**\n * Creates a cached derivation that recomputes only when the signals it reads change. It is core's\n * `useMemo` under the short name the compiler emits.\n *\n * @param fn The computation. Tracked; its result is cached until a dependency changes.\n * @returns An accessor for the current value.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { memo } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [count, setCount] = useSignal(2);\n * const doubled = memo(() => count() * 2);\n * setCount(4);\n * console.log(doubled()); // 8\n * }\n * @see effect\n * @since 1.0.0\n */\nexport function memo<T>(fn: () => T): () => T {\n return useMemo<T>(fn);\n}\n\n/**\n * Applies a directive: calls `fn(el, arg)` untracked, so a directive or a ref never subscribes the\n * surrounding effect to what it reads. A function returned by `fn` is a cleanup, run when the owner\n * disposes.\n *\n * @param fn The directive. Receives the element and the accessor of its argument.\n * @param el The element the directive applies to.\n * @param arg Accessor for the directive's argument. Undefined passes `undefined` through; the\n * directive reads the accessor where it wants to track it.\n * @example\n * import { use } from \"@shadow-js/web\";\n *\n * function tooltip(el: Element, text: () => string) {\n * el.setAttribute(\"title\", text());\n * }\n * const button = document.createElement(\"button\");\n * use(tooltip, button, () => \"Save the draft\");\n * @see refTo\n * @since 1.0.0\n */\nexport function use<T>(\n fn: (el: Element, arg: () => T) => unknown,\n el: Element,\n arg?: () => T,\n): void {\n const cleanup = untrack(() => fn(el, arg as () => T));\n // A ref callback may return a cleanup (React 19): it runs when the owner of the element is disposed.\n if (typeof cleanup === \"function\") onCleanup(cleanup as Cleanup);\n}\n\n/**\n * Fills a ref of any form the compiler accepts. A callback is called with the element (its returned\n * cleanup runs when the owner disposes). A `{ current }` object gets the element as `current`, and\n * `null` once the owner is disposed, as React's `useRef` objects do. Any other value is ignored.\n *\n * @param target The ref value: a callback, a `{ current }` object, or anything else (ignored).\n * @param el The element the ref receives.\n * @example\n * import { refTo } from \"@shadow-js/web\";\n *\n * const box = { current: null as HTMLDivElement | null };\n * const div = document.createElement(\"div\");\n * refTo(box, div);\n * console.log(box.current === div); // true\n * @see use\n * @since 1.0.0\n */\nexport function refTo(target: unknown, el: Element): void {\n if (typeof target === \"function\") {\n use(target as (node: Element, arg: () => unknown) => unknown, el);\n return;\n }\n if (target === null || typeof target !== \"object\" || !(\"current\" in target)) return;\n const holder = target as { current: unknown };\n holder.current = el;\n if (getOwner() !== null) {\n onCleanup(() => {\n holder.current = null;\n });\n }\n}\n"],"mappings":"A,yGA2DA,SAAgBA,EACd,EACA,EACM,CACFC,IAAU,IAAA,GAAWC,EAAgBC,CAAO,EAC3CD,EAAgBC,EAASF,CAAK,CACrC,CAqBA,SAAgBG,EAAQ,EAAsB,CAC5C,OAAOC,EAAWC,CAAE,CACtB,CAsBA,SAAgBC,EACd,EACA,EACA,EACM,CACN,IAAMC,EAAUC,MAAcH,EAAGI,EAAIC,CAAc,CAAC,EAEhD,OAAOH,GAAY,YAAYI,EAAUJ,CAAkB,CACjE,CAmBA,SAAgBK,EAAM,EAAiB,EAAmB,CACxD,GAAI,OAAOC,GAAW,WAAY,CAChCP,EAAIO,EAA0DJ,CAAE,EAChE,MACF,CACA,GAAuB,OAAOI,GAAW,WAArCA,GAAiD,EAAE,YAAaA,GAAS,OAC7E,IAAMC,EAASD,EACf,EAAO,QAAUJ,EACbM,EAAS,IAAM,MACjBJ,MAAgB,CACd,EAAO,QAAU,IACnB,CAAC,CAEL,C"}
1
+ {"version":3,"file":"reactive.js","names":["getOwner","onCleanup","untrack","useMemo","useRenderEffect","effect","compute","apply","memo","fn","use","el","arg","cleanup","refTo","target","holder"],"sources":["../../src/reactive.ts"],"sourcesContent":["import {\n type Cleanup,\n getOwner,\n onCleanup,\n untrack,\n useMemo,\n useRenderEffect,\n} from \"@shadow-js/core\";\n\n/**\n * Runs `fn` as a render effect: synchronously when created, and again when the signals it reads\n * change. It is the effect the compiler emits for DOM bindings; application code usually prefers\n * `useEffect`. A function returned by `fn` is its cleanup, run before the next run and when the\n * owner disposes. It never runs on the server, and in development an effect created outside an\n * owner warns `NO_OWNER_EFFECT`.\n *\n * @param fn Tracked body. Returns an optional cleanup function.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { effect } from \"@shadow-js/web\";\n *\n * const label = document.createElement(\"span\");\n * createRoot(() => {\n * const [name] = useSignal(\"Ada\");\n * effect(() => {\n * label.textContent = name(); // runs now, and again when name changes\n * });\n * });\n * @see memo\n * @since 1.0.0\n */\nexport function effect(fn: () => void | Cleanup): void;\n/**\n * Two-form render effect: `compute` is tracked and `apply` runs untracked with the new and the\n * previous value. A function returned by `apply` is its cleanup. Use it to keep the tracked reads\n * apart from the code that writes the DOM.\n *\n * @param compute Tracked. Its result is passed to `apply`.\n * @param apply Untracked. Receives the value and the previous value (`undefined` on the first run)\n * and returns an optional cleanup function.\n * @example\n * import { createRoot, useSignal } from \"@shadow-js/core\";\n * import { effect } from \"@shadow-js/web\";\n *\n * const title = document.createElement(\"h1\");\n * createRoot(() => {\n * const [text] = useSignal(\"Hello\");\n * effect(text, (value, previous) => {\n * title.textContent = value;\n * console.log(previous); // undefined on the first run\n * });\n * });\n * @see memo\n * @since 1.0.0\n */\nexport function effect<T>(\n compute: () => T,\n apply: (value: T, previous: T | undefined) => void | Cleanup,\n): void;\nexport function effect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n if (apply === undefined) useRenderEffect(compute);\n else useRenderEffect(compute, apply);\n}\n\n/**\n * Creates a cached derivation that recomputes only when the signals it reads change. It is core's\n * `useMemo` under the short name the compiler emits.\n *\n * @param fn The computation. Tracked; its result is cached until a dependency changes.\n * @returns An accessor for the current value.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { memo } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [count, setCount] = useSignal(2);\n * const doubled = memo(() => count() * 2);\n * setCount(4);\n * console.log(doubled()); // 8\n * }\n * @see effect\n * @since 1.0.0\n */\nexport function memo<T>(fn: () => T): () => T {\n return useMemo<T>(fn);\n}\n\n/**\n * Applies a directive: calls `fn(el, arg)` untracked, so a directive or a ref never subscribes the\n * surrounding effect to what it reads. A function returned by `fn` is a cleanup, run when the owner\n * disposes.\n *\n * @param fn The directive. Receives the element and the accessor of its argument.\n * @param el The element the directive applies to.\n * @param arg Accessor for the directive's argument. Undefined passes `undefined` through; the\n * directive reads the accessor where it wants to track it.\n * @example\n * import { use } from \"@shadow-js/web\";\n *\n * function tooltip(el: Element, text: () => string) {\n * el.setAttribute(\"title\", text());\n * }\n * const button = document.createElement(\"button\");\n * use(tooltip, button, () => \"Save the draft\");\n * @see refTo\n * @since 1.0.0\n */\nexport function use<T>(\n fn: (el: Element, arg: () => T) => unknown,\n el: Element,\n arg?: () => T,\n): void {\n const cleanup = untrack(() => fn(el, arg as () => T));\n // A ref callback may return a cleanup (React 19): it runs when the owner of the element is disposed.\n if (typeof cleanup === \"function\") onCleanup(cleanup as Cleanup);\n}\n\n/**\n * Fills a ref of any form the compiler accepts. A callback is called with the element (its returned\n * cleanup runs when the owner disposes). A `{ current }` object gets the element as `current`, and\n * `null` once the owner is disposed, as React's `useRef` objects do. Any other value is ignored.\n *\n * @param target The ref value: a callback, a `{ current }` object, or anything else (ignored).\n * @param el The element the ref receives.\n * @example\n * import { refTo } from \"@shadow-js/web\";\n *\n * const box = { current: null as HTMLDivElement | null };\n * const div = document.createElement(\"div\");\n * refTo(box, div);\n * console.log(box.current === div); // true\n * @see use\n * @since 1.0.0\n */\nexport function refTo(target: unknown, el: Element): void {\n if (typeof target === \"function\") {\n use(target as (node: Element, arg: () => unknown) => unknown, el);\n return;\n }\n if (target === null || typeof target !== \"object\" || !(\"current\" in target)) return;\n const holder = target as { current: unknown };\n holder.current = el;\n if (getOwner() !== null) {\n onCleanup(() => {\n holder.current = null;\n });\n }\n}\n"],"mappings":"A,yGA2DA,SAAgBK,EACdC,EACAC,EACM,CACFA,IAAU,IAAA,GAAWH,EAAgBE,CAAO,EAC3CF,EAAgBE,EAASC,CAAK,CACrC,CAqBA,SAAgBC,EAAQC,EAAsB,CAC5C,OAAON,EAAWM,CAAE,CACtB,CAsBA,SAAgBC,EACdD,EACAE,EACAC,EACM,CACN,IAAMC,EAAUX,MAAcO,EAAGE,EAAIC,CAAc,CAAC,EAEhD,OAAOC,GAAY,YAAYZ,EAAUY,CAAkB,CACjE,CAmBA,SAAgBC,EAAMC,EAAiBJ,EAAmB,CACxD,GAAI,OAAOI,GAAW,WAAY,CAChCL,EAAIK,EAA0DJ,CAAE,EAChE,MACF,CACA,GAAuB,OAAOI,GAAW,WAArCA,GAAiD,EAAE,YAAaA,GAAS,OAC7E,IAAMC,EAASD,EACfC,EAAO,QAAUL,EACbX,EAAS,IAAM,MACjBC,MAAgB,CACde,EAAO,QAAU,IACnB,CAAC,CAEL,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":["render","region","createRegion","container","stop","disposed","teardown","removeRegion","claims","withScope","batch","createRoot","dispose","options","attachRootErrors","bindRegion","untrack","code","flushSync","error","cleanupError"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n try {\n claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n stop = dispose;\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n }),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a render that throws (an effect of the first flush failed),\n // so the root must not stay alive with its DOM and effects.\n try {\n teardown();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"render() failed and so did its teardown.\" : \"SHADOW_RENDER_ERRORS\",\n );\n }\n throw error;\n }\n return teardown;\n}\n"],"mappings":"A,mVAsCA,SAAgBA,EACd,EACA,EACA,EACY,CACZ,IAAMC,EAASC,EAAaC,EAAW,KAAM,IAAA,EAAS,EAClDC,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaN,CAAM,EACrB,EAKA,GAAI,CACFO,EAAO,QAAQ,oBACbC,EAAU,SACRC,MACEC,EAAY,GAAY,CACtB,EAAOC,EAEHC,IAAY,IAAA,IAAWC,EAAiBD,CAAO,EAEnDE,EAAWd,EAAQe,EAAQC,CAAI,CAAC,CAClC,CAAC,CACH,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFb,EAAS,CACX,OAASc,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACmC,sBACzD,CACF,CACA,MAAMD,CACR,CACA,OAAOb,CACT,C"}
1
+ {"version":3,"file":"render.js","names":["attachRootErrors","bindRegion","createRegion","removeRegion","claims","withScope","batch","createRoot","flushSync","untrack","render","code","container","options","region","stop","disposed","teardown","dispose","error","cleanupError"],"sources":["../../src/render.ts"],"sourcesContent":["import { batch, createRoot, flushSync, untrack } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link render}: the error reporters of the root.\n * @since 1.0.0\n */\nexport type RenderOptions = RootErrorOptions;\n\n/**\n * Mounts `code` into `container`. Creates an owner, inserts the output, flushes the effects, and\n * returns a dispose function that stops the owner and removes the nodes this call inserted. A\n * second render into the same container appends after the first.\n *\n * @param code Runs once, untracked, to build the tree (a component call, a node, text or an array).\n * Return an accessor (for example `() => count`) from it to make the root content reactive.\n * @param container Element, Document or DocumentFragment that receives the output.\n * @param options The root's error reporters (`onUncaughtError`, `onCaughtError`). Undefined sets\n * no reporter.\n * @returns A dispose function, safe to call more than once.\n * @example\n * import { createComponent, render } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const dispose = render(\n * () => createComponent(App, {}),\n * document.getElementById(\"root\") as Element,\n * );\n * dispose(); // stops the root and removes the text it inserted\n * @see hydrate\n * @since 1.0.0\n */\nexport function render(\n code: () => unknown,\n container: Element | Document | DocumentFragment,\n options?: RenderOptions,\n): () => void {\n const region = createRegion(container, null, undefined);\n let stop: (() => void) | undefined;\n let disposed = false;\n const teardown = (): void => {\n if (disposed) return;\n disposed = true;\n stop?.();\n removeRegion(region);\n };\n // One batch around the build: effects (and anything a resource's batch would flush mid-build)\n // wait until the whole tree exists, so a Suspense boundary knows what is pending before its\n // content's effects are considered.\n // A fresh root never consumes the enclosing hydration pass's nodes or key sequence.\n try {\n claims.current.withoutClaiming(() =>\n withScope(null, () =>\n batch(() =>\n createRoot((dispose) => {\n stop = dispose;\n // An error nothing else took ends here; with onUncaughtError it is reported instead of thrown.\n if (options !== undefined) attachRootErrors(options);\n // The component tree is built once; only accessors inside the result stay reactive.\n bindRegion(region, untrack(code));\n }),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a render that throws (an effect of the first flush failed),\n // so the root must not stay alive with its DOM and effects.\n try {\n teardown();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"render() failed and so did its teardown.\" : \"SHADOW_RENDER_ERRORS\",\n );\n }\n throw error;\n }\n return teardown;\n}\n"],"mappings":"A,mVAsCA,SAAgBU,EACdC,EACAC,EACAC,EACY,CACZ,IAAMC,EAASZ,EAAaU,EAAW,KAAM,IAAA,EAAS,EAClDG,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJA,EAAW,GACXD,IAAO,EACPZ,EAAaW,CAAM,EACrB,EAKA,GAAI,CACFV,EAAO,QAAQ,oBACbC,EAAU,SACRC,MACEC,EAAYW,GAAY,CACtBH,EAAOG,EAEHL,IAAY,IAAA,IAAWb,EAAiBa,CAAO,EAEnDZ,EAAWa,EAAQL,EAAQE,CAAI,CAAC,CAClC,CAAC,CACH,CACF,CACF,EACAH,EAAU,CACZ,OAASW,EAAO,CAGd,GAAI,CACFF,EAAS,CACX,OAASG,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACmC,sBACzD,CACF,CACA,MAAMD,CACR,CACA,OAAOF,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"resource-hints.js","names":["checkUrl","url","href","carries","name","value","attributes","element","hint","isServer","serverTag","same","tag","existing","\"src\"","\"type\"","serverLink","useHead","preconnect","options","prefetchDNS","preload","preloadModule","preinit","preinitModule"],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept, and a script already anywhere in the document with the same `src` and `type` is\n * not loaded again. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n // A script is the same load when its URL and kind match: the page's own bundle usually sits at the end\n // of the body, and carries `defer` or `async` or neither, so the attributes of the hint are no test.\n const same =\n tag === \"script\"\n ? (existing: Element): boolean =>\n existing.getAttribute(\"src\") === attributes[\"src\"] &&\n (existing.getAttribute(\"type\") ?? \"\") === (attributes[\"type\"] ?? \"\")\n : (existing: Element): boolean => carries(existing, attributes);\n for (const existing of (tag === \"script\" ? document : document.head).querySelectorAll(tag)) {\n if (same(existing)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":"A,wFAoEA,SAASA,EAAS,EAAoB,CACpC,IAAMC,EAAM,IAAI,IAAIC,EAAM,sBAAsB,EAChD,GAAID,EAAI,WAAa,UAAYA,EAAI,WAAa,QAChD,MAAU,UAGJ,0BACN,CAEJ,CAGA,SAASE,EAAQ,EAAkB,EAAiC,CAClE,IAAK,GAAM,CAACC,EAAMC,KAAU,OAAO,QAAQC,CAAU,EACnD,GAAIC,EAAQ,aAAaH,CAAI,IAAMC,EAAO,MAAO,GAEnD,MAAO,EACT,CAOA,SAASG,EACP,EACA,EACA,MAA8B,IAAA,GACxB,CACN,GAAIC,EAAU,CACZC,EAAU,EACV,MACF,CACA,GAAI,OAAO,SAAa,IAAa,OAGrC,IAAMC,EACJC,IAAQ,SACH,GACCC,EAAS,aAAa,KAAK,IAAMP,EAAWQ,MAC3CD,EAAS,aAAa,MAAM,GAAK,OAASP,EAAWS,MAAW,IAClE,GAA+BZ,EAAQU,EAAUP,CAAU,EAClE,IAAK,IAAMO,KAAaD,IAAQ,SAAW,SAAW,SAAS,KAAA,CAAM,iBAAiBA,CAAG,EACvF,GAAID,EAAKE,CAAQ,EAAG,OAEtB,IAAMN,EAAU,SAAS,cAAcK,CAAG,EAC1C,IAAK,GAAM,CAACR,EAAMC,KAAU,OAAO,QAAQC,CAAU,EAAGC,EAAQ,aAAaH,EAAMC,CAAK,EACxF,SAAS,KAAK,OAAOE,CAAO,CAC9B,CAGA,SAASS,EAAW,EAAsE,CACxF,UAAaC,EAAQ,CAAE,IAAK,OAAQ,MAAOX,CAAW,CAAC,CACzD,CAoBA,SAAgBY,EAAW,EAAc,EAAoC,CAC3ElB,EAASE,CAAI,EACb,IAAMI,EAAyB,CAC7B,IAAK,aACL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AAIiB,EAAQ,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CAE1D,EAAGH,EAAW,CAAE,IAAK,UAAW,OAAM,GAAI,QAAS,CAAC,CAAC,CAC/E,CAkBA,SAAgBQ,EAAc,EAAc,EAAoC,CAC9ExB,EAASE,CAAI,EAMbM,EACE,SACA,CANA,IAAKN,EACL,KAAM,SACN,GAAIiB,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CAIxE,EACTH,EAAW,CACT,IAAK,gBACL,OACA,GAAIG,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CACnF,CAAC,CACH,CACF,C"}
1
+ {"version":3,"file":"resource-hints.js","names":["useHead","isServer","checkUrl","href","url","carries","element","attributes","name","value","hint","tag","serverTag","same","existing","\"src\"","\"type\"","serverLink","preconnect","options","prefetchDNS","preload","preloadModule","preinit","preinitModule"],"sources":["../../src/resource-hints.ts"],"sourcesContent":["import { isServer } from \"@shadow-js/core\";\nimport { useHead } from \"./head/use-head\";\nimport type { HeadAttributeValue } from \"./head/validate\";\n\n/**\n * Options of {@link preconnect}, {@link preloadModule} and {@link preinitModule}.\n * @since 1.0.0\n */\nexport interface CrossOriginOptions {\n /**\n * CORS mode of the connection or request: `\"anonymous\"` sends no credentials, `\"use-credentials\"`\n * sends cookies and client certificates. Fonts and `fetch` preloads need one of them.\n * @default undefined (no `crossorigin` attribute; the browser's default for the resource applies)\n */\n readonly crossOrigin?: \"anonymous\" | \"use-credentials\";\n}\n\n/**\n * Options of {@link preload}: the destination is required, as the browser needs it to pick the\n * right request.\n * @since 1.0.0\n */\nexport interface PreloadOptions extends CrossOriginOptions {\n /**\n * The destination of the request, which the browser uses to pick its priority and headers. It\n * must match how the resource is used later, or the preloaded copy is not reused.\n */\n readonly as:\n | \"audio\"\n | \"document\"\n | \"embed\"\n | \"fetch\"\n | \"font\"\n | \"image\"\n | \"object\"\n | \"script\"\n | \"style\"\n | \"track\"\n | \"video\"\n | \"worker\";\n /**\n * MIME type, so the browser can skip unsupported formats (for example `font/woff2`).\n * @default undefined (no `type` attribute)\n */\n readonly type?: string;\n /**\n * Media query the hint applies to (for example `(min-width: 800px)`); the browser skips the\n * preload when it does not match.\n * @default undefined (no `media` attribute; the hint always applies)\n */\n readonly media?: string;\n}\n\n/**\n * Options of {@link preinit}.\n * @since 1.0.0\n */\nexport interface PreinitOptions extends CrossOriginOptions {\n /**\n * What to load: `\"style\"` inserts a stylesheet, `\"script\"` inserts an async script. Required, as\n * the two produce different elements.\n */\n readonly as: \"style\" | \"script\";\n}\n\ntype Attributes = Readonly<Record<string, string>>;\n\n/** Hints are page-level and only ever use http(s) URLs; anything else throws, like head tags do. */\nfunction checkUrl(href: string): void {\n const url = new URL(href, \"https://base.invalid\");\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\n __DEV__\n ? `resource hint: \"${href}\" must be an http(s) or relative URL`\n : \"SHADOW_RESOURCE_HINT_URL\",\n );\n }\n}\n\n/** Whether an element already carries every attribute of a hint (so the hint is already there). */\nfunction carries(element: Element, attributes: Attributes): boolean {\n for (const [name, value] of Object.entries(attributes)) {\n if (element.getAttribute(name) !== value) return false;\n }\n return true;\n}\n\n/**\n * Inserts a hint element once: an identical element already in the head (server-rendered or added\n * earlier) is kept, and a script already anywhere in the document with the same `src` and `type` is\n * not loaded again. On the server the hint joins the render's head collector, when there is one.\n */\nfunction hint(\n tag: \"link\" | \"script\",\n attributes: Attributes,\n serverTag: () => void = () => undefined,\n): void {\n if (isServer) {\n serverTag();\n return;\n }\n if (typeof document === \"undefined\") return;\n // A script is the same load when its URL and kind match: the page's own bundle usually sits at the end\n // of the body, and carries `defer` or `async` or neither, so the attributes of the hint are no test.\n const same =\n tag === \"script\"\n ? (existing: Element): boolean =>\n existing.getAttribute(\"src\") === attributes[\"src\"] &&\n (existing.getAttribute(\"type\") ?? \"\") === (attributes[\"type\"] ?? \"\")\n : (existing: Element): boolean => carries(existing, attributes);\n for (const existing of (tag === \"script\" ? document : document.head).querySelectorAll(tag)) {\n if (same(existing)) return;\n }\n const element = document.createElement(tag);\n for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);\n document.head.append(element);\n}\n\n/** Server form of a hint: a head link (scripts cannot be head tags, see {@link preinitModule}). */\nfunction serverLink(attributes: Readonly<Record<string, HeadAttributeValue>>): () => void {\n return () => useHead({ tag: \"link\", props: attributes });\n}\n\n/**\n * Tells the browser to open a connection (DNS, TCP, TLS) to an origin the page will use soon.\n * React's `preconnect`. Calling it again for the same origin adds nothing. Works in a component, in\n * an event handler, or at module scope on the client.\n *\n * @param href An http(s) origin or URL.\n * @param options CORS mode (needed for fonts and fetch with credentials). Undefined adds no\n * `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or\n * relative.\n * @example\n * import { preconnect } from \"@shadow-js/web\";\n *\n * preconnect(\"https://fonts.example.com\", { crossOrigin: \"anonymous\" });\n * @see prefetchDNS\n * @see preload\n * @since 1.0.0\n */\nexport function preconnect(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preconnect\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Resolves an origin's DNS ahead of use. Cheaper than {@link preconnect}; React's `prefetchDNS`.\n * @param href An http(s) origin or URL.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { prefetchDNS } from \"@shadow-js/web\";\n *\n * prefetchDNS(\"https://api.example.com\");\n * @see preconnect\n * @since 1.0.0\n */\nexport function prefetchDNS(href: string): void {\n checkUrl(href);\n const attributes: Attributes = { rel: \"dns-prefetch\", href };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts fetching a resource the page will need, at high priority. The browser stores it for the\n * later request with the same URL and destination (React's `preload`).\n *\n * @param href An http(s) or relative URL.\n * @param options The destination (`as`, required) and the optional type, media and CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preload } from \"@shadow-js/web\";\n *\n * preload(\"/fonts/inter.woff2\", { as: \"font\", type: \"font/woff2\", crossOrigin: \"anonymous\" });\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preload(href: string, options: PreloadOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"preload\",\n href,\n as: options.as,\n ...(options.type === undefined ? {} : { type: options.type }),\n ...(options.media === undefined ? {} : { media: options.media }),\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Starts loading an ES module the page will import, so the import does not wait for the module\n * graph to be discovered. React's `preloadModule`.\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preloadModule } from \"@shadow-js/web\";\n *\n * preloadModule(\"/chunks/editor.js\");\n * @see preinitModule\n * @see preload\n * @since 1.0.0\n */\nexport function preloadModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n}\n\n/**\n * Loads a stylesheet or script now, and keeps it applied or executed (React's `preinit`). A\n * stylesheet becomes a `<link rel=\"stylesheet\">`; a script becomes an async `<script>` in the head.\n * On the server a script can only be hinted as a preload, because head tags cannot be scripts.\n *\n * @param href An http(s) or relative URL.\n * @param options What to load (`style` or `script`, required) and the CORS mode.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinit } from \"@shadow-js/web\";\n *\n * preinit(\"/theme.css\", { as: \"style\" });\n * @see preload\n * @see preinitModule\n * @since 1.0.0\n */\nexport function preinit(href: string, options: PreinitOptions): void {\n checkUrl(href);\n if (options.as === \"style\") {\n const attributes: Attributes = {\n rel: \"stylesheet\",\n href,\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"link\", attributes, serverLink(attributes));\n return;\n }\n const attributes: Attributes = {\n src: href,\n async: \"\",\n ...(options.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\"script\", attributes, serverLink({ rel: \"preload\", href, as: \"script\" }));\n}\n\n/**\n * Loads and runs an ES module now (React's `preinitModule`). On the client it inserts a\n * `<script type=\"module\">`; on the server it hints the module with `modulepreload`, since the\n * script itself is loaded by the page.\n *\n * @param href An http(s) or relative URL of the module.\n * @param options CORS mode. Undefined adds no `crossorigin` attribute.\n * @throws TypeError (production message `SHADOW_RESOURCE_HINT_URL`) for a URL that is not http(s) or relative.\n * @example\n * import { preinitModule } from \"@shadow-js/web\";\n *\n * preinitModule(\"/chunks/app.js\");\n * @see preloadModule\n * @see preinit\n * @since 1.0.0\n */\nexport function preinitModule(href: string, options?: CrossOriginOptions): void {\n checkUrl(href);\n const attributes: Attributes = {\n src: href,\n type: \"module\",\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n };\n hint(\n \"script\",\n attributes,\n serverLink({\n rel: \"modulepreload\",\n href,\n ...(options?.crossOrigin === undefined ? {} : { crossorigin: options.crossOrigin }),\n }),\n );\n}\n"],"mappings":"A,wFAoEA,SAASE,EAASC,EAAoB,CACpC,IAAMC,EAAM,IAAI,IAAID,EAAM,sBAAsB,EAChD,GAAIC,EAAI,WAAa,UAAYA,EAAI,WAAa,QAChD,MAAU,UAGJ,0BACN,CAEJ,CAGA,SAASC,EAAQC,EAAkBC,EAAiC,CAClE,IAAK,GAAM,CAACC,E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CACT,IAAK,gBACLd,OACA,GAAIgB,GAAS,cAAgB,IAAA,GAAY,CAAC,EAAI,CAAE,YAAaA,EAAQ,WAAY,CACnF,CAAC,CACH,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"select-value.js","names":["bound","listed","value","item","plainText","setSelectValue","select","keepWatchingCommits","apply","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["import { keepWatchingCommits } from \"./insert\";\n\n/** The value each select was last given, which it takes again when its options change (see {@link setSelectValue}). */\nconst bound = new WeakMap<HTMLSelectElement, unknown>();\n\n/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`). The select\n * takes the value again whenever the nodes inside it change (the options of a `<For>`, a `<Show>` or an optgroup), so\n * options that arrive or are replaced after the value keep it selected.\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n // Options that arrive or are replaced after this call (a `<For>` inside the select) leave the browser's own pick, the\n // first option: the select takes its value again after each commit to its children, as React's does.\n if (!bound.has(select)) keepWatchingCommits(select, () => apply(select, bound.get(select)));\n bound.set(select, value);\n apply(select, value);\n}\n\nfunction apply(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"A,kDAGA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAO,EAAwC,CACtD,OAAO,IAAI,IAAIC,EAAM,OAAQ,GAASC,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAU,EAAwB,CAChD,OAAOF,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAwBA,SAAgBG,EAAe,EAA2B,EAAsB,CAGzEL,EAAM,IAAIM,CAAM,GAAGC,EAAoBD,MAAcE,EAAMF,EAAQN,EAAM,IAAIM,CAAM,CAAC,CAAC,EAC1FN,EAAM,IAAIM,EAAQJ,CAAK,EACvBM,EAAMF,EAAQJ,CAAK,CACrB,CAEA,SAASM,EAAM,EAA2B,EAAsB,CAC9D,GAAIF,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMO,EAASR,EAAOC,CAAK,EAC3B,IAAK,IAAMQ,KAAU,MAAM,KAAKJ,EAAO,OAAO,EAAG,EAAO,SAAWG,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACA,GAAO,MAAQN,EAAUF,CAAK,CAChC,C"}
1
+ {"version":3,"file":"select-value.js","names":["keepWatchingCommits","bound","listed","value","item","plainText","setSelectValue","select","apply","wanted","option"],"sources":["../../src/select-value.ts"],"sourcesContent":["import { keepWatchingCommits } from \"./insert\";\n\n/** The value each select was last given, which it takes again when its options change (see {@link setSelectValue}). */\nconst bound = new WeakMap<HTMLSelectElement, unknown>();\n\n/** The values an array stands for, as strings; null and undefined entries are skipped. */\nfunction listed(value: readonly unknown[]): Set<string> {\n return new Set(value.filter((item) => item !== null && item !== undefined).map(String));\n}\n\n/** The string a value assigns to `select.value`, `innerHTML` or `textContent`; null and undefined are empty. @internal */\nexport function plainText(value: unknown): string {\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Selects the options a `value` stands for. The compiler calls it for `<select value={...}>`. A\n * single value behaves like `select.value = value` (`null` and `undefined` are the empty string).\n * On a `<select multiple>` an array selects exactly the options whose value it lists and clears\n * the others. The server writes the same state as `selected` on the options (`ssrSelectValue`). The select\n * takes the value again whenever the nodes inside it change (the options of a `<For>`, a `<Show>` or an optgroup), so\n * options that arrive or are replaced after the value keep it selected.\n *\n * @param select The select element; its options must already be in it.\n * @param value A string or number (written as `String(value)`), or `null`/`undefined` (written as\n * `\"\"`: an option with an empty value is selected, otherwise none). For a `multiple` select, an array of them: `null` and `undefined`\n * entries are skipped. An array on a single select is written as `String(array)`.\n * @example\n * import { setSelectValue } from \"@shadow-js/web\";\n *\n * const select = document.createElement(\"select\");\n * select.multiple = true;\n * select.append(new Option(\"A\", \"a\"), new Option(\"B\", \"b\"), new Option(\"C\", \"c\"));\n * setSelectValue(select, [\"a\", \"c\"]); // A and C selected, B cleared\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function setSelectValue(select: HTMLSelectElement, value: unknown): void {\n // Options that arrive or are replaced after this call (a `<For>` inside the select) leave the browser's own pick, the\n // first option: the select takes its value again after each commit to its children, as React's does.\n if (!bound.has(select)) keepWatchingCommits(select, () => apply(select, bound.get(select)));\n bound.set(select, value);\n apply(select, value);\n}\n\nfunction apply(select: HTMLSelectElement, value: unknown): void {\n if (select.multiple && Array.isArray(value)) {\n const wanted = listed(value);\n for (const option of Array.from(select.options)) option.selected = wanted.has(option.value);\n return;\n }\n select.value = plainText(value);\n}\n"],"mappings":"A,kDAGA,MAAMC,kBAAQ,IAAI,QAGlB,SAASC,EAAOC,EAAwC,CACtD,OAAO,IAAI,IAAIA,EAAM,OAAQC,GAASA,GAAS,IAA0B,CAAC,CAAC,IAAI,MAAM,CAAC,CACxF,CAGA,SAAgBC,EAAUF,EAAwB,CAChD,OAAOA,GAAU,KAA8B,GAAK,OAAOA,CAAK,CAClE,CAwBA,SAAgBG,EAAeC,EAA2BJ,EAAsB,CAGzEF,EAAM,IAAIM,CAAM,GAAGP,EAAoBO,MAAcC,EAAMD,EAAQN,EAAM,IAAIM,CAAM,CAAC,CAAC,EAC1FN,EAAM,IAAIM,EAAQJ,CAAK,EACvBK,EAAMD,EAAQJ,CAAK,CACrB,CAEA,SAASK,EAAMD,EAA2BJ,EAAsB,CAC9D,GAAII,EAAO,UAAY,MAAM,QAAQJ,CAAK,EAAG,CAC3C,IAAMM,EAASP,EAAOC,CAAK,EAC3B,IAAK,IAAMO,KAAU,MAAM,KAAKH,EAAO,OAAO,EAAGG,EAAO,SAAWD,EAAO,IAAIC,EAAO,KAAK,CAE5F,KACAH,GAAO,MAAQF,EAAUF,CAAK,CAChC,C"}