@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":"components.js","names":["partText","value","textOf","resolved","keyOf","attributeValue","attributesOf","entries","key","props","skip","attributeTag","Title","useHead","Meta","Link","Style","attributes","text","Base"],"sources":["../../../src/head/components.ts"],"sourcesContent":["import { useHead } from \"./use-head\";\nimport type { HeadAttributeValue, HeadTag, HeadTagName } from \"./validate\";\n\n/**\n * Props of {@link Title}.\n * @since 1.0.0\n */\nexport interface TitleProps {\n /**\n * The title text: a string, a number, an array of those, or an accessor returning them. `null`,\n * `undefined` and `false` count as empty text; anything else throws a TypeError.\n * @default undefined (the title is the empty string)\n */\n readonly children?: unknown;\n}\n\n/**\n * Props of {@link Meta}, {@link Link} and {@link Base}: every prop is an attribute, and a function\n * value is read reactively.\n * @since 1.0.0\n */\nexport interface HeadAttributeProps {\n /**\n * One attribute of the tag. A string or number is written as text, `true` as an empty attribute,\n * and `false`, `null` or `undefined` omit it. Any other value throws a TypeError.\n */\n readonly [attribute: string]: unknown;\n}\n\n/**\n * Props of {@link Style}: the CSS text and an optional key that replaces an earlier style with the\n * same key.\n * @since 1.0.0\n */\nexport interface StyleProps {\n /**\n * The CSS text: a string, a number, an array of those, or an accessor returning them.\n * @default undefined (the style has no text)\n */\n readonly children?: unknown;\n /**\n * Identity of the style: a later style with the same key replaces an earlier one. Must be a\n * non-empty string.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: unknown;\n /** One attribute of the `<style>` element, such as `media`, with the same rules as {@link HeadAttributeProps}. */\n readonly [attribute: string]: unknown;\n}\n\n/** Text of a value that may be an accessor. Anything but text or an array of text throws. */\nfunction partText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n if (value === undefined || value === null || value === false) return \"\";\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: Title children must be text.\" : \"SHADOW_HEAD_TITLE_TEXT\",\n );\n}\n\n/** The text a Title shows. An accessor is called once, so its reads are tracked by the caller. */\nfunction textOf(value: unknown): string {\n const resolved = typeof value === \"function\" ? (value as () => unknown)() : value;\n if (Array.isArray(resolved)) return (resolved as unknown[]).map(partText).join(\"\");\n return partText(resolved);\n}\n\n/** The style key of a prop: absent stays absent, a non-empty string is kept, anything else throws. */\nfunction keyOf(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\" && value !== \"\") return value;\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n}\n\n/** One attribute value from a prop: strings, numbers and booleans are kept, the rest is an error. */\nfunction attributeValue(value: unknown): HeadAttributeValue {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return true;\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return value;\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * The attributes of a component's props, reading each prop (so a getter is tracked by the\n * caller). `skip` lists props that are not attributes.\n */\nfunction attributesOf(props: object, skip: readonly string[]): Record<string, HeadAttributeValue> {\n const entries: Array<[string, HeadAttributeValue]> = [];\n for (const key of Object.keys(props)) {\n if (skip.includes(key)) continue;\n entries.push([key, attributeValue(Reflect.get(props, key))]);\n }\n return Object.fromEntries(entries);\n}\n\n/** A tag with attributes and no text, of the given name. */\nfunction attributeTag(tag: HeadTagName, props: object, skip: readonly string[]): HeadTag {\n return { tag, props: attributesOf(props, skip) };\n}\n\n/**\n * Sets the document title. The last registered Title wins; removing it restores the one below, or\n * the original title when none is left.\n *\n * @param props The title text.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_TITLE_TEXT`) when the children are not text.\n * @example\n * import { Title } from \"@shadow-js/web\";\n *\n * function Home() {\n * return <Title>Home | Blog</Title>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Title(props: TitleProps): null {\n useHead((): HeadTag => ({ tag: \"title\", children: textOf(props.children) }));\n return null;\n}\n\n/**\n * Registers a `<meta>`. Identity follows name, property, http-equiv or charset, so the last\n * description wins. Children are ignored: a meta carries no text.\n *\n * @param props Attributes, such as `name` and `content`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Meta } from \"@shadow-js/web\";\n *\n * function About() {\n * return <Meta name=\"description\" content=\"About us\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Meta(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"meta\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<link>`. Icons are keyed by rel, sizes and type; preloads and stylesheets by rel,\n * href and as; other links are append-only.\n *\n * @param props Attributes, such as `rel` and `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Link } from \"@shadow-js/web\";\n *\n * function Page() {\n * return <Link rel=\"stylesheet\" href=\"/site.css\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Link(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"link\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<style>` with the given CSS text. A `key` makes it replace an earlier style with the\n * same key; without one, every style stays.\n *\n * @param props The CSS as `children`, an optional `key`, and attributes such as `media`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_KEY`) when `key` is not a non-empty string.\n * @example\n * import { Style } from \"@shadow-js/web\";\n *\n * function Theme() {\n * return <Style key=\"theme\">{\"body { margin: 0 }\"}</Style>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Style(props: StyleProps): null {\n useHead((): HeadTag => {\n const attributes = attributesOf(props, [\"children\", \"key\"]);\n const text = props.children === undefined ? undefined : textOf(props.children);\n const key = keyOf(props.key);\n return {\n tag: \"style\",\n props: attributes,\n ...(text === undefined ? {} : { children: text }),\n ...(key === undefined ? {} : { key }),\n };\n });\n return null;\n}\n\n/**\n * Registers the document `<base>`. There is one; the last registration wins. Base is placed first\n * in the head, as browsers expect.\n *\n * @param props Attributes, such as `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean.\n * @example\n * import { Base } from \"@shadow-js/web\";\n *\n * function Shell() {\n * return <Base href=\"/app/\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Base(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"base\", props, [\"children\"]));\n return null;\n}\n"],"mappings":"A,wCAmDA,SAASA,EAAS,EAAwB,CACxC,GAAI,OAAOC,GAAU,SAAU,OAAOA,EACtC,GAAI,OAAOA,GAAU,SAAU,OAAO,OAAOA,CAAK,EAClD,GAAIA,GAAiC,MAAQA,IAAU,GAAO,MAAO,GACrE,MAAU,UACkD,wBAC5D,CACF,CAGA,SAASC,EAAO,EAAwB,CACtC,IAAMC,EAAW,OAAOF,GAAU,WAAcA,EAAwB,EAAIA,EAE5E,OADI,MAAM,QAAQE,CAAQ,EAAWA,EAAuB,IAAIH,CAAQ,CAAC,CAAC,KAAK,EAAE,EAC1EA,EAASG,CAAQ,CAC1B,CAGA,SAASC,EAAM,EAAoC,CACjD,GAAIH,GAAiC,KACrC,IAAI,OAAOA,GAAU,UAAYA,IAAU,GAAI,OAAOA,EACtD,MAAU,UACuD,iBACjE,CAHsD,CAIxD,CAGA,SAASI,EAAe,EAAoC,CAC1D,GAAIJ,GAAiC,MAAQA,IAAU,GACvD,IAAIA,IAAU,GAAM,MAAO,GAE3B,GADI,OAAOA,GAAU,UACjB,OAAOA,GAAU,SAAU,OAAOA,EACtC,MAAU,UAGJ,6BACN,CAP2B,CAQ7B,CAMA,SAASK,EAAa,EAAe,EAA6D,CAChG,IAAMC,EAA+C,CAAC,EACtD,IAAK,IAAMC,KAAO,OAAO,KAAKC,CAAK,EAC7BC,EAAK,SAASF,CAAG,GACrBD,EAAQ,KAAK,CAACC,EAAKH,EAAe,QAAQ,IAAII,EAAOD,CAAG,CAAC,CAAC,CAAC,EAE7D,OAAO,OAAO,YAAYD,CAAO,CACnC,CAGA,SAASI,EAAa,EAAkB,EAAe,EAAkC,CACvF,MAAO,CAAE,MAAK,MAAOL,EAAaG,EAAOC,CAAI,CAAE,CACjD,CAkBA,SAAgBE,EAAM,EAAyB,CAE7C,OADAC,OAAwB,CAAE,IAAK,QAAS,SAAUX,EAAOO,EAAM,QAAQ,CAAE,EAAE,EACpE,IACT,CAoBA,SAAgBK,EAAK,EAAiC,CAEpD,OADAD,MAAcF,EAAa,OAAQF,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,CAoBA,SAAgBM,EAAK,EAAiC,CAEpD,OADAF,MAAcF,EAAa,OAAQF,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,CAkBA,SAAgBO,EAAM,EAAyB,CAY7C,OAXAH,MAAuB,CACrB,IAAMI,EAAaX,EAAaG,EAAO,CAAC,WAAY,KAAK,CAAC,EACpDS,EAAOT,EAAM,WAAa,IAAA,GAAY,IAAA,GAAYP,EAAOO,EAAM,QAAQ,EACvED,EAAMJ,EAAMK,EAAM,GAAG,EAC3B,MAAO,CACL,IAAK,QACL,MAAOQ,EACP,GAAIC,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,SAAUA,CAAK,EAC/C,GAAIV,IAAQ,IAAA,GAAY,CAAC,EAAI,CAAE,KAAI,CACrC,CACF,CAAC,EACM,IACT,CAmBA,SAAgBW,EAAK,EAAiC,CAEpD,OADAN,MAAcF,EAAa,OAAQF,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,C"}
1
+ {"version":3,"file":"components.js","names":["useHead","partText","value","textOf","resolved","keyOf","attributeValue","attributesOf","props","skip","entries","key","attributeTag","tag","Title","Meta","Link","Style","attributes","text","Base"],"sources":["../../../src/head/components.ts"],"sourcesContent":["import { useHead } from \"./use-head\";\nimport type { HeadAttributeValue, HeadTag, HeadTagName } from \"./validate\";\n\n/**\n * Props of {@link Title}.\n * @since 1.0.0\n */\nexport interface TitleProps {\n /**\n * The title text: a string, a number, an array of those, or an accessor returning them. `null`,\n * `undefined` and `false` count as empty text; anything else throws a TypeError.\n * @default undefined (the title is the empty string)\n */\n readonly children?: unknown;\n}\n\n/**\n * Props of {@link Meta}, {@link Link} and {@link Base}: every prop is an attribute, and a function\n * value is read reactively.\n * @since 1.0.0\n */\nexport interface HeadAttributeProps {\n /**\n * One attribute of the tag. A string or number is written as text, `true` as an empty attribute,\n * and `false`, `null` or `undefined` omit it. Any other value throws a TypeError.\n */\n readonly [attribute: string]: unknown;\n}\n\n/**\n * Props of {@link Style}: the CSS text and an optional key that replaces an earlier style with the\n * same key.\n * @since 1.0.0\n */\nexport interface StyleProps {\n /**\n * The CSS text: a string, a number, an array of those, or an accessor returning them.\n * @default undefined (the style has no text)\n */\n readonly children?: unknown;\n /**\n * Identity of the style: a later style with the same key replaces an earlier one. Must be a\n * non-empty string.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: unknown;\n /** One attribute of the `<style>` element, such as `media`, with the same rules as {@link HeadAttributeProps}. */\n readonly [attribute: string]: unknown;\n}\n\n/** Text of a value that may be an accessor. Anything but text or an array of text throws. */\nfunction partText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n if (value === undefined || value === null || value === false) return \"\";\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: Title children must be text.\" : \"SHADOW_HEAD_TITLE_TEXT\",\n );\n}\n\n/** The text a Title shows. An accessor is called once, so its reads are tracked by the caller. */\nfunction textOf(value: unknown): string {\n const resolved = typeof value === \"function\" ? (value as () => unknown)() : value;\n if (Array.isArray(resolved)) return (resolved as unknown[]).map(partText).join(\"\");\n return partText(resolved);\n}\n\n/** The style key of a prop: absent stays absent, a non-empty string is kept, anything else throws. */\nfunction keyOf(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\" && value !== \"\") return value;\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n}\n\n/** One attribute value from a prop: strings, numbers and booleans are kept, the rest is an error. */\nfunction attributeValue(value: unknown): HeadAttributeValue {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return true;\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return value;\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * The attributes of a component's props, reading each prop (so a getter is tracked by the\n * caller). `skip` lists props that are not attributes.\n */\nfunction attributesOf(props: object, skip: readonly string[]): Record<string, HeadAttributeValue> {\n const entries: Array<[string, HeadAttributeValue]> = [];\n for (const key of Object.keys(props)) {\n if (skip.includes(key)) continue;\n entries.push([key, attributeValue(Reflect.get(props, key))]);\n }\n return Object.fromEntries(entries);\n}\n\n/** A tag with attributes and no text, of the given name. */\nfunction attributeTag(tag: HeadTagName, props: object, skip: readonly string[]): HeadTag {\n return { tag, props: attributesOf(props, skip) };\n}\n\n/**\n * Sets the document title. The last registered Title wins; removing it restores the one below, or\n * the original title when none is left.\n *\n * @param props The title text.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_TITLE_TEXT`) when the children are not text.\n * @example\n * import { Title } from \"@shadow-js/web\";\n *\n * function Home() {\n * return <Title>Home | Blog</Title>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Title(props: TitleProps): null {\n useHead((): HeadTag => ({ tag: \"title\", children: textOf(props.children) }));\n return null;\n}\n\n/**\n * Registers a `<meta>`. Identity follows name, property, http-equiv or charset, so the last\n * description wins. Children are ignored: a meta carries no text.\n *\n * @param props Attributes, such as `name` and `content`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Meta } from \"@shadow-js/web\";\n *\n * function About() {\n * return <Meta name=\"description\" content=\"About us\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Meta(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"meta\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<link>`. Icons are keyed by rel, sizes and type; preloads and stylesheets by rel,\n * href and as; other links are append-only.\n *\n * @param props Attributes, such as `rel` and `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Link } from \"@shadow-js/web\";\n *\n * function Page() {\n * return <Link rel=\"stylesheet\" href=\"/site.css\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Link(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"link\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<style>` with the given CSS text. A `key` makes it replace an earlier style with the\n * same key; without one, every style stays.\n *\n * @param props The CSS as `children`, an optional `key`, and attributes such as `media`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_KEY`) when `key` is not a non-empty string.\n * @example\n * import { Style } from \"@shadow-js/web\";\n *\n * function Theme() {\n * return <Style key=\"theme\">{\"body { margin: 0 }\"}</Style>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Style(props: StyleProps): null {\n useHead((): HeadTag => {\n const attributes = attributesOf(props, [\"children\", \"key\"]);\n const text = props.children === undefined ? undefined : textOf(props.children);\n const key = keyOf(props.key);\n return {\n tag: \"style\",\n props: attributes,\n ...(text === undefined ? {} : { children: text }),\n ...(key === undefined ? {} : { key }),\n };\n });\n return null;\n}\n\n/**\n * Registers the document `<base>`. There is one; the last registration wins. Base is placed first\n * in the head, as browsers expect.\n *\n * @param props Attributes, such as `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean.\n * @example\n * import { Base } from \"@shadow-js/web\";\n *\n * function Shell() {\n * return <Base href=\"/app/\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Base(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"base\", props, [\"children\"]));\n return null;\n}\n"],"mappings":"A,wCAmDA,SAASC,EAASC,EAAwB,CACxC,GAAI,OAAOA,GAAU,SAAU,OAAOA,EACtC,GAAI,OAAOA,GAAU,SAAU,OAAO,OAAOA,CAAK,EAClD,GAAIA,GAAiC,MAAQA,IAAU,GAAO,MAAO,GACrE,MAAU,UACkD,wBAC5D,CACF,CAGA,SAASC,EAAOD,EAAwB,CACtC,IAAME,EAAW,OAAOF,GAAU,WAAcA,EAAwB,EAAIA,EAE5E,OADI,MAAM,QAAQE,CAAQ,EAAWA,EAAuB,IAAIH,CAAQ,CAAC,CAAC,KAAK,EAAE,EAC1EA,EAASG,CAAQ,CAC1B,CAGA,SAASC,EAAMH,EAAoC,CACjD,GAAIA,GAAiC,KACrC,IAAI,OAAOA,GAAU,UAAYA,IAAU,GAAI,OAAOA,EACtD,MAAU,UACuD,iBACjE,CAHsD,CAIxD,CAGA,SAASI,EAAeJ,EAAoC,CAC1D,GAAIA,GAAiC,MAAQA,IAAU,GACvD,IAAIA,IAAU,GAAM,MAAO,GAE3B,GADI,OAAOA,GAAU,UACjB,OAAOA,GAAU,SAAU,OAAOA,EACtC,MAAU,UAGJ,6BACN,CAP2B,CAQ7B,CAMA,SAASK,EAAaC,EAAeC,EAA6D,CAChG,IAAMC,EAA+C,CAAC,EACtD,IAAK,IAAMC,KAAO,OAAO,KAAKH,CAAK,EAC7BC,EAAK,SAASE,CAAG,GACrBD,EAAQ,KAAK,CAACC,EAAKL,EAAe,QAAQ,IAAIE,EAAOG,CAAG,CAAC,CAAC,CAAC,EAE7D,OAAO,OAAO,YAAYD,CAAO,CACnC,CAGA,SAASE,EAAaC,EAAkBL,EAAeC,EAAkC,CACvF,MAAO,CAAEI,MAAK,MAAON,EAAaC,EAAOC,CAAI,CAAE,CACjD,CAkBA,SAAgBK,EAAMN,EAAyB,CAE7C,OADAR,OAAwB,CAAE,IAAK,QAAS,SAAUG,EAAOK,EAAM,QAAQ,CAAE,EAAE,EACpE,IACT,CAoBA,SAAgBO,EAAKP,EAAiC,CAEpD,OADAR,MAAcY,EAAa,OAAQJ,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,CAoBA,SAAgBQ,EAAKR,EAAiC,CAEpD,OADAR,MAAcY,EAAa,OAAQJ,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,CAkBA,SAAgBS,EAAMT,EAAyB,CAY7C,OAXAR,MAAuB,CACrB,IAAMkB,EAAaX,EAAaC,EAAO,CAAC,WAAY,KAAK,CAAC,EACpDW,EAAOX,EAAM,WAAa,IAAA,GAAY,IAAA,GAAYL,EAAOK,EAAM,QAAQ,EACvEG,EAAMN,EAAMG,EAAM,GAAG,EAC3B,MAAO,CACL,IAAK,QACL,MAAOU,EACP,GAAIC,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,SAAUA,CAAK,EAC/C,GAAIR,IAAQ,IAAA,GAAY,CAAC,EAAI,CAAEA,KAAI,CACrC,CACF,CAAC,EACM,IACT,CAmBA,SAAgBS,EAAKZ,EAAiC,CAEpD,OADAR,MAAcY,EAAa,OAAQJ,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"registry.js","names":["noop","createHeadRegistry","stacks","appendOnly","tags","entries","tag","slot","stack","entry","onChange","removed","index","winners","top"],"sources":["../../../src/head/registry.ts"],"sourcesContent":["import type { NormalizedTag } from \"./validate\";\n\n/**\n * One rendered head element: the slot it occupies (its identity, or a unique key for an\n * append-only tag) and the tag that currently wins that slot.\n * @internal\n */\nexport interface HeadWinner {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\n/**\n * The pure head registry: no DOM, no signals. Every registration joins the stack of its identity;\n * the top of each stack is the winner. Removing a registration takes it out of its stack, so the\n * one below it wins again.\n * @internal\n */\nexport interface HeadRegistry {\n /**\n * Registers a group of tags. The returned function removes them again; calling it twice is a\n * no-op.\n */\n add(tags: readonly NormalizedTag[]): () => void;\n /** The winning tag of every slot, in the order each slot first appeared. */\n winners(): HeadWinner[];\n}\n\ninterface Entry {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\nconst noop = (): void => undefined;\n\n/**\n * Creates an empty head registry. `onChange` runs after every effective add or removal, so the\n * owner of the DOM can schedule one update for a whole batch.\n *\n * @param onChange Called after the registry changes.\n * @returns A registry with no winners.\n * @internal\n * @since 1.0.0\n */\nexport function createHeadRegistry(onChange: () => void): HeadRegistry {\n const stacks = new Map<string, Entry[]>();\n let appendOnly = 0;\n return {\n add(tags: readonly NormalizedTag[]): () => void {\n if (tags.length === 0) return noop;\n const entries: Entry[] = [];\n for (const tag of tags) {\n let slot = tag.identity;\n if (slot === undefined) {\n slot = `#${appendOnly}`;\n appendOnly += 1;\n }\n let stack = stacks.get(slot);\n if (stack === undefined) {\n stack = [];\n stacks.set(slot, stack);\n }\n const entry: Entry = { slot, tag };\n stack.push(entry);\n entries.push(entry);\n }\n onChange();\n let removed = false;\n return (): void => {\n if (removed) return;\n removed = true;\n for (const entry of entries) {\n const stack = stacks.get(entry.slot);\n if (stack === undefined) continue;\n const index = stack.indexOf(entry);\n if (index !== -1) stack.splice(index, 1);\n if (stack.length === 0) stacks.delete(entry.slot);\n }\n onChange();\n };\n },\n winners(): HeadWinner[] {\n const winners: HeadWinner[] = [];\n for (const [slot, stack] of stacks) {\n const top = stack[stack.length - 1];\n if (top !== undefined) winners.push({ slot, tag: top.tag });\n }\n return winners;\n },\n };\n}\n"],"mappings":"AAiCA,MAAMA,MAAmB,IAAA,GAWzB,SAAgBC,EAAmB,EAAoC,CACrE,IAAMC,kBAAS,IAAI,IACfC,EAAa,EACjB,MAAO,CACL,IAAI,EAA4C,CAC9C,GAAIC,EAAK,SAAW,EAAG,OAAOJ,EAC9B,IAAMK,EAAmB,CAAC,EAC1B,IAAK,IAAMC,KAAOF,EAAM,CACtB,IAAIG,EAAOD,EAAI,SACXC,IAAS,IAAA,KACX,EAAO,IAAIJ,IACX,GAAc,GAEhB,IAAIK,EAAQN,EAAO,IAAIK,CAAI,EACvBC,IAAU,IAAA,KACZ,EAAQ,CAAC,EACTN,EAAO,IAAIK,EAAMC,CAAK,GAExB,IAAMC,EAAe,CAAE,OAAM,KAAI,EACjCD,EAAM,KAAKC,CAAK,EAChBJ,EAAQ,KAAKI,CAAK,CACpB,CACAC,EAAS,EACT,IAAIC,EAAU,GACd,UAAmB,CACjB,GAAI,GACJ,GAAU,GACV,IAAK,IAAMF,KAASJ,EAAS,CAC3B,IAAMG,EAAQN,EAAO,IAAIO,EAAM,IAAI,EACnC,GAAID,IAAU,IAAA,GAAW,SACzB,IAAMI,EAAQJ,EAAM,QAAQC,CAAK,EAC7BG,IAAU,IAAIJ,EAAM,OAAOI,EAAO,CAAC,EACnCJ,EAAM,SAAW,GAAGN,EAAO,OAAOO,EAAM,IAAI,CAClD,CACAC,EAAS,CARC,CASZ,CACF,EACA,SAAwB,CACtB,IAAMG,EAAwB,CAAC,EAC/B,IAAK,GAAM,CAACN,EAAMC,KAAUN,EAAQ,CAClC,IAAMY,EAAMN,EAAMA,EAAM,OAAS,GAC7BM,IAAQ,IAAA,IAAWD,EAAQ,KAAK,CAAE,OAAM,IAAKC,EAAI,GAAI,CAAC,CAC5D,CACA,OAAOD,CACT,CACF,CACF,C"}
1
+ {"version":3,"file":"registry.js","names":["noop","createHeadRegistry","onChange","stacks","appendOnly","tags","entries","tag","slot","stack","entry","removed","index","winners","top"],"sources":["../../../src/head/registry.ts"],"sourcesContent":["import type { NormalizedTag } from \"./validate\";\n\n/**\n * One rendered head element: the slot it occupies (its identity, or a unique key for an\n * append-only tag) and the tag that currently wins that slot.\n * @internal\n */\nexport interface HeadWinner {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\n/**\n * The pure head registry: no DOM, no signals. Every registration joins the stack of its identity;\n * the top of each stack is the winner. Removing a registration takes it out of its stack, so the\n * one below it wins again.\n * @internal\n */\nexport interface HeadRegistry {\n /**\n * Registers a group of tags. The returned function removes them again; calling it twice is a\n * no-op.\n */\n add(tags: readonly NormalizedTag[]): () => void;\n /** The winning tag of every slot, in the order each slot first appeared. */\n winners(): HeadWinner[];\n}\n\ninterface Entry {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\nconst noop = (): void => undefined;\n\n/**\n * Creates an empty head registry. `onChange` runs after every effective add or removal, so the\n * owner of the DOM can schedule one update for a whole batch.\n *\n * @param onChange Called after the registry changes.\n * @returns A registry with no winners.\n * @internal\n * @since 1.0.0\n */\nexport function createHeadRegistry(onChange: () => void): HeadRegistry {\n const stacks = new Map<string, Entry[]>();\n let appendOnly = 0;\n return {\n add(tags: readonly NormalizedTag[]): () => void {\n if (tags.length === 0) return noop;\n const entries: Entry[] = [];\n for (const tag of tags) {\n let slot = tag.identity;\n if (slot === undefined) {\n slot = `#${appendOnly}`;\n appendOnly += 1;\n }\n let stack = stacks.get(slot);\n if (stack === undefined) {\n stack = [];\n stacks.set(slot, stack);\n }\n const entry: Entry = { slot, tag };\n stack.push(entry);\n entries.push(entry);\n }\n onChange();\n let removed = false;\n return (): void => {\n if (removed) return;\n removed = true;\n for (const entry of entries) {\n const stack = stacks.get(entry.slot);\n if (stack === undefined) continue;\n const index = stack.indexOf(entry);\n if (index !== -1) stack.splice(index, 1);\n if (stack.length === 0) stacks.delete(entry.slot);\n }\n onChange();\n };\n },\n winners(): HeadWinner[] {\n const winners: HeadWinner[] = [];\n for (const [slot, stack] of stacks) {\n const top = stack[stack.length - 1];\n if (top !== undefined) winners.push({ slot, tag: top.tag });\n }\n return winners;\n },\n };\n}\n"],"mappings":"AAiCA,MAAMA,MAAmB,IAAA,GAWzB,SAAgBC,EAAmBC,EAAoC,CACrE,IAAMC,kBAAS,IAAI,IACfC,EAAa,EACjB,MAAO,CACL,IAAIC,EAA4C,CAC9C,GAAIA,EAAK,SAAW,EAAG,OAAOL,EAC9B,IAAMM,EAAmB,CAAC,EAC1B,IAAK,IAAMC,KAAOF,EAAM,CACtB,IAAIG,EAAOD,EAAI,SACXC,IAAS,IAAA,KACXA,EAAO,IAAIJ,IACXA,GAAc,GAEhB,IAAIK,EAAQN,EAAO,IAAIK,CAAI,EACvBC,IAAU,IAAA,KACZA,EAAQ,CAAC,EACTN,EAAO,IAAIK,EAAMC,CAAK,GAExB,IAAMC,EAAe,CAAEF,OAAMD,KAAI,EACjCE,EAAM,KAAKC,CAAK,EAChBJ,EAAQ,KAAKI,CAAK,CACpB,CACAR,EAAS,EACT,IAAIS,EAAU,GACd,UAAmB,CACjB,GAAIA,GACJA,GAAU,GACV,IAAK,IAAMD,KAASJ,EAAS,CAC3B,IAAMG,EAAQN,EAAO,IAAIO,EAAM,IAAI,EACnC,GAAID,IAAU,IAAA,GAAW,SACzB,IAAMG,EAAQH,EAAM,QAAQC,CAAK,EAC7BE,IAAU,IAAIH,EAAM,OAAOG,EAAO,CAAC,EACnCH,EAAM,SAAW,GAAGN,EAAO,OAAOO,EAAM,IAAI,CAClD,CACAR,EAAS,CARC,CASZ,CACF,EACA,SAAwB,CACtB,IAAMW,EAAwB,CAAC,EAC/B,IAAK,GAAM,CAACL,EAAMC,KAAUN,EAAQ,CAClC,IAAMW,EAAML,EAAMA,EAAM,OAAS,GAC7BK,IAAQ,IAAA,IAAWD,EAAQ,KAAK,CAAEL,OAAM,IAAKM,EAAI,GAAI,CAAC,CAC5D,CACA,OAAOD,CACT,CACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"server-head.js","names":["VOID_TAGS","ServerHeadContext","tagHtml","attributes","HEAD_MARKER","tag","HEAD_KEY","escapeHtml","name","value","text","nonce","createServerHead","registry","createHeadRegistry","tags","winner","options","runWithServerHead","head","fn","holder"],"sources":["../../../src/head/server-head.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\nimport { escapeHtml } from \"../server/escape\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, type NormalizedTag } from \"./validate\";\n\n/** Elements that never have content or a closing tag. */\nconst VOID_TAGS: ReadonlySet<string> = new Set([\"meta\", \"link\", \"base\"]);\n\n/**\n * The head of one server render: what `useHead`, `<Title>`, `<Meta>`, `<Link>`, `<Style>` and\n * `<Base>` registered while the app rendered. Pass it to a render function through its `head`\n * option, then write {@link ServerHead.html} into the document's `<head>`.\n *\n * Tags follow the same rules as in the browser: the last registration of an identity wins\n * (`title`, `meta` by name, ...), append-only tags all stay. Every tag carries the marker the\n * browser's head sink looks for, so the client adopts the server's elements instead of adding\n * duplicates.\n * @since 1.0.0\n */\nexport interface ServerHead {\n /** Registers tags. Used by `useHead`; the returned function removes them again. */\n add(tags: readonly NormalizedTag[]): () => void;\n /** Forgets every registration. Multi-pass renders call this before each pass. */\n clear(): void;\n /**\n * The markup of the winning tags, in registration order. With a `nonce`, every `<style>` carries\n * it, so the page's Content-Security-Policy (`style-src 'nonce-...'`) accepts the styles. Throws a\n * TypeError when the text of a style contains a closing style tag.\n *\n * @param options `nonce` is added to every `<style>`. Default: no options, so no nonce.\n */\n html(options?: { readonly nonce?: string }): string;\n /** The winning tags, for hosts that build the head themselves. */\n tags(): readonly NormalizedTag[];\n}\n\n/** The collector `useHead` writes to while a render is running; null outside a render with `head`. @internal */\nexport const ServerHeadContext: Context<ServerHead | null> =\n /* @__PURE__ */ createContext<ServerHead | null>(null, { name: \"ServerHead\" });\n\n/** Markup of one tag. Text and attribute values are escaped; `</style` cannot appear in a style. */\nfunction tagHtml(tag: NormalizedTag, nonce: string | undefined): string {\n let attributes = ` ${HEAD_MARKER}`;\n if (tag.key !== undefined) attributes += ` ${HEAD_KEY}=\"${escapeHtml(tag.key)}\"`;\n for (const [name, value] of tag.attributes) {\n attributes += value === \"\" ? ` ${name}` : ` ${name}=\"${escapeHtml(value)}\"`;\n }\n if (VOID_TAGS.has(tag.tag)) return `<${tag.tag}${attributes}>`;\n const text = tag.text ?? \"\";\n if (tag.tag === \"style\") {\n if (/<\\/style/i.test(text)) {\n throw new TypeError(\"ShadowJS head: style text may not contain a closing style tag.\");\n }\n const withNonce =\n nonce === undefined ? attributes : `${attributes} nonce=\"${escapeHtml(nonce)}\"`;\n return `<style${withNonce}>${text}</style>`;\n }\n return `<${tag.tag}${attributes}>${escapeHtml(text)}</${tag.tag}>`;\n}\n\n/**\n * Creates an empty server head collector.\n *\n * @returns A collector to pass as the `head` option of `renderToString`, `renderToStringAsync` or\n * `renderToStream`.\n * @example\n * import { createComponent, Title } from \"@shadow-js/web\";\n * import { createServerHead, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return Title({ children: \"Home\" });\n * }\n *\n * const head = createServerHead();\n * const html = renderToString(() => createComponent(App, {}), { head });\n * const page = `<!doctype html><head>${head.html()}</head><body>${html}</body>`;\n * @see useHead\n * @since 1.0.0\n */\nexport function createServerHead(): ServerHead {\n let registry: HeadRegistry = createHeadRegistry(() => undefined);\n return {\n add: (tags) => registry.add(tags),\n clear() {\n registry = createHeadRegistry(() => undefined);\n },\n html: (options) =>\n registry\n .winners()\n .map((winner) => tagHtml(winner.tag, options?.nonce))\n .join(\"\"),\n tags: () => registry.winners().map((winner) => winner.tag),\n };\n}\n\n/**\n * Runs `fn` with `head` as the collector `useHead` writes to. Server renderers call it around the\n * app; with no collector `fn` runs as is. @internal\n */\nexport function runWithServerHead<T>(head: ServerHead | undefined, fn: () => T): T {\n if (head === undefined) return fn();\n const holder: { value?: T } = {};\n ServerHeadContext({\n value: head,\n get children() {\n holder.value = fn();\n return null;\n },\n });\n return holder.value as T;\n}\n"],"mappings":"A,8MAMA,MAAMA,kBAAiC,IAAI,IAAI,CAAC,OAAQ,OAAQ,MAAM,CAAC,EA+B1DC,EACK,kBAAiC,KAAM,CAAE,KAAM,YAAa,CAAC,EAG/E,SAASC,EAAQ,EAAoB,EAAmC,CACtE,IAAIC,EAAa,IAAIC,IACjBC,EAAI,MA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","HEAD_KEY","HEAD_MARKER","createContext","VOID_TAGS","ServerHeadContext","tagHtml","tag","nonce","attributes","name","value","text","createServerHead","registry","tags","options","winner","runWithServerHead","head","fn","holder"],"sources":["../../../src/head/server-head.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\nimport { escapeHtml } from \"../server/escape\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, type NormalizedTag } from \"./validate\";\n\n/** Elements that never have content or a closing tag. */\nconst VOID_TAGS: ReadonlySet<string> = new Set([\"meta\", \"link\", \"base\"]);\n\n/**\n * The head of one server render: what `useHead`, `<Title>`, `<Meta>`, `<Link>`, `<Style>` and\n * `<Base>` registered while the app rendered. Pass it to a render function through its `head`\n * option, then write {@link ServerHead.html} into the document's `<head>`.\n *\n * Tags follow the same rules as in the browser: the last registration of an identity wins\n * (`title`, `meta` by name, ...), append-only tags all stay. Every tag carries the marker the\n * browser's head sink looks for, so the client adopts the server's elements instead of adding\n * duplicates.\n * @since 1.0.0\n */\nexport interface ServerHead {\n /** Registers tags. Used by `useHead`; the returned function removes them again. */\n add(tags: readonly NormalizedTag[]): () => void;\n /** Forgets every registration. Multi-pass renders call this before each pass. */\n clear(): void;\n /**\n * The markup of the winning tags, in registration order. With a `nonce`, every `<style>` carries\n * it, so the page's Content-Security-Policy (`style-src 'nonce-...'`) accepts the styles. Throws a\n * TypeError when the text of a style contains a closing style tag.\n *\n * @param options `nonce` is added to every `<style>`. Default: no options, so no nonce.\n */\n html(options?: { readonly nonce?: string }): string;\n /** The winning tags, for hosts that build the head themselves. */\n tags(): readonly NormalizedTag[];\n}\n\n/** The collector `useHead` writes to while a render is running; null outside a render with `head`. @internal */\nexport const ServerHeadContext: Context<ServerHead | null> =\n /* @__PURE__ */ createContext<ServerHead | null>(null, { name: \"ServerHead\" });\n\n/** Markup of one tag. Text and attribute values are escaped; `</style` cannot appear in a style. */\nfunction tagHtml(tag: NormalizedTag, nonce: string | undefined): string {\n let attributes = ` ${HEAD_MARKER}`;\n if (tag.key !== undefined) attributes += ` ${HEAD_KEY}=\"${escapeHtml(tag.key)}\"`;\n for (const [name, value] of tag.attributes) {\n attributes += value === \"\" ? ` ${name}` : ` ${name}=\"${escapeHtml(value)}\"`;\n }\n if (VOID_TAGS.has(tag.tag)) return `<${tag.tag}${attributes}>`;\n const text = tag.text ?? \"\";\n if (tag.tag === \"style\") {\n if (/<\\/style/i.test(text)) {\n throw new TypeError(\"ShadowJS head: style text may not contain a closing style tag.\");\n }\n const withNonce =\n nonce === undefined ? attributes : `${attributes} nonce=\"${escapeHtml(nonce)}\"`;\n return `<style${withNonce}>${text}</style>`;\n }\n return `<${tag.tag}${attributes}>${escapeHtml(text)}</${tag.tag}>`;\n}\n\n/**\n * Creates an empty server head collector.\n *\n * @returns A collector to pass as the `head` option of `renderToString`, `renderToStringAsync` or\n * `renderToStream`.\n * @example\n * import { createComponent, Title } from \"@shadow-js/web\";\n * import { createServerHead, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return Title({ children: \"Home\" });\n * }\n *\n * const head = createServerHead();\n * const html = renderToString(() => createComponent(App, {}), { head });\n * const page = `<!doctype html><head>${head.html()}</head><body>${html}</body>`;\n * @see useHead\n * @since 1.0.0\n */\nexport function createServerHead(): ServerHead {\n let registry: HeadRegistry = createHeadRegistry(() => undefined);\n return {\n add: (tags) => registry.add(tags),\n clear() {\n registry = createHeadRegistry(() => undefined);\n },\n html: (options) =>\n registry\n .winners()\n .map((winner) => tagHtml(winner.tag, options?.nonce))\n .join(\"\"),\n tags: () => registry.winners().map((winner) => winner.tag),\n };\n}\n\n/**\n * Runs `fn` with `head` as the collector `useHead` writes to. Server renderers call it around the\n * app; with no collector `fn` runs as is. @internal\n */\nexport function runWithServerHead<T>(head: ServerHead | undefined, fn: () => T): T {\n if (head === undefined) return fn();\n const holder: { value?: T } = {};\n ServerHeadContext({\n value: head,\n get children() {\n holder.value = fn();\n return null;\n },\n });\n return holder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ID,IAAS,IAAA,GAAW,OAAOC,EAAG,EAClC,IAAMC,EAAwB,CAAC,EAQ/B,OAPAhB,EAAkB,CAChB,MAAOc,EACP,IAAI,UAAW,CAEb,MADAE,GAAO,MAAQD,EAAG,EACX,IACT,CACF,CAAC,EACMC,EAAO,KAChB,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"sink.js","names":["release","el","record","head","adoptable","tag","candidate","identityOfElement","slot","acquire","doc","existing","claimed","HEAD_MARKER","HEAD_KEY","sync","wanted","name","value","text","createDomHeadSink","owned","winners","winner"],"sources":["../../../src/head/sink.ts"],"sourcesContent":["import type { HeadWinner } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, identityOfElement, type NormalizedTag } from \"./validate\";\n\n/**\n * What the sink knows about one element it writes. `created` elements are removed on release;\n * adopted ones are removed too unless they are titles, where the original text comes back.\n */\ninterface Owned {\n readonly el: Element;\n readonly created: boolean;\n /** Text an adopted title had before the sink took it over. */\n readonly restoreText: string | undefined;\n /** Attributes last written, so the next write can remove the ones that disappeared. */\n attributes: ReadonlyArray<readonly [string, string]>;\n}\n\n/** Removes or restores one element the sink owned. Elements already gone are ignored. */\nfunction release(head: HTMLHeadElement, record: Owned): void {\n const el = record.el;\n if (el.parentNode !== head) return;\n if (el.localName === \"title\" && !record.created) {\n if (record.restoreText !== undefined && el.textContent !== record.restoreText) {\n el.textContent = record.restoreText;\n }\n return;\n }\n el.remove();\n}\n\n/**\n * Finds an element to adopt for a slot, or returns undefined. Only identity-keyed slots adopt. A\n * server-rendered element carries the marker, and a page title or base is adopted even without it,\n * because the browser shows that one, so it must be the one that changes.\n */\nfunction adoptable(\n head: HTMLHeadElement,\n slot: string,\n tag: NormalizedTag,\n claimed: Set<Element>,\n): Element | undefined {\n if (tag.identity === undefined) return undefined;\n for (const candidate of Array.from(head.querySelectorAll(tag.tag))) {\n if (claimed.has(candidate)) continue;\n if (identityOfElement(candidate) !== slot) continue;\n if (candidate.hasAttribute(HEAD_MARKER) || tag.tag === \"title\") return candidate;\n }\n return undefined;\n}\n\n/** Takes over an existing element for a slot, or creates and marks a new one. */\nfunction acquire(doc: Document, slot: string, tag: NormalizedTag, claimed: Set<Element>): Owned {\n const head = doc.head;\n const existing = adoptable(head, slot, tag, claimed);\n if (existing !== undefined) {\n const restoreText = tag.tag === \"title\" ? existing.textContent : undefined;\n return { el: existing, created: false, restoreText, attributes: [] };\n }\n const el = doc.createElement(tag.tag);\n el.setAttribute(HEAD_MARKER, \"\");\n if (tag.key !== undefined) el.setAttribute(HEAD_KEY, tag.key);\n if (tag.tag === \"base\") head.insertBefore(el, head.firstChild);\n else head.appendChild(el);\n return { el, created: true, restoreText: undefined, attributes: [] };\n}\n\n/** Writes the attributes and text of `tag` to its element, touching only what changed. */\nfunction sync(record: Owned, tag: NormalizedTag): void {\n const el = record.el;\n const wanted = new Map<string, string>(tag.attributes);\n for (const [name] of record.attributes) {\n if (!wanted.has(name)) el.removeAttribute(name);\n }\n for (const [name, value] of tag.attributes) {\n if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n }\n record.attributes = tag.attributes;\n if (tag.tag === \"title\" || tag.tag === \"style\") {\n const text = tag.text ?? \"\";\n if (el.textContent !== text) el.textContent = text;\n }\n}\n\n/**\n * Creates the DOM sink for one document. The returned function makes `document.head` show the\n * given winners: it releases elements whose slot is gone, adopts or creates the rest and updates\n * them in place. It is called once per batch of registrations, so one call is one DOM pass.\n *\n * @param doc The document whose head is written.\n * @returns A function that applies a list of winners.\n * @internal\n * @since 1.0.0\n */\nexport function createDomHeadSink(doc: Document): (winners: readonly HeadWinner[]) => void {\n const owned = new Map<string, Owned>();\n return (winners: readonly HeadWinner[]): void => {\n const head = doc.head;\n const wanted = new Set(winners.map((winner) => winner.slot));\n for (const [slot, record] of owned) {\n if (wanted.has(slot) && record.el.parentNode === head) continue;\n owned.delete(slot);\n release(head, record);\n }\n const claimed = new Set<Element>();\n for (const record of owned.values()) claimed.add(record.el);\n for (const winner of winners) {\n let record = owned.get(winner.slot);\n if (record === undefined) {\n record = acquire(doc, winner.slot, winner.tag, claimed);\n owned.set(winner.slot, record);\n claimed.add(record.el);\n }\n sync(record, winner.tag);\n }\n };\n}\n"],"mappings":"A,iFAiBA,SAASA,EAAQ,EAAuB,EAAqB,CAC3D,IAAMC,EAAKC,EAAO,GACdD,EAAG,aAAeE,IAClBF,EAAG,YAAc,SAAW,CAACC,EAAO,QAClCA,EAAO,cAAgB,IAAA,IAAaD,EAAG,cAAgBC,EAAO,cAChE,EAAG,YAAcA,EAAO,aAI5BD,EAAG,OAAO,EACZ,CAOA,SAASG,EACP,EACA,EACA,EACA,EACqB,CACrB,GAAIC,EAAI,WAAa,IAAA,GACrB,KAAK,IAAMC,KAAa,MAAM,KAAKH,EAAK,iBAAiBE,EAAI,GAAG,CAAC,EAC/D,GAAI,GAAQ,IAAIC,CAAS,GACrBC,EAAkBD,CAAS,IAAME,IACjCF,EAAU,aAAA,kBAAwB,GAAKD,EAAI,MAAQ,SAAS,OAAOC,CACzE,CAEF,CAGA,SAASG,EAAQ,EAAe,EAAc,EAAoB,EAA8B,CAC9F,IAAMN,EAAOO,EAAI,KACXC,EAAWP,EAAUD,EAAMK,EAAMH,EAAKO,CAAO,EACnD,GAAID,IAAa,IAAA,GAEf,MAAO,CAAE,GAAIA,EAAU,QAAS,GAAO,YADnBN,EAAI,MAAQ,QAAUM,EAAS,YAAc,IAAA,GACb,WAAY,CAAC,CAAE,EAErE,IAAMV,EAAKS,EAAI,cAAcL,EAAI,GAAG,EAKpC,OAJAJ,EAAG,aAAaY,EAAa,EAAE,EAC3BR,EAAI,MAAQ,IAAA,IAAWJ,EAAG,aAAaa,EAAUT,EAAI,GAAG,EACxDA,EAAI,MAAQ,OAAQF,EAAK,aAAaF,EAAIE,EAAK,UAAU,EACxDA,EAAK,YAAYF,CAAE,EACjB,CAAE,KAAI,QAAS,GAAM,YAAa,IAAA,GAAW,WAAY,CAAC,CAAE,CACrE,CAGA,SAASc,EAAK,EAAe,EAA0B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ot","tag","claimed","candidate","acquire","doc","existing","sync","wanted","name","value","text","createDomHeadSink","owned","winners","winner"],"sources":["../../../src/head/sink.ts"],"sourcesContent":["import type { HeadWinner } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, identityOfElement, type NormalizedTag } from \"./validate\";\n\n/**\n * What the sink knows about one element it writes. `created` elements are removed on release;\n * adopted ones are removed too unless they are titles, where the original text comes back.\n */\ninterface Owned {\n readonly el: Element;\n readonly created: boolean;\n /** Text an adopted title had before the sink took it over. */\n readonly restoreText: string | undefined;\n /** Attributes last written, so the next write can remove the ones that disappeared. */\n attributes: ReadonlyArray<readonly [string, string]>;\n}\n\n/** Removes or restores one element the sink owned. Elements already gone are ignored. */\nfunction release(head: HTMLHeadElement, record: Owned): void {\n const el = record.el;\n if (el.parentNode !== head) return;\n if (el.localName === \"title\" && !record.created) {\n if (record.restoreText !== undefined && el.textContent !== record.restoreText) {\n el.textContent = record.restoreText;\n }\n return;\n }\n el.remove();\n}\n\n/**\n * Finds an element to adopt for a slot, or returns undefined. Only identity-keyed slots adopt. A\n * server-rendered element carries the marker, and a page title or base is adopted even without it,\n * because the browser shows that one, so it must be the one that changes.\n */\nfunction adoptable(\n head: HTMLHeadElement,\n slot: string,\n tag: NormalizedTag,\n claimed: Set<Element>,\n): Element | undefined {\n if (tag.identity === undefined) return undefined;\n for (const candidate of Array.from(head.querySelectorAll(tag.tag))) {\n if (claimed.has(candidate)) continue;\n if (identityOfElement(candidate) !== slot) continue;\n if (candidate.hasAttribute(HEAD_MARKER) || tag.tag === \"title\") return candidate;\n }\n return undefined;\n}\n\n/** Takes over an existing element for a slot, or creates and marks a new one. */\nfunction acquire(doc: Document, slot: string, tag: NormalizedTag, claimed: Set<Element>): Owned {\n const head = doc.head;\n const existing = adoptable(head, slot, tag, claimed);\n if (existing !== undefined) {\n const restoreText = tag.tag === \"title\" ? existing.textContent : undefined;\n return { el: existing, created: false, restoreText, attributes: [] };\n }\n const el = doc.createElement(tag.tag);\n el.setAttribute(HEAD_MARKER, \"\");\n if (tag.key !== undefined) el.setAttribute(HEAD_KEY, tag.key);\n if (tag.tag === \"base\") head.insertBefore(el, head.firstChild);\n else head.appendChild(el);\n return { el, created: true, restoreText: undefined, attributes: [] };\n}\n\n/** Writes the attributes and text of `tag` to its element, touching only what changed. */\nfunction sync(record: Owned, tag: NormalizedTag): void {\n const el = record.el;\n const wanted = new Map<string, string>(tag.attributes);\n for (const [name] of record.attributes) {\n if (!wanted.has(name)) el.removeAttribute(name);\n }\n for (const [name, value] of tag.attributes) {\n if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n }\n record.attributes = tag.attributes;\n if (tag.tag === \"title\" || tag.tag === \"style\") {\n const text = tag.text ?? \"\";\n if (el.textContent !== text) el.textContent = text;\n }\n}\n\n/**\n * Creates the DOM sink for one document. The returned function makes `document.head` show the\n * given winners: it releases elements whose slot is gone, adopts or creates the rest and updates\n * them in place. It is called once per batch of registrations, so one call is one DOM pass.\n *\n * @param doc The document whose head is written.\n * @returns A function that applies a list of winners.\n * @internal\n * @since 1.0.0\n */\nexport function createDomHeadSink(doc: Document): (winners: readonly HeadWinner[]) => void {\n const owned = new Map<string, Owned>();\n return (winners: readonly HeadWinner[]): void => {\n const head = doc.head;\n const wanted = new Set(winners.map((winner) => winner.slot));\n for (const [slot, record] of owned) {\n if (wanted.has(slot) && record.el.parentNode === head) continue;\n owned.delete(slot);\n release(head, record);\n }\n const claimed = new Set<Element>();\n for (const record of owned.values()) claimed.add(record.el);\n for (const winner of winners) {\n let record = owned.get(winner.slot);\n if (record === undefined) {\n record = acquire(doc, winner.slot, winner.tag, claimed);\n owned.set(winner.slot, record);\n claimed.add(record.el);\n }\n sync(record, winner.tag);\n }\n };\n}\n"],"mappings":"A,iFAiBA,SAASG,EAAQC,EAAuBC,EAAqB,CAC3D,IAAMC,EAAKD,EAAO,GACdC,EAAG,aAAeF,IAClBE,EAAG,YAAc,SAAW,CAACD,EAAO,QAClCA,EAAO,cAAgB,IAAA,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EAAMC,CAAK,EAGlE,GADAb,EAAO,WAAaI,EAAI,WACpBA,EAAI,MAAQ,SAAWA,EAAI,MAAQ,QAAS,CAC9C,IAAMU,EAAOV,EAAI,MAAQ,GACrBH,EAAG,cAAgBa,IAAMb,EAAG,YAAca,EAChD,CACF,CAYA,SAAgBC,EAAkBP,EAAyD,CACzF,IAAMQ,kBAAQ,IAAI,IAClB,MAAQC,IAAyC,CAC/C,IAAMlB,EAAOS,EAAI,KACXG,EAAS,IAAI,IAAIM,EAAQ,IAAKC,GAAWA,EAAO,IAAI,CAAC,EAC3D,IAAK,GAAM,CAACf,EAAMH,KAAWgB,EACvBL,EAAO,IAAIR,CAAI,GAAKH,EAAO,GAAG,aAAeD,IACjDiB,EAAM,OAAOb,CAAI,EACjBL,EAAQC,EAAMC,CAAM,GAEtB,IAAMK,kBAAU,IAAI,IACpB,IAAK,IAAML,KAAUgB,EAAM,OAAO,EAAGX,EAAQ,IAAIL,EAAO,EAAE,EAC1D,IAAK,IAAMkB,KAAUD,EAAS,CAC5B,IAAIjB,EAASgB,EAAM,IAAIE,EAAO,IAAI,EAC9BlB,IAAW,IAAA,KACbA,EAASO,EAAQC,EAAKU,EAAO,KAAMA,EAAO,IAAKb,CAAO,EACtDW,EAAM,IAAIE,EAAO,KAAMlB,CAAM,EAC7BK,EAAQ,IAAIL,EAAO,EAAE,GAEvBU,EAAKV,EAAQkB,EAAO,GAAG,CACzB,CACF,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-head.js","names":["registries","createRegistryFor","createRoot","version","bump","useSignal","registry","createHeadRegistry","count","apply","createDomHeadSink","doc","useEffect","winners","registryFor","known","useHead","isServer","collector","getOwner","useContext","ServerHeadContext","normalizeTags","untrack","input","useRenderEffect","tags"],"sources":["../../../src/head/use-head.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n untrack,\n useContext,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { ServerHeadContext } from \"./server-head\";\nimport { createDomHeadSink } from \"./sink\";\nimport { type HeadInput, normalizeTags } from \"./validate\";\n\n/** One registry per document, shared by every `useHead` call on it. */\nconst registries = new WeakMap<Document, HeadRegistry>();\n\n/**\n * Creates the registry for a document and the deferred effect that writes it to the head. The\n * effect is detached: it lives as long as the document, not as long as the first caller. It runs\n * in the user-effect queue, so every registration made in one flush produces one DOM pass.\n */\nfunction createRegistryFor(doc: Document): HeadRegistry {\n return createRoot(\n (): HeadRegistry => {\n const [version, bump] = useSignal(0);\n const registry = createHeadRegistry(() => {\n bump((count) => count + 1);\n });\n const apply = createDomHeadSink(doc);\n useEffect(\n () => {\n version();\n return registry.winners();\n },\n (winners) => {\n apply(winners);\n },\n );\n return registry;\n },\n { detached: true },\n );\n}\n\n/** The registry of a document, created on first use. */\nfunction registryFor(doc: Document): HeadRegistry {\n const known = registries.get(doc);\n if (known !== undefined) return known;\n const registry = createRegistryFor(doc);\n registries.set(doc, registry);\n return registry;\n}\n\n/**\n * Registers head tags for the lifetime of the current owner. Each registration joins the stack of\n * its identity: `title` and `base` are singletons, `meta` is keyed by its name, property,\n * http-equiv or charset (and media), icons by rel, sizes and type, resource links by rel, href and\n * as, and styles by key. The last registration of an identity wins; disposing it restores the one\n * below. Append-only tags (no identity) all stay. Passing a function re-registers when its\n * dependencies change. On the client the registrations are written to `document.head` after the\n * render phase of a flush, in one pass per flush. On the server the tags go to the render's `head`\n * collector (see `createServerHead`), read once; without one, or outside an owner, nothing is\n * registered.\n *\n * @param input One tag, several tags, or a function returning them. `null`, `undefined` and `false`\n * register nothing.\n * @throws TypeError for an invalid tag description (see {@link normalizeTags}); on the client the\n * error is raised in the registration's render effect and goes to the owner's error handler.\n * In development builds, calling it on the client with no owner does not throw: it warns\n * `HEAD_OUTSIDE_OWNER` and registers nothing.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { useHead } from \"@shadow-js/web\";\n *\n * function Post() {\n * const [post] = useSignal({ title: \"Hello\" });\n * useHead(() => ({ tag: \"title\", children: `${post().title} | Blog` }));\n * return null;\n * }\n * @see Title\n * @see Meta\n * @since 1.0.0\n */\nexport function useHead(input: HeadInput | (() => HeadInput)): void {\n if (isServer) {\n const collector = getOwner() === null ? null : useContext(ServerHeadContext);\n if (collector !== null) {\n collector.add(normalizeTags(untrack(() => (typeof input === \"function\" ? input() : input))));\n }\n return;\n }\n if (getOwner() === null) {\n if (__DEV__) {\n console.warn(\"[shadow HEAD_OUTSIDE_OWNER] useHead() needs an owner; nothing was registered.\");\n }\n return;\n }\n const registry = registryFor(document);\n useRenderEffect(\n () => normalizeTags(typeof input === \"function\" ? input() : input),\n (tags) => registry.add(tags),\n );\n}\n"],"mappings":"A,6VAgBA,MAAMA,kBAAa,IAAI,QAOvB,SAASC,EAAkB,EAA6B,CACtD,OAAOC,MACe,CAClB,GAAM,CAACC,EAASC,GAAQC,EAAU,CAAC,EAC7BC,EAAWC,MAAyB,CACxCH,EAAM,GAAUI,EAAQ,CAAC,CAC3B,CAAC,EACKC,EAAQC,EAAkBC,CAAG,EAUnC,OATAC,OAEIT,EAAQ,EACDG,EAAS,QAAQ,GAEzB,GAAY,CACXG,EAAMI,CAAO,CACf,CACF,EACOP,CACT,EACA,CAAE,SAAU,EAAK,CACnB,CACF,CAGA,SAASQ,EAAY,EAA6B,CAChD,IAAMC,EAAQf,EAAW,IAAIW,CAAG,EAChC,GAAII,IAAU,IAAA,GAAW,OAAOA,EAChC,IAAMT,EAAWL,EAAkBU,CAAG,EAEtC,OADAX,EAAW,IAAIW,EAAKL,CAAQ,EACrBA,CACT,CAgCA,SAAgBU,EAAQ,EAA4C,CAClE,GAAIC,EAAU,CACZ,IAAMC,EAAYC,EAAS,IAAM,KAAO,KAAOC,EAAWC,CAAiB,EACvEH,IAAc,MAChBA,EAAU,IAAII,EAAcC,MAAe,OAAOC,GAAU,WAAaA,EAAM,EAAIA,CAAM,CAAC,CAAC,EAE7F,MACF,CACA,GAAIL,EAAS,IAAM,KAIjB,OAEF,IAAMb,EAAWQ,EAAY,QAAQ,EACrCW,MACQH,EAAc,OAAOE,GAAU,WAAaA,EAAM,EAAIA,CAAK,EAChE,GAASlB,EAAS,IAAIoB,CAAI,CAC7B,CACF,C"}
1
+ {"version":3,"file":"use-head.js","names":["createHeadRegistry","ServerHeadContext","createDomHeadSink","normalizeTags","createRoot","getOwner","isServer","untrack","useContext","useEffect","useRenderEffect","useSignal","registries","createRegistryFor","doc","version","bump","registry","count","apply","winners","registryFor","known","useHead","input","collector","tags"],"sources":["../../../src/head/use-head.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n untrack,\n useContext,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { ServerHeadContext } from \"./server-head\";\nimport { createDomHeadSink } from \"./sink\";\nimport { type HeadInput, normalizeTags } from \"./validate\";\n\n/** One registry per document, shared by every `useHead` call on it. */\nconst registries = new WeakMap<Document, HeadRegistry>();\n\n/**\n * Creates the registry for a document and the deferred effect that writes it to the head. The\n * effect is detached: it lives as long as the document, not as long as the first caller. It runs\n * in the user-effect queue, so every registration made in one flush produces one DOM pass.\n */\nfunction createRegistryFor(doc: Document): HeadRegistry {\n return createRoot(\n (): HeadRegistry => {\n const [version, bump] = useSignal(0);\n const registry = createHeadRegistry(() => {\n bump((count) => count + 1);\n });\n const apply = createDomHeadSink(doc);\n useEffect(\n () => {\n version();\n return registry.winners();\n },\n (winners) => {\n apply(winners);\n },\n );\n return registry;\n },\n { detached: true },\n );\n}\n\n/** The registry of a document, created on first use. */\nfunction registryFor(doc: Document): HeadRegistry {\n const known = registries.get(doc);\n if (known !== undefined) return known;\n const registry = createRegistryFor(doc);\n registries.set(doc, registry);\n return registry;\n}\n\n/**\n * Registers head tags for the lifetime of the current owner. Each registration joins the stack of\n * its identity: `title` and `base` are singletons, `meta` is keyed by its name, property,\n * http-equiv or charset (and media), icons by rel, sizes and type, resource links by rel, href and\n * as, and styles by key. The last registration of an identity wins; disposing it restores the one\n * below. Append-only tags (no identity) all stay. Passing a function re-registers when its\n * dependencies change. On the client the registrations are written to `document.head` after the\n * render phase of a flush, in one pass per flush. On the server the tags go to the render's `head`\n * collector (see `createServerHead`), read once; without one, or outside an owner, nothing is\n * registered.\n *\n * @param input One tag, several tags, or a function returning them. `null`, `undefined` and `false`\n * register nothing.\n * @throws TypeError for an invalid tag description (see {@link normalizeTags}); on the client the\n * error is raised in the registration's render effect and goes to the owner's error handler.\n * In development builds, calling it on the client with no owner does not throw: it warns\n * `HEAD_OUTSIDE_OWNER` and registers nothing.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { useHead } from \"@shadow-js/web\";\n *\n * function Post() {\n * const [post] = useSignal({ title: \"Hello\" });\n * useHead(() => ({ tag: \"title\", children: `${post().title} | Blog` }));\n * return null;\n * }\n * @see Title\n * @see Meta\n * @since 1.0.0\n */\nexport function useHead(input: HeadInput | (() => HeadInput)): void {\n if (isServer) {\n const collector = getOwner() === null ? null : useContext(ServerHeadContext);\n if (collector !== null) {\n collector.add(normalizeTags(untrack(() => (typeof input === \"function\" ? input() : input))));\n }\n return;\n }\n if (getOwner() === null) {\n if (__DEV__) {\n console.warn(\"[shadow HEAD_OUTSIDE_OWNER] useHead() needs an owner; nothing was registered.\");\n }\n return;\n }\n const registry = registryFor(document);\n useRenderEffect(\n () => normalizeTags(typeof input === \"function\" ? input() : input),\n (tags) => registry.add(tags),\n );\n}\n"],"mappings":"A,6VAgBA,MAAMY,kBAAa,IAAI,QAOvB,SAASC,EAAkBC,EAA6B,CACtD,OAAOV,MACe,CAClB,GAAM,CAACW,EAASC,GAAQL,EAAU,CAAC,EAC7BM,EAAWjB,MAAyB,CACxCgB,EAAME,GAAUA,EAAQ,CAAC,CAC3B,CAAC,EACKC,EAAQjB,EAAkBY,CAAG,EAUnC,OATAL,OAEIM,EAAQ,EACDE,EAAS,QAAQ,GAEzBG,GAAY,CACXD,EAAMC,CAAO,CACf,CACF,EACOH,CACT,EACA,CAAE,SAAU,EAAK,CACnB,CACF,CAGA,SAASI,EAAYP,EAA6B,CAChD,IAAMQ,EAAQV,EAAW,IAAIE,CAAG,EAChC,GAAIQ,IAAU,IAAA,GAAW,OAAOA,EAChC,IAAML,EAAWJ,EAAkBC,CAAG,EAEtC,OADAF,EAAW,IAAIE,EAAKG,CAAQ,EACrBA,CACT,CAgCA,SAAgBM,EAAQC,EAA4C,CAClE,GAAIlB,EAAU,CACZ,IAAMmB,EAAYpB,EAAS,IAAM,KAAO,KAAOG,EAAWP,CAAiB,EACvEwB,IAAc,MAChBA,EAAU,IAAItB,EAAcI,MAAe,OAAOiB,GAAU,WAAaA,EAAM,EAAIA,CAAM,CAAC,CAAC,EAE7F,MACF,CACA,GAAInB,EAAS,IAAM,KAIjB,OAEF,IAAMY,EAAWI,EAAY,QAAQ,EACrCX,MACQP,EAAc,OAAOqB,GAAU,WAAaA,EAAM,EAAIA,CAAK,EAChEE,GAAST,EAAS,IAAIS,CAAI,CAC7B,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"validate.js","names":["HEAD_MARKER","HEAD_KEY","TAG_NAMES","ATTRIBUTE_NAME","RESERVED_ATTRIBUTES","FORBIDDEN_NAMES","META_IDENTITY_FIELDS","MULTI_VALUED_META","MULTI_LINK_RELS","RESOURCE_RELS","isHeadTagName","value","frame","parts","part","attributeText","attributesFrom","props","values","key","name","text","isUnsafeUrlAttribute","tag","textFrom","children","keyFrom","normalizeRel","raw","tokens","token","metaIdentity","media","lookup","field","linkIdentity","rel","identityOf","normalizeTag","input","normalizeTags","item","identityOfElement","element","attribute"],"sources":["../../../src/head/validate.ts"],"sourcesContent":["import { isUnsafeUrlAttribute, warnOnce } from \"../extend\";\n\n/**\n * Head elements the registry manages. `script` and `noscript` are refused: a head-registered\n * script would bypass CSP nonces and Trusted Types, so scripts come only from the asset pipeline.\n * @since 1.0.0\n */\nexport type HeadTagName = \"title\" | \"meta\" | \"link\" | \"style\" | \"base\";\n\n/**\n * One attribute value: a string is written as is, `true` as an empty attribute, `false` and\n * `undefined` omit it, and a number is written as text.\n * @since 1.0.0\n */\nexport type HeadAttributeValue = string | number | boolean | undefined;\n\n/**\n * Describes one head element. `key` identifies a `style` for replacement; other tags use their\n * own identity (see {@link useHead}).\n *\n * @example\n * import type { HeadTag } from \"@shadow-js/web\";\n *\n * const description: HeadTag = { tag: \"meta\", props: { name: \"description\", content: \"Docs\" } };\n * @since 1.0.0\n */\nexport interface HeadTag {\n /** The element to register: `title`, `meta`, `link`, `style` or `base`. Any other name throws. */\n readonly tag: HeadTagName;\n /**\n * The attributes of the element. Names are case-insensitive, must be valid attribute names, and\n * may not start with `on`.\n * @default undefined (the element has no attributes)\n */\n readonly props?: Readonly<Record<string, HeadAttributeValue>>;\n /**\n * The text of a `title` or `style`. Other tags take no text and throw when it is given.\n * @default undefined (no text)\n */\n readonly children?: string;\n /**\n * Identity of a `style`: a later style with the same key replaces an earlier one. Only `style`\n * takes a key.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: string;\n}\n\n/**\n * What {@link useHead} accepts: one tag, several tags, or nothing (which registers nothing).\n * @since 1.0.0\n */\nexport type HeadInput = HeadTag | readonly HeadTag[] | null | undefined | false;\n\n/**\n * A validated tag: lower-case attribute names, the text it carries, and its identity. Produced\n * only by {@link normalizeTag}, so the registry and the DOM sink never see unchecked input.\n * @internal\n */\nexport interface NormalizedTag {\n readonly tag: HeadTagName;\n readonly attributes: ReadonlyArray<readonly [string, string]>;\n readonly text: string | undefined;\n readonly key: string | undefined;\n /** Identity that replaces earlier registrations; undefined for append-only tags. */\n readonly identity: string | undefined;\n}\n\n/** Marks every element the sink created or adopted. Callers may not supply it. @internal */\nexport const HEAD_MARKER = \"data-shadow-head\";\n/** Carries a style's key so a server-rendered style can be adopted. @internal */\nexport const HEAD_KEY = \"data-shadow-key\";\n\nconst TAG_NAMES: ReadonlySet<string> = new Set([\"title\", \"meta\", \"link\", \"style\", \"base\"]);\nconst ATTRIBUTE_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;\nconst RESERVED_ATTRIBUTES: ReadonlySet<string> = new Set([HEAD_MARKER, HEAD_KEY]);\n/** Names skipped silently, as spread does: they would reach a prototype if written as keys. */\nconst FORBIDDEN_NAMES: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst META_IDENTITY_FIELDS = [\"name\", \"property\", \"http-equiv\", \"charset\"] as const;\n/**\n * Properties that repeat by design (one tag per image, per tag, per locale). Their identity includes the content,\n * so every value stays; the others are last-wins. Sub-properties of an image (`og:image:width`) are single.\n * @since 1.0.0\n */\nconst MULTI_VALUED_META: ReadonlySet<string> = new Set([\n \"og:image\",\n \"og:video\",\n \"og:audio\",\n \"og:locale:alternate\",\n \"og:email\",\n \"og:phone_number\",\n \"og:fax_number\",\n \"article:tag\",\n \"article:author\",\n \"book:author\",\n \"book:tag\",\n \"music:album\",\n \"music:song\",\n \"music:musician\",\n \"music:creator\",\n \"video:actor\",\n \"video:director\",\n \"video:writer\",\n \"video:tag\",\n \"fb:admins\",\n \"twitter:image\",\n]);\n/** Links that repeat (alternates per language, authors, archives): their identity is every attribute. */\nconst MULTI_LINK_RELS: ReadonlySet<string> = new Set([\n \"alternate\",\n \"author\",\n \"archives\",\n \"assets\",\n \"bookmarks\",\n \"me\",\n \"apple-touch-startup-image\",\n]);\nconst RESOURCE_RELS: ReadonlySet<string> = new Set([\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"preconnect\",\n \"dns-prefetch\",\n \"stylesheet\",\n]);\n\n/** True for the tag names the registry manages. @internal */\nexport function isHeadTagName(value: string): value is HeadTagName {\n return TAG_NAMES.has(value);\n}\n\n/**\n * Length-prefixed identity: `[\"a|b\"]` and `[\"a\", \"b\"]` can never collide because every part\n * carries its own length.\n */\nfunction frame(parts: readonly string[]): string {\n return parts.map((part) => `${part.length}:${part}`).join(\"\");\n}\n\n/** Text of an attribute value, or undefined when the attribute is omitted. */\nfunction attributeText(value: unknown): string | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * Validates the props of one tag and returns its lower-case, de-duplicated attributes, in order. The\n * map is the lookup that the identity is built from, so it is built once per tag.\n */\nfunction attributesFrom(tag: HeadTagName, props: unknown): ReadonlyMap<string, string> {\n if (props === undefined || props === null) return new Map();\n if (typeof props !== \"object\" || Array.isArray(props)) {\n throw new TypeError(__DEV__ ? \"ShadowJS head: props must be an object.\" : \"SHADOW_HEAD_PROPS\");\n }\n const values = new Map<string, string>();\n for (const key of Object.keys(props)) {\n if (!ATTRIBUTE_NAME.test(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: \"${key}\" is not a valid attribute name.`\n : \"SHADOW_HEAD_ATTRIBUTE_NAME\",\n );\n }\n const name = key.toLowerCase();\n if (name.startsWith(\"on\")) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: event attribute \"${key}\" is not allowed.`\n : \"SHADOW_HEAD_EVENT_ATTRIBUTE\",\n );\n }\n if (RESERVED_ATTRIBUTES.has(name)) {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: \"${key}\" is reserved for the runtime.` : \"SHADOW_HEAD_RESERVED\",\n );\n }\n if (FORBIDDEN_NAMES.has(name)) continue;\n const text = attributeText(Reflect.get(props, key));\n if (text === undefined) continue;\n if (isUnsafeUrlAttribute(name, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Dropped the unsafe \"${name}\" value of a <${tag}> head tag.`);\n continue;\n }\n values.set(name, text);\n }\n return values;\n}\n\n/** Children text: title and style only, and only as a string. */\nfunction textFrom(tag: HeadTagName, children: unknown): string | undefined {\n if (children === undefined || children === null) return undefined;\n if (tag !== \"title\" && tag !== \"style\") {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: <${tag}> takes no children.` : \"SHADOW_HEAD_NO_CHILDREN\",\n );\n }\n if (typeof children !== \"string\")\n throw new TypeError(__DEV__ ? \"ShadowJS head: children must be text.\" : \"SHADOW_HEAD_TEXT\");\n return children;\n}\n\n/** The key of a style. Only style takes one. */\nfunction keyFrom(tag: HeadTagName, key: unknown): string | undefined {\n if (key === undefined || key === null) return undefined;\n if (tag !== \"style\")\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: only <style> takes a key.\" : \"SHADOW_HEAD_STYLE_KEY\",\n );\n if (typeof key !== \"string\" || key === \"\") {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n }\n return key;\n}\n\n/** Rel tokens, lower-cased and sorted, so `\"ICON apple\"` and `\"apple icon\"` compare equal. */\nfunction normalizeRel(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const tokens = raw\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return undefined;\n return tokens.sort().join(\" \");\n}\n\n/** Identity of a meta: its first identifying field and the media query. */\nfunction metaIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const media = lookup.get(\"media\") ?? \"\";\n for (const field of META_IDENTITY_FIELDS) {\n const value = lookup.get(field);\n if (value === undefined) continue;\n // A document has one charset, whatever its value: that meta is a singleton.\n if (field === \"charset\") return frame([\"meta\", field]);\n if (MULTI_VALUED_META.has(value))\n return frame([\"meta\", field, value, media, lookup.get(\"content\") ?? \"\"]);\n return frame([\"meta\", field, value, media]);\n }\n return undefined;\n}\n\n/** Identity of a link: icons by rel, sizes and type; preloads and stylesheets by rel, href and as. */\nfunction linkIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const rel = normalizeRel(lookup.get(\"rel\"));\n if (rel === undefined) return undefined;\n const isIcon = rel.split(\" \").some((token) => token === \"icon\" || token.endsWith(\"-icon\"));\n if (isIcon) {\n return frame([\"link\", \"icon\", rel, lookup.get(\"sizes\") ?? \"\", lookup.get(\"type\") ?? \"\"]);\n }\n // A document has one canonical URL: a singleton, so a new value replaces the old element (and a server's\n // copy is adopted) instead of a second `<link rel=\"canonical\">` being appended.\n if (rel === \"canonical\") return frame([\"link\", \"canonical\"]);\n if (RESOURCE_RELS.has(rel)) {\n return frame([\"link\", \"resource\", rel, lookup.get(\"href\") ?? \"\", lookup.get(\"as\") ?? \"\"]);\n }\n if (MULTI_LINK_RELS.has(rel)) {\n return frame([\n \"link\",\n \"multi\",\n rel,\n lookup.get(\"href\") ?? \"\",\n lookup.get(\"hreflang\") ?? \"\",\n lookup.get(\"media\") ?? \"\",\n lookup.get(\"type\") ?? \"\",\n ]);\n }\n return undefined;\n}\n\n/** Identity of a validated tag, or undefined when the tag is append-only. @internal */\nexport function identityOf(\n tag: HeadTagName,\n lookup: ReadonlyMap<string, string>,\n key: string | undefined,\n): string | undefined {\n if (tag === \"title\") return frame([\"title\"]);\n if (tag === \"base\") return frame([\"base\"]);\n if (tag === \"style\") return key === undefined ? undefined : frame([\"style\", key]);\n return tag === \"meta\" ? metaIdentity(lookup) : linkIdentity(lookup);\n}\n\n/**\n * Validates one head tag description and computes its identity. Hostile input throws a\n * TypeError: an unknown tag (including `script`), a bad attribute name, an event attribute, a\n * reserved marker, children on a void tag, or a key on anything but a style. An unsafe URL\n * attribute is dropped with a dev warning, the same way `setAttribute` treats it.\n *\n * @param input The description, usually a {@link HeadTag}; any value is checked.\n * @returns The normalized tag.\n * @throws TypeError for every invalid input listed above.\n * @internal\n * @since 1.0.0\n */\nexport function normalizeTag(input: unknown): NormalizedTag {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a head tag must be an object.\" : \"SHADOW_HEAD_TAG\",\n );\n }\n const name = Reflect.get(input, \"tag\");\n if (typeof name !== \"string\" || !isHeadTagName(name)) {\n const shown = typeof name === \"string\" ? name : typeof name;\n throw new TypeError(\n __DEV__ ? `ShadowJS head: unsupported tag \"${shown}\".` : \"SHADOW_HEAD_TAG_NAME\",\n );\n }\n const lookup = attributesFrom(name, Reflect.get(input, \"props\"));\n const text = textFrom(name, Reflect.get(input, \"children\"));\n const key = keyFrom(name, Reflect.get(input, \"key\"));\n return {\n tag: name,\n attributes: [...lookup],\n text,\n key,\n identity: identityOf(name, lookup, key),\n };\n}\n\n/**\n * Normalizes what {@link useHead} receives: one description, a list, or nothing.\n *\n * @param input A description, a list of them, or null, undefined or false for none.\n * @returns The normalized tags, in order.\n * @throws TypeError when any description is invalid: an unknown tag (including `script`), an\n * attribute name that is not valid or starts with `on`, a reserved marker attribute, an attribute\n * value that is not a string, number or boolean, children on a tag other than `title` and `style`,\n * or a key on anything but a `style`. The production messages start with `SHADOW_HEAD_`.\n * @example\n * import { normalizeTags } from \"@shadow-js/web/server\";\n *\n * const tags = normalizeTags([\n * { tag: \"title\", children: \"A\" },\n * { tag: \"base\", props: { href: \"/\" } },\n * ]);\n * console.log(tags.length); // 2\n * @see useHead\n * @since 1.0.0\n */\nexport function normalizeTags(input: unknown): NormalizedTag[] {\n if (input === null || input === undefined || input === false) return [];\n if (Array.isArray(input)) return input.map((item: unknown) => normalizeTag(item));\n return [normalizeTag(input)];\n}\n\n/**\n * The identity of an element already in the document, computed the same way as for a\n * registration, so the sink can adopt a server-rendered element. Undefined for elements that are\n * not head tags or that are append-only.\n * @internal\n */\nexport function identityOfElement(element: Element): string | undefined {\n const name = element.localName;\n if (!isHeadTagName(name)) return undefined;\n const lookup = new Map<string, string>();\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.name === HEAD_MARKER || attribute.name === HEAD_KEY) continue;\n lookup.set(attribute.name.toLowerCase(), attribute.value);\n }\n const key = element.getAttribute(HEAD_KEY) ?? undefined;\n return identityOf(name, lookup, key);\n}\n"],"mappings":"A,2FAqEA,MAAaA,EAAc,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BUTE_NAME","RESERVED_ATTRIBUTES","FORBIDDEN_NAMES","META_IDENTITY_FIELDS","MULTI_VALUED_META","MULTI_LINK_RELS","RESOURCE_RELS","isHeadTagName","value","frame","parts","part","attributeText","attributesFrom","tag","props","values","key","name","text","textFrom","children","keyFrom","normalizeRel","raw","tokens","token","metaIdentity","lookup","media","field","linkIdentity","rel","identityOf","normalizeTag","input","normalizeTags","item","identityOfElement","element","attribute"],"sources":["../../../src/head/validate.ts"],"sourcesContent":["import { isUnsafeUrlAttribute, warnOnce } from \"../extend\";\n\n/**\n * Head elements the registry manages. `script` and `noscript` are refused: a head-registered\n * script would bypass CSP nonces and Trusted Types, so scripts come only from the asset pipeline.\n * @since 1.0.0\n */\nexport type HeadTagName = \"title\" | \"meta\" | \"link\" | \"style\" | \"base\";\n\n/**\n * One attribute value: a string is written as is, `true` as an empty attribute, `false` and\n * `undefined` omit it, and a number is written as text.\n * @since 1.0.0\n */\nexport type HeadAttributeValue = string | number | boolean | undefined;\n\n/**\n * Describes one head element. `key` identifies a `style` for replacement; other tags use their\n * own identity (see {@link useHead}).\n *\n * @example\n * import type { HeadTag } from \"@shadow-js/web\";\n *\n * const description: HeadTag = { tag: \"meta\", props: { name: \"description\", content: \"Docs\" } };\n * @since 1.0.0\n */\nexport interface HeadTag {\n /** The element to register: `title`, `meta`, `link`, `style` or `base`. Any other name throws. */\n readonly tag: HeadTagName;\n /**\n * The attributes of the element. Names are case-insensitive, must be valid attribute names, and\n * may not start with `on`.\n * @default undefined (the element has no attributes)\n */\n readonly props?: Readonly<Record<string, HeadAttributeValue>>;\n /**\n * The text of a `title` or `style`. Other tags take no text and throw when it is given.\n * @default undefined (no text)\n */\n readonly children?: string;\n /**\n * Identity of a `style`: a later style with the same key replaces an earlier one. Only `style`\n * takes a key.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: string;\n}\n\n/**\n * What {@link useHead} accepts: one tag, several tags, or nothing (which registers nothing).\n * @since 1.0.0\n */\nexport type HeadInput = HeadTag | readonly HeadTag[] | null | undefined | false;\n\n/**\n * A validated tag: lower-case attribute names, the text it carries, and its identity. Produced\n * only by {@link normalizeTag}, so the registry and the DOM sink never see unchecked input.\n * @internal\n */\nexport interface NormalizedTag {\n readonly tag: HeadTagName;\n readonly attributes: ReadonlyArray<readonly [string, string]>;\n readonly text: string | undefined;\n readonly key: string | undefined;\n /** Identity that replaces earlier registrations; undefined for append-only tags. */\n readonly identity: string | undefined;\n}\n\n/** Marks every element the sink created or adopted. Callers may not supply it. @internal */\nexport const HEAD_MARKER = \"data-shadow-head\";\n/** Carries a style's key so a server-rendered style can be adopted. @internal */\nexport const HEAD_KEY = \"data-shadow-key\";\n\nconst TAG_NAMES: ReadonlySet<string> = new Set([\"title\", \"meta\", \"link\", \"style\", \"base\"]);\nconst ATTRIBUTE_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;\nconst RESERVED_ATTRIBUTES: ReadonlySet<string> = new Set([HEAD_MARKER, HEAD_KEY]);\n/** Names skipped silently, as spread does: they would reach a prototype if written as keys. */\nconst FORBIDDEN_NAMES: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst META_IDENTITY_FIELDS = [\"name\", \"property\", \"http-equiv\", \"charset\"] as const;\n/**\n * Properties that repeat by design (one tag per image, per tag, per locale). Their identity includes the content,\n * so every value stays; the others are last-wins. Sub-properties of an image (`og:image:width`) are single.\n * @since 1.0.0\n */\nconst MULTI_VALUED_META: ReadonlySet<string> = new Set([\n \"og:image\",\n \"og:video\",\n \"og:audio\",\n \"og:locale:alternate\",\n \"og:email\",\n \"og:phone_number\",\n \"og:fax_number\",\n \"article:tag\",\n \"article:author\",\n \"book:author\",\n \"book:tag\",\n \"music:album\",\n \"music:song\",\n \"music:musician\",\n \"music:creator\",\n \"video:actor\",\n \"video:director\",\n \"video:writer\",\n \"video:tag\",\n \"fb:admins\",\n \"twitter:image\",\n]);\n/** Links that repeat (alternates per language, authors, archives): their identity is every attribute. */\nconst MULTI_LINK_RELS: ReadonlySet<string> = new Set([\n \"alternate\",\n \"author\",\n \"archives\",\n \"assets\",\n \"bookmarks\",\n \"me\",\n \"apple-touch-startup-image\",\n]);\nconst RESOURCE_RELS: ReadonlySet<string> = new Set([\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"preconnect\",\n \"dns-prefetch\",\n \"stylesheet\",\n]);\n\n/** True for the tag names the registry manages. @internal */\nexport function isHeadTagName(value: string): value is HeadTagName {\n return TAG_NAMES.has(value);\n}\n\n/**\n * Length-prefixed identity: `[\"a|b\"]` and `[\"a\", \"b\"]` can never collide because every part\n * carries its own length.\n */\nfunction frame(parts: readonly string[]): string {\n return parts.map((part) => `${part.length}:${part}`).join(\"\");\n}\n\n/** Text of an attribute value, or undefined when the attribute is omitted. */\nfunction attributeText(value: unknown): string | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * Validates the props of one tag and returns its lower-case, de-duplicated attributes, in order. The\n * map is the lookup that the identity is built from, so it is built once per tag.\n */\nfunction attributesFrom(tag: HeadTagName, props: unknown): ReadonlyMap<string, string> {\n if (props === undefined || props === null) return new Map();\n if (typeof props !== \"object\" || Array.isArray(props)) {\n throw new TypeError(__DEV__ ? \"ShadowJS head: props must be an object.\" : \"SHADOW_HEAD_PROPS\");\n }\n const values = new Map<string, string>();\n for (const key of Object.keys(props)) {\n if (!ATTRIBUTE_NAME.test(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: \"${key}\" is not a valid attribute name.`\n : \"SHADOW_HEAD_ATTRIBUTE_NAME\",\n );\n }\n const name = key.toLowerCase();\n if (name.startsWith(\"on\")) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: event attribute \"${key}\" is not allowed.`\n : \"SHADOW_HEAD_EVENT_ATTRIBUTE\",\n );\n }\n if (RESERVED_ATTRIBUTES.has(name)) {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: \"${key}\" is reserved for the runtime.` : \"SHADOW_HEAD_RESERVED\",\n );\n }\n if (FORBIDDEN_NAMES.has(name)) continue;\n const text = attributeText(Reflect.get(props, key));\n if (text === undefined) continue;\n if (isUnsafeUrlAttribute(name, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Dropped the unsafe \"${name}\" value of a <${tag}> head tag.`);\n continue;\n }\n values.set(name, text);\n }\n return values;\n}\n\n/** Children text: title and style only, and only as a string. */\nfunction textFrom(tag: HeadTagName, children: unknown): string | undefined {\n if (children === undefined || children === null) return undefined;\n if (tag !== \"title\" && tag !== \"style\") {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: <${tag}> takes no children.` : \"SHADOW_HEAD_NO_CHILDREN\",\n );\n }\n if (typeof children !== \"string\")\n throw new TypeError(__DEV__ ? \"ShadowJS head: children must be text.\" : \"SHADOW_HEAD_TEXT\");\n return children;\n}\n\n/** The key of a style. Only style takes one. */\nfunction keyFrom(tag: HeadTagName, key: unknown): string | undefined {\n if (key === undefined || key === null) return undefined;\n if (tag !== \"style\")\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: only <style> takes a key.\" : \"SHADOW_HEAD_STYLE_KEY\",\n );\n if (typeof key !== \"string\" || key === \"\") {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n }\n return key;\n}\n\n/** Rel tokens, lower-cased and sorted, so `\"ICON apple\"` and `\"apple icon\"` compare equal. */\nfunction normalizeRel(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const tokens = raw\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return undefined;\n return tokens.sort().join(\" \");\n}\n\n/** Identity of a meta: its first identifying field and the media query. */\nfunction metaIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const media = lookup.get(\"media\") ?? \"\";\n for (const field of META_IDENTITY_FIELDS) {\n const value = lookup.get(field);\n if (value === undefined) continue;\n // A document has one charset, whatever its value: that meta is a singleton.\n if (field === \"charset\") return frame([\"meta\", field]);\n if (MULTI_VALUED_META.has(value))\n return frame([\"meta\", field, value, media, lookup.get(\"content\") ?? \"\"]);\n return frame([\"meta\", field, value, media]);\n }\n return undefined;\n}\n\n/** Identity of a link: icons by rel, sizes and type; preloads and stylesheets by rel, href and as. */\nfunction linkIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const rel = normalizeRel(lookup.get(\"rel\"));\n if (rel === undefined) return undefined;\n const isIcon = rel.split(\" \").some((token) => token === \"icon\" || token.endsWith(\"-icon\"));\n if (isIcon) {\n return frame([\"link\", \"icon\", rel, lookup.get(\"sizes\") ?? \"\", lookup.get(\"type\") ?? \"\"]);\n }\n // A document has one canonical URL: a singleton, so a new value replaces the old element (and a server's\n // copy is adopted) instead of a second `<link rel=\"canonical\">` being appended.\n if (rel === \"canonical\") return frame([\"link\", \"canonical\"]);\n if (RESOURCE_RELS.has(rel)) {\n return frame([\"link\", \"resource\", rel, lookup.get(\"href\") ?? \"\", lookup.get(\"as\") ?? \"\"]);\n }\n if (MULTI_LINK_RELS.has(rel)) {\n return frame([\n \"link\",\n \"multi\",\n rel,\n lookup.get(\"href\") ?? \"\",\n lookup.get(\"hreflang\") ?? \"\",\n lookup.get(\"media\") ?? \"\",\n lookup.get(\"type\") ?? \"\",\n ]);\n }\n return undefined;\n}\n\n/** Identity of a validated tag, or undefined when the tag is append-only. @internal */\nexport function identityOf(\n tag: HeadTagName,\n lookup: ReadonlyMap<string, string>,\n key: string | undefined,\n): string | undefined {\n if (tag === \"title\") return frame([\"title\"]);\n if (tag === \"base\") return frame([\"base\"]);\n if (tag === \"style\") return key === undefined ? undefined : frame([\"style\", key]);\n return tag === \"meta\" ? metaIdentity(lookup) : linkIdentity(lookup);\n}\n\n/**\n * Validates one head tag description and computes its identity. Hostile input throws a\n * TypeError: an unknown tag (including `script`), a bad attribute name, an event attribute, a\n * reserved marker, children on a void tag, or a key on anything but a style. An unsafe URL\n * attribute is dropped with a dev warning, the same way `setAttribute` treats it.\n *\n * @param input The description, usually a {@link HeadTag}; any value is checked.\n * @returns The normalized tag.\n * @throws TypeError for every invalid input listed above.\n * @internal\n * @since 1.0.0\n */\nexport function normalizeTag(input: unknown): NormalizedTag {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a head tag must be an object.\" : \"SHADOW_HEAD_TAG\",\n );\n }\n const name = Reflect.get(input, \"tag\");\n if (typeof name !== \"string\" || !isHeadTagName(name)) {\n const shown = typeof name === \"string\" ? name : typeof name;\n throw new TypeError(\n __DEV__ ? `ShadowJS head: unsupported tag \"${shown}\".` : \"SHADOW_HEAD_TAG_NAME\",\n );\n }\n const lookup = attributesFrom(name, Reflect.get(input, \"props\"));\n const text = textFrom(name, Reflect.get(input, \"children\"));\n const key = keyFrom(name, Reflect.get(input, \"key\"));\n return {\n tag: name,\n attributes: [...lookup],\n text,\n key,\n identity: identityOf(name, lookup, key),\n };\n}\n\n/**\n * Normalizes what {@link useHead} receives: one description, a list, or nothing.\n *\n * @param input A description, a list of them, or null, undefined or false for none.\n * @returns The normalized tags, in order.\n * @throws TypeError when any description is invalid: an unknown tag (including `script`), an\n * attribute name that is not valid or starts with `on`, a reserved marker attribute, an attribute\n * value that is not a string, number or boolean, children on a tag other than `title` and `style`,\n * or a key on anything but a `style`. The production messages start with `SHADOW_HEAD_`.\n * @example\n * import { normalizeTags } from \"@shadow-js/web/server\";\n *\n * const tags = normalizeTags([\n * { tag: \"title\", children: \"A\" },\n * { tag: \"base\", props: { href: \"/\" } },\n * ]);\n * console.log(tags.length); // 2\n * @see useHead\n * @since 1.0.0\n */\nexport function normalizeTags(input: unknown): NormalizedTag[] {\n if (input === null || input === undefined || input === false) return [];\n if (Array.isArray(input)) return input.map((item: unknown) => normalizeTag(item));\n return [normalizeTag(input)];\n}\n\n/**\n * The identity of an element already in the document, computed the same way as for a\n * registration, so the sink can adopt a server-rendered element. Undefined for elements that are\n * not head tags or that are append-only.\n * @internal\n */\nexport function identityOfElement(element: Element): string | undefined {\n const name = element.localName;\n if (!isHeadTagName(name)) return undefined;\n const lookup = new Map<string, string>();\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.name === HEAD_MARKER || attribute.name === HEAD_KEY) continue;\n lookup.set(attribute.name.toLowerCase(), attribute.value);\n }\n const key = element.getAttribute(HEAD_KEY) ?? undefined;\n return identityOf(name, lookup, key);\n}\n"],"mappings":"A,2FAqEA,MAAaC,EAAc,mBAEdC,EAAW,kBAElBC,kBAAiC,IAAI,IAAI,CAAC,QAAS,OAAQ,OAAQ,QAAS,MAAM,CAAC,EACnFC,EAAiB,8BACjBC,kBAA2C,IAAI,IAAI,CAACJ,EAAaC,CAAQ,CAAC,EAE1EI,kBAAuC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EACxFC,EAAuB,CAAC,OAAQ,WAAY,aAAc,SAAS,EAMnEC,kBAAyC,IAAI,IAAI,CACrD,WACA,WACA,WACA,sBACA,WACA,kBACA,gBACA,cACA,iBACA,cACA,WACA,cACA,aACA,iBACA,gBACA,cACA,iBACA,eACA,YACA,YACA,eACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CACnD,YACA,SACA,WACA,SACA,YACA,KACA,2BACF,CAAC,EACKC,kBAAqC,IAAI,IAAI,CACjD,UACA,gBACA,WACA,aACA,eACA,YACF,CAAC,EAGD,SAAgBC,EAAcC,EAAqC,CACjE,OAAOT,EAAU,IAAIS,CAAK,CAC5B,CAMA,SAASC,EAAMC,EAAkC,CAC/C,OAAOA,EAAM,IAAKC,GAAS,GAAGA,EAAK,OAAO,GAAGA,GAAM,CAAC,CAAC,KAAK,EAAE,CAC9D,CAGA,SAASC,EAAcJ,EAAoC,CAC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AC,EACzE,CAACH,EAAaC,CAAK,CAAC,CAC7B,CAQA,SAAgBG,EAAkBC,EAAsC,CACtE,IAAMrB,EAAOqB,EAAQ,UACrB,GAAI,CAAChC,EAAcW,CAAI,EAAG,OAC1B,IAAMU,kBAAS,IAAI,IACnB,IAAK,IAAMY,KAAa,MAAM,KAAKD,EAAQ,UAAU,EAC/CC,EAAU,OAAA,oBAAwBA,EAAU,OAAA,mBAChDZ,EAAO,IAAIY,EAAU,KAAK,YAAY,EAAGA,EAAU,KAAK,EAG1D,OAAOP,EAAWf,EAAMU,EADZW,EAAQ,aAAA,iBAAqB,GAAK,IAAA,EACX,CACrC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","disposed","teardown","removeRegion","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","dispose","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","flushSync","error","cleanupError","endClaiming","replayEarlyEvents"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\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 try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":"A,wuBAsDA,SAASA,EAAU,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IAAKC,EACL,KAAK,EAAK,CACR,GAAI,GAAK,IAAIC,CAAG,GAAM,OAAO,OAAOC,EAAMD,CAAG,EAE7C,OADAF,EAAK,IAAIE,CAAG,EACL,CAAE,MAAOC,EAAKD,EAAK,CAC5B,EACA,OAAQ,CAER,CACF,CACF,CAMA,SAASE,EAAe,EAAuB,CAC7C,IAAMC,EAAMC,aAAqB,SAAWA,EAAYA,EAAU,cAClE,GAAID,IAAQ,KAAM,OACdA,EAAI,OAAS,MAAME,EAAwBF,EAAI,IAAI,EACvD,IAAMG,EAASH,EAAI,iBAAiBC,EAAW,WAAW,YAAY,EAChEG,EAAmB,CAAC,EAC1B,KAAOD,EAAO,SAAS,GAAG,CACxB,IAAME,EAAUF,EAAO,aACnBE,EAAQ,OAAS,KAAOA,EAAQ,OAAS,MAAKD,EAAM,KAAKC,CAAO,CACtE,CACA,IAAK,IAAMA,KAAWD,EAAOC,EAAQ,OAAO,CAC9C,CAgCA,SAAgBC,EACd,EACA,EACA,EAA0B,CAAC,EACf,CACZ,GAAIC,EAAW,EACb,MAAU,MACsD,wBAChE,EACF,IAAMC,kBAAW,IAAI,IACfC,EAAmBR,aAAqB,QAAU,CAACA,CAAS,EAAI,CAAC,EACvE,IAAK,IAAMS,IAAW,CAAC,GAAGD,EAAO,GAAG,MAAM,KAAKR,EAAU,iBAAiB,WAAW,CAAC,CAAC,EAAG,CACxF,IAAMJ,EAAMa,EAAQ,aAAa,SAAS,EACtCb,IAAQ,MAAMW,EAAS,IAAIX,EAAKa,CAAO,CAC7C,CACAC,EAAcH,EAAUI,EAAQ,kBAAkB,EAElD,IAAMC,EAAqB,CACzB,eACA,aACA,gBACA,cACA,aACA,iBACF,EACMC,EAAiBC,EAAO,QAC9B,EAAO,QAAUF,EACjB,IAAMG,EAAQtB,EAAUkB,EAAQ,MAAQ,CAAC,CAAC,EACpCK,EAASC,EAAajB,EAAW,KAAM,MAAM,KAAKA,EAAU,UAAU,CAAC,EACzEkB,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJ,EAAW,GACXD,IAAO,EACPG,EAAaL,CAAM,EACrB,EACA,GAAI,CAMFM,MACEC,MACEC,EAAUC,EAAgBd,EAAQ,QAAQ,MACxCe,EAAaf,EAAQ,OAAS,SAC5BgB,EAAY,GAAY,CACtB,EAAOC,EACPC,EAAiBlB,CAAO,EACxBmB,EAAqB,CACnB,MAAOf,EACP,IAAI,UAAW,CAEb,OADAgB,EAAWf,EAAQgB,EAAQC,CAAI,CAAC,EACzB,IACT,CACF,CAAC,CACH,CAAC,CACH,CACF,CACF,CACF,EACAC,EAAU,CACZ,OAASC,EAAO,CAGd,GAAI,CACFjB,IAAO,CACT,OAASkB,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACoC,uBAC1D,CACF,CACA,MAAMD,CACR,QAAU,CACRE,EAAY,EACZ,EAAO,QAAUxB,CACnB,CAGA,OAFAyB,EAAkB,EAClBxC,EAAeE,CAAS,EACjBoB,CACT,C"}
1
+ {"version":3,"file":"hydration.js","names":["attachRootErrors","bindRegion","createRegion","removeRegion","beginClaiming","claimElement","claimPortal","endClaiming","isClaiming","liftedRegions","releaseUnclaimedPortals","takeRegion","withoutClaiming","replayEarlyEvents","claims","createRootScope","resourceKey","withScope","ResourceCacheContext","batch","createRoot","flushSync","runWithOwner","untrack","withHydration","dataCache","data","used","key","stripLeftovers","container","doc","walker","stale","comment","hydrate","code","options","registry","roots","element","passClaims","previousClaims","cache","region","stop","disposed","teardown","dispose","error","cleanupError"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\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 try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n stop = dispose;\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n }),\n ),\n ),\n ),\n );\n flushSync();\n } catch (error) {\n // The caller gets no dispose function from a hydration that throws, so the root must not stay alive. Its\n // effects and listeners go; the server's markup stays, so the page keeps what the server rendered.\n try {\n stop?.();\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"hydrate() failed and so did its teardown.\" : \"SHADOW_HYDRATE_ERRORS\",\n );\n }\n throw error;\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n return teardown;\n}\n"],"mappings":"A,wuBAsDA,SAASyB,EAAUC,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB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U,UAAU,CAAC,EACzEe,EACAC,EAAW,GACTC,MAAuB,CACvBD,IACJA,EAAW,GACXD,IAAO,EACP1C,EAAayC,CAAM,EACrB,EACA,GAAI,CAMFpB,MACEL,MACEF,EAAUF,EAAgBsB,EAAQ,QAAQ,MACxCf,EAAae,EAAQ,OAAS,SAC5BjB,EAAY4B,GAAY,CACtBH,EAAOG,EACPhD,EAAiBqC,CAAO,EACxBnB,EAAqB,CACnB,MAAOyB,EACP,IAAI,UAAW,CAEb,OADA1C,EAAW2C,EAAQrB,EAAQa,CAAI,CAAC,EACzB,IACT,CACF,CAAC,CACH,CAAC,CACH,CACF,CACF,CACF,EACAf,EAAU,CACZ,OAAS4B,EAAO,CAGd,GAAI,CACFJ,IAAO,CACT,OAASK,EAAc,CACrB,MAAU,eACR,CAACD,EAAOC,CAAY,EACoC,uBAC1D,CACF,CACA,MAAMD,CACR,QAAU,CACR1C,EAAY,EACZO,EAAO,QAAU4B,CACnB,CAGA,OAFA7B,EAAkB,EAClBgB,EAAeC,CAAS,EACjBiB,CACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":["tails","documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","fragmentChildren","flatten","parts","item","leaves","root","call","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","set","parent","run","onCleanup","keepWatchingCommits","commit","next","attached","first","end","reconcileNodes","commitValue","raw","created","createRegion","initial","anchorNode","linkRegion","tail","currentOwner","start","anchor","addCleanup","containsFunction","stack","frame","bindRegion","value","latest","ordered","useRenderEffect","owner","memos","touched","fn","createComputation","readComputation","disposeOwner","moveRegion","keepFocus","move","removeRegion","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,oXA+CA,MAAMA,kBAAQ,IAAI,QAGlB,SAASC,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IA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AAE,EACfG,EAAatE,CAAI,GAEnB,OAAOW,CACT,EACC,GAAU,CACT2B,EAAOnC,EAAQQ,CAAK,CACtB,CACF,CACF,MACEiC,EAAYzC,EAAQ0C,CAAG,CAE3B,CAAC,EACMgB,CACT,CAYA,SAAgBU,EAAW,EAAgB,EAAc,EAAkC,CACzF,IAAM/B,EAAWrC,EAAO,MAAM,OAAQ,GAASH,EAAK,aAAeG,EAAO,MAAM,EAEhFqE,EAAUrE,EAAO,WAAc,CAC7B,IAAK,IAAMH,KAAQwC,EAAUiC,EAAKzE,CAAI,CACxC,CAAC,EAED,EAA6B,OAASkC,EACtC,EAAO,OAASM,EAAS,EAAE,EAAE,iBAAmBN,EAAO,SACzD,CAOA,SAAgBwC,EAAa,EAAsB,CACjD,IAAK,IAAM1E,KAAQG,EAAO,MACpBH,EAAK,aAAeG,EAAO,QAAQA,EAAO,OAAO,YAAYH,CAAI,EAEvE,EAAO,MAAQ,CAAC,EAChB,EAAO,MAAQ,IACjB,CAkBA,SAAgBsD,EAAO,EAAc,EAA2B,CAC9D,IAAMjD,EAAON,EAAWmC,CAAM,CAAC,CAAC,eAAe,EAAE,EAEjD,OADAA,EAAO,aAAa7B,EAAMsE,CAAM,EACzBtE,CACT,CAwCA,SAAgBuE,EACd,EACA,EACA,EACA,EACS,CACT,IAAMC,EAAiB5B,GAAc,KAIrC,OAAOU,EADQZ,EAAab,EAAQ2C,EADlC7B,IAAY,IAAA,GAAY8B,EAAO,QAAQ,WAAW5C,EAAQ2C,CAAc,EAAI7B,CAEvD,EAAGY,EAAOiB,IAAmB,IAAI,CAC1D,C"}
1
+ {"version":3,"file":"insert.js","names":["leaves","claims","keepFocus","reconcileNodes","onCleanup","useRenderEffect","addCleanup","createComputation","currentOwner","disposeOwner","readComputation","tails","documentOf","node","ownsText","region","texts","addText","text","pruneTexts","keep","kept","fragmentChildren","flatten","root","call","parts","item","kids","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","marker","commitWatchers","watchCommits","parent","run","set","keepWatchingCommits","commit","next","attached","first","end","commitValue","raw","created","createRegion","anchorNode","initial","linkRegion","tail","start","anchor","containsFunction","stack","frame","bindRegion","value","ordered","latest","owner","memos","touched","fn","moveRegion","move","removeRegion","before","insert","resolvedAnchor"],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":"A,oXA+CA,MAAMW,kBAAQ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,EACAuB,EACAV,EACAC,EACS,CACT,IAAMqB,EAAiBtB,GAAc,KAIrC,OAAOS,EADQV,EAAaZ,EAAQmC,EADlCrB,IAAY,IAAA,GAAY1D,EAAO,QAAQ,WAAW4C,EAAQmC,CAAc,EAAIrB,CAEvD,EAAGS,EAAOY,IAAmB,IAAI,CAC1D,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"accessor.js","names":["unwrap","fn","depth","value","call","leaves","found","frames","root","cursors","active","top","frame","cursor","item","cycle"],"sources":["../../../src/internal/accessor.ts"],"sourcesContent":["/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the\n * value at its end. `call` runs each function (default: a plain call); `insert` passes one that\n * memoizes. Class and style values use the default, inside the effect that applies them, so the\n * signals an accessor reads are tracked by it.\n * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.\n * @internal\n */\nexport function unwrap(\n value: unknown,\n call: (fn: () => unknown) => unknown = (fn) => fn(),\n): unknown {\n for (let depth = 0; typeof value === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__\n ? \"An accessor returns accessors more than 10,000 levels deep.\"\n : \"SHADOW_INSERT_DEPTH\",\n );\n value = call(value as () => unknown);\n }\n return value;\n}\n\n/**\n * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is\n * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.\n * `insert` and the class writer share it.\n * @param root The value; an array is entered, any other value is a leaf.\n * @param cycle The message of the `TypeError` thrown when an array contains itself.\n * @param call Passed to {@link unwrap}.\n * @internal\n */\nexport function leaves(\n root: unknown,\n cycle: string,\n call?: (fn: () => unknown) => unknown,\n): unknown[] {\n const found: unknown[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top] as unknown[];\n const cursor = cursors[top] as number;\n if (cursor >= frame.length) {\n active.delete(frames.pop() as unknown[]);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = unwrap(frame[cursor], call);\n if (!Array.isArray(item)) found.push(item);\n else if (active.has(item)) throw new TypeError(cycle);\n else {\n active.add(item);\n frames.push(item);\n cursors.push(0);\n }\n }\n return found;\n}\n"],"mappings":"AAWA,SAAgBA,EACd,EACA,EAAwC,GAAOC,EAAG,EACzC,CACT,IAAK,IAAIC,EAAQ,EAAG,OAAOC,GAAU,WAAY,GAAS,EAAG,CAC3D,GAAID,GAAS,IACX,MAAU,UAGJ,qBACN,EACF,EAAQE,EAAKD,CAAsB,CACrC,CACA,OAAOA,CACT,CAWA,SAAgBE,EACd,EACA,EACA,EACW,CACX,IAAMC,EAAmB,CAAC,EACpBC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOH,EAAO,OAAS,GAAG,CACxB,IAAMI,EAAMJ,EAAO,OAAS,EACtBK,EAAQL,EAAOI,GACfE,EAASJ,EAAQE,GACvB,GAAIE,GAAUD,EAAM,OAAQ,CAC1BF,EAAO,OAAOH,EAAO,IAAI,CAAc,EACvCE,EAAQ,IAAI,EACZ,QACF,CACA,EAAQE,GAAOE,EAAS,EACxB,IAAMC,EAAOd,EAAOY,EAAMC,GAAST,CAAI,EACvC,GAAI,CAAC,MAAM,QAAQU,CAAI,EAAGR,EAAM,KAAKQ,CAAI,OACpC,GAAIJ,EAAO,IAAII,CAAI,EAAG,MAAU,UAAUC,CAAK,OAElDL,EAAO,IAAII,CAAI,EACfP,EAAO,KAAKO,CAAI,EAChBL,EAAQ,KAAK,CAAC,CAElB,CACA,OAAOH,CACT,C"}
1
+ {"version":3,"file":"accessor.js","names":["unwrap","value","call","fn","depth","leaves","root","cycle","found","frames","cursors","active","top","frame","cursor","item"],"sources":["../../../src/internal/accessor.ts"],"sourcesContent":["/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * Calls `value` while it is a function, so an accessor that returns an accessor is followed to the\n * value at its end. `call` runs each function (default: a plain call); `insert` passes one that\n * memoizes. Class and style values use the default, inside the effect that applies them, so the\n * signals an accessor reads are tracked by it.\n * @throws TypeError (production message `SHADOW_INSERT_DEPTH`) after 10,000 functions in a row.\n * @internal\n */\nexport function unwrap(\n value: unknown,\n call: (fn: () => unknown) => unknown = (fn) => fn(),\n): unknown {\n for (let depth = 0; typeof value === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__\n ? \"An accessor returns accessors more than 10,000 levels deep.\"\n : \"SHADOW_INSERT_DEPTH\",\n );\n value = call(value as () => unknown);\n }\n return value;\n}\n\n/**\n * The leaves of a value made of nested arrays, in order, found without recursion (the nesting depth is\n * the user's): every item goes through {@link unwrap}, an array is entered, anything else is a leaf.\n * `insert` and the class writer share it.\n * @param root The value; an array is entered, any other value is a leaf.\n * @param cycle The message of the `TypeError` thrown when an array contains itself.\n * @param call Passed to {@link unwrap}.\n * @internal\n */\nexport function leaves(\n root: unknown,\n cycle: string,\n call?: (fn: () => unknown) => unknown,\n): unknown[] {\n const found: unknown[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top] as unknown[];\n const cursor = cursors[top] as number;\n if (cursor >= frame.length) {\n active.delete(frames.pop() as unknown[]);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n const item = unwrap(frame[cursor], call);\n if (!Array.isArray(item)) found.push(item);\n else if (active.has(item)) throw new TypeError(cycle);\n else {\n active.add(item);\n frames.push(item);\n cursors.push(0);\n }\n }\n return found;\n}\n"],"mappings":"AAWA,SAAgBA,EACdC,EACAC,EAAwCC,GAAOA,EAAG,EACzC,CACT,IAAK,IAAIC,EAAQ,EAAG,OAAOH,GAAU,WAAYG,GAAS,EAAG,CAC3D,GAAIA,GAAS,IACX,MAAU,UAGJ,qBACN,EACFH,EAAQC,EAAKD,CAAsB,CACrC,CACA,OAAOA,CACT,CAWA,SAAgBI,EACdC,EACAC,EACAL,EACW,CACX,IAAMM,EAAmB,CAAC,EACpBC,EAAsB,CAAC,CAACH,CAAI,CAAC,EAC7BI,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOF,EAAO,OAAS,GAAG,CACxB,IAAMG,EAAMH,EAAO,OAAS,EACtBI,EAAQJ,EAAOG,GACfE,EAASJ,EAAQE,GACvB,GAAIE,GAAUD,EAAM,OAAQ,CAC1BF,EAAO,OAAOF,EAAO,IAAI,CAAc,EACvCC,EAAQ,IAAI,EACZ,QACF,CACAA,EAAQE,GAAOE,EAAS,EACxB,IAAMC,EAAOf,EAAOa,EAAMC,GAASZ,CAAI,EACvC,GAAI,CAAC,MAAM,QAAQa,CAAI,EAAGP,EAAM,KAAKO,CAAI,OACpC,GAAIJ,EAAO,IAAII,CAAI,EAAG,MAAU,UAAUR,CAAK,OAElDI,EAAO,IAAII,CAAI,EACfN,EAAO,KAAKM,CAAI,EAChBL,EAAQ,KAAK,CAAC,CAElB,CACA,OAAOF,CACT,C"}