@shadow-js/web 1.0.2 → 1.0.3

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 (183) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/dev/attributes.js.map +1 -1
  3. package/dist/dev/class-style.d.ts +10 -5
  4. package/dist/dev/class-style.js +47 -47
  5. package/dist/dev/class-style.js.map +1 -1
  6. package/dist/dev/control-flow/dynamic.js +2 -2
  7. package/dist/dev/control-flow/dynamic.js.map +1 -1
  8. package/dist/dev/control-flow/error-boundary.js +2 -2
  9. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  10. package/dist/dev/control-flow/portal.d.ts +2 -2
  11. package/dist/dev/control-flow/portal.js +15 -13
  12. package/dist/dev/control-flow/portal.js.map +1 -1
  13. package/dist/dev/control-flow/suspense-list.js +2 -2
  14. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  15. package/dist/dev/control-flow/suspense.js +2 -2
  16. package/dist/dev/control-flow/suspense.js.map +1 -1
  17. package/dist/dev/element.js +5 -2
  18. package/dist/dev/element.js.map +1 -1
  19. package/dist/dev/extend.d.ts +2 -2
  20. package/dist/dev/extend.js +2 -2
  21. package/dist/dev/insert.d.ts +11 -0
  22. package/dist/dev/insert.js +50 -33
  23. package/dist/dev/insert.js.map +1 -1
  24. package/dist/dev/internal/accessor.js +56 -0
  25. package/dist/dev/internal/accessor.js.map +1 -0
  26. package/dist/dev/internal/claim.js +0 -1
  27. package/dist/dev/internal/claim.js.map +1 -1
  28. package/dist/dev/internal/css-units.js +2 -2
  29. package/dist/dev/internal/css-units.js.map +1 -1
  30. package/dist/dev/internal/portal-context.d.ts +9 -0
  31. package/dist/dev/internal/portal-context.js.map +1 -1
  32. package/dist/dev/internal/react-names.js +22 -12
  33. package/dist/dev/internal/react-names.js.map +1 -1
  34. package/dist/dev/internal/reconcile.js +4 -6
  35. package/dist/dev/internal/reconcile.js.map +1 -1
  36. package/dist/dev/server/attributes.js +1 -31
  37. package/dist/dev/server/attributes.js.map +1 -1
  38. package/dist/dev/server/element.js +5 -6
  39. package/dist/dev/server/element.js.map +1 -1
  40. package/dist/dev/server/index.js +1 -1
  41. package/dist/dev/server/portals.js +3 -0
  42. package/dist/dev/server/portals.js.map +1 -1
  43. package/dist/dev/server/render.js +1 -1
  44. package/dist/dev/server/stream.js +1 -1
  45. package/dist/dev/server.js +1 -1
  46. package/dist/dev/spread.js +49 -27
  47. package/dist/dev/spread.js.map +1 -1
  48. package/dist/dev/template.js +1 -3
  49. package/dist/dev/template.js.map +1 -1
  50. package/dist/dev/view-transition.js +12 -4
  51. package/dist/dev/view-transition.js.map +1 -1
  52. package/dist/prod/attributes.js +1 -1
  53. package/dist/prod/attributes.js.map +1 -1
  54. package/dist/prod/class-style.js +1 -1
  55. package/dist/prod/class-style.js.map +1 -1
  56. package/dist/prod/control-flow/dynamic.js +1 -1
  57. package/dist/prod/control-flow/dynamic.js.map +1 -1
  58. package/dist/prod/control-flow/error-boundary.js +1 -1
  59. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  60. package/dist/prod/control-flow/portal.js +1 -1
  61. package/dist/prod/control-flow/portal.js.map +1 -1
  62. package/dist/prod/control-flow/suspense-list.js +1 -1
  63. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  64. package/dist/prod/control-flow/suspense.js +1 -1
  65. package/dist/prod/control-flow/suspense.js.map +1 -1
  66. package/dist/prod/element.js +1 -1
  67. package/dist/prod/element.js.map +1 -1
  68. package/dist/prod/extend.js +1 -1
  69. package/dist/prod/insert.js +1 -1
  70. package/dist/prod/insert.js.map +1 -1
  71. package/dist/prod/internal/accessor.js +2 -0
  72. package/dist/prod/internal/accessor.js.map +1 -0
  73. package/dist/prod/internal/claim.js +1 -1
  74. package/dist/prod/internal/claim.js.map +1 -1
  75. package/dist/prod/internal/css-units.js +1 -1
  76. package/dist/prod/internal/css-units.js.map +1 -1
  77. package/dist/prod/internal/portal-context.js.map +1 -1
  78. package/dist/prod/internal/react-names.js +1 -1
  79. package/dist/prod/internal/react-names.js.map +1 -1
  80. package/dist/prod/internal/reconcile.js +1 -1
  81. package/dist/prod/internal/reconcile.js.map +1 -1
  82. package/dist/prod/server/attributes.js +1 -1
  83. package/dist/prod/server/attributes.js.map +1 -1
  84. package/dist/prod/server/element.js +1 -1
  85. package/dist/prod/server/element.js.map +1 -1
  86. package/dist/prod/server/index.js +1 -1
  87. package/dist/prod/server/portals.js +1 -1
  88. package/dist/prod/server/portals.js.map +1 -1
  89. package/dist/prod/server/render.js +1 -1
  90. package/dist/prod/server/stream.js +1 -1
  91. package/dist/prod/server.js +1 -1
  92. package/dist/prod/spread.js +1 -1
  93. package/dist/prod/spread.js.map +1 -1
  94. package/dist/prod/template.js +1 -1
  95. package/dist/prod/template.js.map +1 -1
  96. package/dist/prod/view-transition.js +1 -1
  97. package/dist/prod/view-transition.js.map +1 -1
  98. package/dist/server/attributes.js +1 -1
  99. package/dist/server/attributes.js.map +1 -1
  100. package/dist/server/class-style.js +1 -1
  101. package/dist/server/class-style.js.map +1 -1
  102. package/dist/server/control-flow/dynamic.js.map +1 -1
  103. package/dist/server/control-flow/error-boundary.js +1 -1
  104. package/dist/server/control-flow/error-boundary.js.map +1 -1
  105. package/dist/server/control-flow/portal.js +1 -1
  106. package/dist/server/control-flow/portal.js.map +1 -1
  107. package/dist/server/control-flow/suspense-list.js +1 -1
  108. package/dist/server/control-flow/suspense-list.js.map +1 -1
  109. package/dist/server/control-flow/suspense.js +1 -1
  110. package/dist/server/control-flow/suspense.js.map +1 -1
  111. package/dist/server/element.js.map +1 -1
  112. package/dist/server/extend.js +1 -1
  113. package/dist/server/insert.js +1 -1
  114. package/dist/server/insert.js.map +1 -1
  115. package/dist/server/internal/accessor.js +2 -0
  116. package/dist/server/internal/accessor.js.map +1 -0
  117. package/dist/server/internal/claim.js +1 -1
  118. package/dist/server/internal/claim.js.map +1 -1
  119. package/dist/server/internal/css-units.js +1 -1
  120. package/dist/server/internal/css-units.js.map +1 -1
  121. package/dist/server/internal/portal-context.js.map +1 -1
  122. package/dist/server/internal/react-names.js +1 -1
  123. package/dist/server/internal/react-names.js.map +1 -1
  124. package/dist/server/internal/reconcile.js +1 -1
  125. package/dist/server/internal/reconcile.js.map +1 -1
  126. package/dist/server/server/attributes.js +1 -1
  127. package/dist/server/server/attributes.js.map +1 -1
  128. package/dist/server/server/element.js +1 -1
  129. package/dist/server/server/element.js.map +1 -1
  130. package/dist/server/server/index.js +1 -1
  131. package/dist/server/server/portals.js +1 -1
  132. package/dist/server/server/portals.js.map +1 -1
  133. package/dist/server/server/render.js +1 -1
  134. package/dist/server/server/stream.js +1 -1
  135. package/dist/server/server.js +1 -1
  136. package/dist/server/spread.js +1 -1
  137. package/dist/server/spread.js.map +1 -1
  138. package/dist/server/template.js +1 -1
  139. package/dist/server/template.js.map +1 -1
  140. package/dist/server/view-transition.js.map +1 -1
  141. package/dist/server-dev/attributes.js.map +1 -1
  142. package/dist/server-dev/class-style.js +47 -47
  143. package/dist/server-dev/class-style.js.map +1 -1
  144. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  145. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  146. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  147. package/dist/server-dev/control-flow/portal.js +15 -13
  148. package/dist/server-dev/control-flow/portal.js.map +1 -1
  149. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  150. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  151. package/dist/server-dev/control-flow/suspense.js +2 -2
  152. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  153. package/dist/server-dev/element.js.map +1 -1
  154. package/dist/server-dev/extend.js +2 -2
  155. package/dist/server-dev/insert.js +50 -33
  156. package/dist/server-dev/insert.js.map +1 -1
  157. package/dist/server-dev/internal/accessor.js +56 -0
  158. package/dist/server-dev/internal/accessor.js.map +1 -0
  159. package/dist/server-dev/internal/claim.js +0 -1
  160. package/dist/server-dev/internal/claim.js.map +1 -1
  161. package/dist/server-dev/internal/css-units.js +2 -2
  162. package/dist/server-dev/internal/css-units.js.map +1 -1
  163. package/dist/server-dev/internal/portal-context.js.map +1 -1
  164. package/dist/server-dev/internal/react-names.js +22 -12
  165. package/dist/server-dev/internal/react-names.js.map +1 -1
  166. package/dist/server-dev/internal/reconcile.js +4 -6
  167. package/dist/server-dev/internal/reconcile.js.map +1 -1
  168. package/dist/server-dev/server/attributes.js +1 -31
  169. package/dist/server-dev/server/attributes.js.map +1 -1
  170. package/dist/server-dev/server/element.js +5 -6
  171. package/dist/server-dev/server/element.js.map +1 -1
  172. package/dist/server-dev/server/index.js +1 -1
  173. package/dist/server-dev/server/portals.js +3 -0
  174. package/dist/server-dev/server/portals.js.map +1 -1
  175. package/dist/server-dev/server/render.js +1 -1
  176. package/dist/server-dev/server/stream.js +1 -1
  177. package/dist/server-dev/server.js +1 -1
  178. package/dist/server-dev/spread.js +35 -26
  179. package/dist/server-dev/spread.js.map +1 -1
  180. package/dist/server-dev/template.js +1 -3
  181. package/dist/server-dev/template.js.map +1 -1
  182. package/dist/server-dev/view-transition.js.map +1 -1
  183. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"element.js","names":["TAG_NAME","VOID_ELEMENTS","SKIPPED_KEYS","innerHtmlOfValue","value","ssr","holes","parts","html","index","hole","isSsrNode","SsrNode","ssrRaw","ssrHydrationKey","key","nextKey","escapeHtml","ssrElement","tag","invalid","lowerTag","isSelect","isTextarea","control","hasValue","hasFallback","attributes","needsKey","classes","style","innerHtml","props","IGNORED_KEYS","isEventName","resolveValue","text","classText","collectTruthyKeys","styleText","plainHtml","ssrAttribute","name","attributeName","svg","flag","BOOLEAN_ATTRIBUTES","ssrStyle","raw","given","children","propsChildren","content","rawElementContent","escape","textareaContent","markSelectedOptions","keepLeadingNewline","out"],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS } from \"../internal/react-names\";\nimport { BOOLEAN_ATTRIBUTES, isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, &lt;Ada&gt;</p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"&lt;b&gt;escaped&lt;/b&gt;<!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.has(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n // `hidden=\"until-found\"` is a keyword, not a flag: a bare `hidden` would hide what it should only collapse.\n const flag =\n BOOLEAN_ATTRIBUTES.has(name) && !(name === \"hidden\" && value === \"until-found\");\n attributes += ssrAttribute(name, value, flag);\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (isTextarea && innerHtml === undefined) {\n // The children of a textarea are its value (as on the client): keep a first line break the parser drops.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":"A,gmBAYA,MAAMA,EAAW,0BAGXC,kBAAqC,IAAI,IAAI,CACjD,OACA,OACA,KACA,MACA,UACA,QACA,KACA,MACA,QACA,SACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAGKC,kBAAoC,IAAI,IAAI,CAChD,YACA,cACA,YACA,WACA,KACF,CAAC,EAGD,SAASC,EAAiB,EAAyB,CACjD,GAAsB,OAAOC,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,QAAQ,CACpC,CAsBA,SAAgBC,EAAI,EAA0B,GAAGC,EAA2B,CAC1E,GAAI,CAAC,MAAM,QAAQC,CAAK,GAAKA,EAAM,SAAWD,EAAM,OAAS,EAC3D,MAAU,UAAU,6DAA6D,EAEnF,IAAIE,EAAOD,EAAM,IAAM,GACvB,IAAK,IAAIE,EAAQ,EAAGA,EAAQH,EAAM,OAAQ,GAAS,EAAG,CACpD,IAAMI,EAAOJ,EAAMG,GACnB,GAAI,OAAOC,GAAS,SAAU,GAAQA,OACjC,GAAIC,EAAUD,CAAI,EAAG,GAAQA,EAAK,OAClC,MAAU,UAAU,wDAAwD,EACjF,GAAQH,EAAME,EAAQ,IAAM,EAC9B,CACA,OAAO,IAAIG,EAAQJ,CAAI,CACzB,CAiBA,SAAgBK,EAAO,EAAuB,CAC5C,GAAI,OAAOL,GAAS,SAAU,MAAU,UAAU,wCAAwC,EAC1F,OAAO,IAAII,EAAQJ,CAAI,CACzB,CAgBA,SAAgBM,GAA0B,CACxC,IAAMC,EAAMC,EAAQ,EACpB,OAAOD,IAAQ,IAAA,GAAY,GAAK,aAAaE,EAAWF,CAAG,EAAE,EAC/D,CAkCA,SAAgBG,EACd,EACA,EACA,EAAoB,IAAA,GACpB,EAAW,GACX,EAAM,GACG,CACT,GAAI,OAAOC,GAAQ,UAA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AOnB,GAAU,UAAnCA,EACJ,OAAO,QAAQ,IAAIA,EAAO,UAAU,CACtC,CAGA,SAASM,EAAkB,EAAgB,EAAqB,CAC9D,GAAsB,OAAOlC,GAAU,UAAnCA,GAA+C,OAAM,QAAQA,CAAK,EACtE,IAAK,IAAMW,KAAO,OAAO,KAAKX,CAAK,EAC7BW,IAAQ,IAAMoB,EAAa,QAAQ,IAAI/B,EAAOW,CAAG,CAAC,GAAG2C,EAAI,KAAK3C,CAAG,CAEzE,CAGA,SAASyB,EAAU,EAAwB,CACzC,GAAIpC,GAAU,KAA6B,MAAO,GAClD,GAAIO,EAAUP,CAAK,EAAG,OAAOA,EAAM,EACnC,GAAI,OAAOA,GAAU,SACnB,MAAMgB,EAAQ,4BAA6B,+BAA+B,EAC5E,OAAO,OAAOhB,CAAK,CACrB,C"}
1
+ {"version":3,"file":"element.js","names":["TAG_NAME","VOID_ELEMENTS","SKIPPED_KEYS","innerHtmlOfValue","value","ssr","holes","parts","html","index","hole","isSsrNode","SsrNode","ssrRaw","ssrHydrationKey","key","nextKey","escapeHtml","ssrElement","tag","invalid","lowerTag","isSelect","isTextarea","control","hasValue","hasFallback","attributes","needsKey","classes","style","innerHtml","props","IGNORED_KEYS","isEventName","resolveValue","text","classText","collectTruthyKeys","styleText","plainHtml","ssrAttribute","name","attributeName","svg","isFlagAttribute","ssrStyle","raw","given","children","propsChildren","content","rawElementContent","escape","textareaContent","markSelectedOptions","keepLeadingNewline","out"],"sources":["../../../src/server/element.ts"],"sourcesContent":["import { nextKey } from \"../internal/hydration-scope\";\nimport { attributeName, IGNORED_KEYS, isFlagAttribute } from \"../internal/react-names\";\nimport { isEventName, ssrAttribute } from \"./attributes\";\nimport { classText, ssrStyle, styleText } from \"./class-style\";\nimport { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { keepLeadingNewline, markSelectedOptions, textareaContent } from \"./form-controls\";\nimport { isSsrNode, SsrNode } from \"./node\";\nimport { rawElementContent } from \"./raw-text\";\n\n/** A tag name: letters, digits and dashes, starting with a letter. Anything else could break out. */\nconst TAG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;\n\n/** Elements that never have children or a closing tag. */\nconst VOID_ELEMENTS: ReadonlySet<string> = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"command\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"keygen\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n]);\n\n/** Keys that never become attributes: they are handled elsewhere or would reach a prototype. */\nconst SKIPPED_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n \"children\",\n \"ref\",\n]);\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`): null and undefined are empty. */\nfunction innerHtmlOfValue(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return undefined;\n return Reflect.get(value, \"__html\");\n}\n\n/**\n * Joins the static parts of a server template with its dynamic holes into trusted markup: the\n * function compiled server output calls for each element tree. Holes are inserted unchanged, so each\n * must already be escaped (the output of `escape`, `ssrAttribute`, `ssrClass`, ...) or an `SsrNode`;\n * any other value throws, so a raw user value cannot reach the markup.\n *\n * @param parts The static markup, one more entry than there are holes.\n * @param holes The dynamic parts: strings produced by the escaping helpers, or `SsrNode` values.\n * @returns The markup as a trusted `SsrNode`, which `escape` writes without encoding.\n * @throws TypeError when `parts` is not an array of `holes.length + 1` entries, or when a hole is not\n * a string or an `SsrNode`.\n * @example\n * import { escape, renderToString, ssr } from \"@shadow-js/web/server\";\n *\n * const name = \"<Ada>\";\n * const html = renderToString(() => ssr([\"<p>Hello, \", \"</p>\"], escape(name)));\n * // \"<p>Hello, &lt;Ada&gt;</p>\"\n * @see ssrRaw\n * @since 1.0.0\n */\nexport function ssr(parts: readonly string[], ...holes: unknown[]): SsrNode {\n if (!Array.isArray(parts) || parts.length !== holes.length + 1) {\n throw new TypeError(\"ssr(): parts must have one more entry than there are holes.\");\n }\n let html = parts[0] ?? \"\";\n for (let index = 0; index < holes.length; index += 1) {\n const hole = holes[index];\n if (typeof hole === \"string\") html += hole;\n else if (isSsrNode(hole)) html += hole.t;\n else throw new TypeError(\"ssr(): a hole must be an escaped string or an SsrNode.\");\n html += parts[index + 1] ?? \"\";\n }\n return new SsrNode(html);\n}\n\n/**\n * Marks a string as trusted markup that `escape` and `ssr` insert unchanged. Only use it for markup\n * the application wrote itself, never for user input.\n *\n * @param html The markup, inserted unchanged.\n * @returns The markup as a trusted `SsrNode`.\n * @throws TypeError when `html` is not a string.\n * @example\n * import { renderToString, ssrRaw } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => [\"<b>escaped</b>\", ssrRaw(\"<!-- build 42 -->\")]);\n * // \"&lt;b&gt;escaped&lt;/b&gt;<!-- build 42 -->\"\n * @see ssr\n * @since 1.0.0\n */\nexport function ssrRaw(html: string): SsrNode {\n if (typeof html !== \"string\") throw new TypeError(\"ssrRaw(): the markup must be a string.\");\n return new SsrNode(html);\n}\n\n/**\n * Draws the next hydration key of the current scope and returns it as a `data-hk` attribute, such as\n * `' data-hk=\"0-0\"'`: compiled server output calls it for the root element of each template, and\n * the client's `hydrate()` claims the element by that key. Calls must happen in the same order as on\n * the client, so call it only where the compiler would.\n *\n * @returns Markup for the `data-hk` attribute, or `\"\"` outside a server render (no key is drawn).\n * @example\n * import { renderToString, ssr, ssrHydrationKey } from \"@shadow-js/web/server\";\n *\n * const html = renderToString(() => ssr([\"<div\", \">x</div>\"], ssrHydrationKey()));\n * // '<div data-hk=\"0-0\">x</div>'\n * @since 1.0.0\n */\nexport function ssrHydrationKey(): string {\n const key = nextKey();\n return key === undefined ? \"\" : ` data-hk=\"${escapeHtml(key)}\"`;\n}\n\n/**\n * Renders an element from a props object: what compiled server output calls for an element with a\n * spread (`<div {...props} />`), and the server half of `Dynamic` and `element`. It writes the same\n * markup the client's `spread` produces.\n *\n * `class`, `className`, `classList` and `style` are combined into one `class` and one `style`\n * attribute; other keys are attributes, with React names mapped (`htmlFor` is `for`) and HTML boolean\n * attributes (`disabled`, `checked`, ...) written as bare names. `ref`, `children`, `on*` keys and the\n * `on:`, `use:` and `prop:` prefixes are skipped; `attr:` and `bool:` select the attribute and presence\n * forms. `innerHTML` and `dangerouslySetInnerHTML` are written unescaped as the content. On a\n * `textarea` the `value` (or `defaultValue`) is the content; on a `select` it marks the matching\n * `<option selected>` (an array for `multiple`); on other elements `defaultValue` and `defaultChecked`\n * are the `value` and `checked` attributes. Void elements (`img`, `input`, ...) get no content.\n *\n * @param tag Element name: letters, digits and dashes, starting with a letter.\n * @param props The props object (each getter is read once), or `null`.\n * @param children The content, escaped unless it is an `SsrNode`. Undefined (the default) uses the\n * `children` prop.\n * @param needsKey `true` writes the hydration key of this template root first. Default: `false`.\n * @param svg `true` for an SVG element: SVG presentation names are hyphenated (`strokeWidth` is\n * `stroke-width`), other names keep their case. Default: `false`.\n * @returns The element as a trusted `SsrNode`.\n * @throws TypeError `INVALID_TAG_NAME` for an invalid tag, `INVALID_ATTRIBUTE_NAME` for an invalid\n * attribute name, and the errors of {@link ssrAttribute}, `ssrClass` and `ssrStyle` for invalid values.\n * @example\n * import { renderToString, ssrElement } from \"@shadow-js/web/server\";\n *\n * const props = { id: \"save\", disabled: true, class: [\"btn\", { primary: true }], children: \"Save\" };\n * const html = renderToString(() => ssrElement(\"button\", props));\n * // '<button id=\"save\" disabled class=\"btn primary\">Save</button>'\n * @since 1.0.0\n */\nexport function ssrElement(\n tag: string,\n props: unknown,\n children: unknown = undefined,\n needsKey = false,\n svg = false,\n): SsrNode {\n if (typeof tag !== \"string\" || !TAG_NAME.test(tag)) {\n throw invalid(\"INVALID_TAG_NAME\", `\"${String(tag)}\" is not a valid tag name.`);\n }\n const lowerTag = tag.toLowerCase();\n // A browser ignores `value` on these: a textarea's value is its content, a select's value is the\n // `selected` flag of its options. The props are read once and applied to the content below.\n const isSelect = lowerTag === \"select\";\n const isTextarea = lowerTag === \"textarea\";\n const control: { value?: unknown; fallback?: unknown } = {};\n let hasValue = false;\n let hasFallback = false;\n let attributes = needsKey ? ssrHydrationKey() : \"\";\n const classes: string[] = [];\n let style = \"\";\n let innerHtml: string | undefined;\n if (props !== null && typeof props === \"object\") {\n for (const key of Object.keys(props)) {\n if (SKIPPED_KEYS.has(key) || IGNORED_KEYS.test(key)) continue;\n if (\n key === \"ref\" ||\n key.startsWith(\"on:\") ||\n key.startsWith(\"use:\") ||\n key.startsWith(\"prop:\")\n )\n continue;\n if (isEventName(key)) continue;\n if (needsKey && key === \"data-hk\") continue;\n const value = resolveValue(Reflect.get(props, key));\n if (key === \"class\" || key === \"className\") {\n const text = classText(value);\n if (text !== \"\") classes.push(text);\n } else if (key === \"classList\") {\n collectTruthyKeys(value, classes);\n } else if (key === \"style\") {\n style = styleText(value);\n } else if (key === \"innerHTML\") {\n innerHtml = plainHtml(value);\n } else if (key === \"dangerouslySetInnerHTML\") {\n innerHtml = plainHtml(resolveValue(innerHtmlOfValue(value)));\n } else if ((isSelect || isTextarea) && key === \"value\") {\n control.value = value;\n hasValue = true;\n } else if ((isSelect || isTextarea) && key === \"defaultValue\") {\n control.fallback = value;\n hasFallback = true;\n } else if (key.startsWith(\"attr:\")) {\n attributes += ssrAttribute(key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n attributes += ssrAttribute(key.slice(5), value, true);\n } else if (key === \"defaultValue\" || key === \"defaultChecked\") {\n // The attributes of the same name in HTML are the defaults: `value` and `checked`.\n const name = key === \"defaultValue\" ? \"value\" : \"checked\";\n if (!Object.hasOwn(props, name))\n attributes += ssrAttribute(name, value, name === \"checked\");\n } else {\n const name = attributeName(key, svg);\n attributes += ssrAttribute(name, value, isFlagAttribute(name, value));\n }\n }\n }\n if (classes.length > 0) attributes += ` class=\"${escapeHtml(classes.join(\" \"))}\"`;\n if (style !== \"\") attributes += ssrStyle(style);\n if (VOID_ELEMENTS.has(lowerTag)) return new SsrNode(`<${tag}${attributes}>`);\n // Like the DOM `spread`: a `children` prop supplies the content unless the element wrote its own.\n // The text of a script or a style is raw (no entities), so it is written as it is and checked instead.\n const raw = !svg && (lowerTag === \"script\" || lowerTag === \"style\");\n const given = children === undefined ? propsChildren(props) : children;\n let content =\n innerHtml !== undefined ? innerHtml : raw ? rawElementContent(lowerTag, given) : escape(given);\n if (innerHtml === undefined && (hasValue || hasFallback)) {\n const value = hasValue ? control.value : control.fallback;\n content = isTextarea ? textareaContent(value) : markSelectedOptions(value, content);\n } else if (\n (isTextarea || lowerTag === \"pre\" || lowerTag === \"listing\") &&\n innerHtml === undefined\n ) {\n // The parser drops one line break right after these start tags (a textarea's children are its\n // value, as on the client): write one more so the content is read as it was given.\n content = keepLeadingNewline(content);\n }\n return new SsrNode(`<${tag}${attributes}>${content}</${tag}>`);\n}\n\n/** The `children` of a spread props object (read once, so a getter runs once), or undefined. */\nfunction propsChildren(props: unknown): unknown {\n if (props === null || typeof props !== \"object\") return undefined;\n return Reflect.get(props, \"children\");\n}\n\n/** Class names whose key is truthy, from a `classList` object. */\nfunction collectTruthyKeys(value: unknown, out: string[]): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return;\n for (const key of Object.keys(value)) {\n if (key !== \"\" && resolveValue(Reflect.get(value, key))) out.push(key);\n }\n}\n\n/** Raw HTML text for `innerHTML`: null and undefined become \"\", an SsrNode its markup. */\nfunction plainHtml(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (isSsrNode(value)) return value.t;\n if (typeof value === \"symbol\")\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be innerHTML.\");\n return String(value);\n}\n"],"mappings":"A,6lBAYA,MAAMA,EAAW,0BAGXC,kBAAqC,IAAI,IAAI,CACjD,OACA,OACA,KACA,MACA,UACA,QACA,KACA,MACA,QACA,SACA,OACA,OACA,QACA,SACA,QACA,KACF,CAAC,EAGKC,kBAAo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1C,CAAG,CAEzE,CAGA,SAASyB,EAAU,EAAwB,CACzC,GAAIpC,GAAU,KAA6B,MAAO,GAClD,GAAIO,EAAUP,CAAK,EAAG,OAAOA,EAAM,EACnC,GAAI,OAAOA,GAAU,SACnB,MAAMgB,EAAQ,4BAA6B,+BAA+B,EAC5E,OAAO,OAAOhB,CAAK,CACrB,C"}
@@ -1 +1 @@
1
- import{escape as e}from"./escape.js";import{ssrAttribute as t}from"./attributes.js";import{ssrClass as n,ssrStyle as r}from"./class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./form-controls.js";import{ssrRawText as o}from"./raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./element.js";import{createServerPortals as d}from"./portals.js";import{normalizeTags as f}from"../head/validate.js";import{createServerHead as p}from"../head/server-head.js";import{createComponent as m,memo as h}from"./component.js";import{derived as g}from"./derived.js";import{HydrationScript as _,generateHydrationScript as v}from"./hydration-script.js";import{renderToString as y,renderToStringAsync as b}from"./render.js";import{deserialize as x,serialize as S}from"./serialize.js";import{renderToStream as C}from"./stream.js";import{mergeProps as w}from"@shadow-js/core";export{_ as HydrationScript,m as createComponent,p as createServerHead,d as createServerPortals,g as derived,x as deserialize,e as escape,v as generateHydrationScript,h as memo,w as mergeProps,f as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
1
+ import{escape as e}from"./escape.js";import{ssrAttribute as t}from"./attributes.js";import{ssrClass as n,ssrStyle as r}from"./class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./form-controls.js";import{ssrRawText as o}from"./raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./element.js";import{normalizeTags as d}from"../head/validate.js";import{createServerHead as f}from"../head/server-head.js";import{createComponent as p,memo as m}from"./component.js";import{derived as h}from"./derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./hydration-script.js";import{createServerPortals as v}from"./portals.js";import{renderToString as y,renderToStringAsync as b}from"./render.js";import{deserialize as x,serialize as S}from"./serialize.js";import{renderToStream as C}from"./stream.js";import{mergeProps as w}from"@shadow-js/core";export{g as HydrationScript,p as createComponent,f as createServerHead,v as createServerPortals,h as derived,x as deserialize,e as escape,_ as generateHydrationScript,m as memo,w as mergeProps,d as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
@@ -1,2 +1,2 @@
1
- import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
1
+ import{childScope as e,withScope as t}from"../internal/hydration-scope.js";import{SsrError as n}from"./errors.js";import{escape as r}from"./escape.js";import{PortalContext as i}from"../internal/portal-context.js";var a=class{entries=/* @__PURE__ */ new Map;add(e,t){if(!this.entries.has(e)&&this.entries.size>=256)throw new n(`SSR_PORTAL_LIMIT`,`A render produced more than 256 portals; close some overlays or raise the limit.`);this.entries.set(e,t)}clear(){this.entries.clear()}render(e,t){l(e,t,this)}html(){let e=``;for(let[t,n]of this.entries)e+=`<!--portal:${t}-->${n}<!--/portal:${t}-->`;return e}};const o=/* @__PURE__ */ new WeakMap;function s(){let e=new a,t={html:()=>e.html()};return o.set(t,e),t}function c(e){let t=o.get(e);if(t===void 0)throw TypeError(`portals must be created with createServerPortals().`);return t}function l(n,i,a){if(a===null||n===void 0)return;let o=t(e(n),()=>r(i()));a.add(n,o)}function u(e,t){return i({value:e,get children(){return t()}})()}function d(e){if(e===void 0)return null;let t=c(e);return t.clear(),t}export{a as PortalCollector,c as collectorOf,s as createServerPortals,d as portalCollectorFor,l as renderServerPortal,u as withPortalSink};
2
2
  //# sourceMappingURL=portals.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":["PortalCollector","key","SsrError","html","out","collectors","createServerPortals","collector","portals","collectorOf","renderServerPortal","sink","withScope","childScope","escape","children","withPortalSink","PortalContext","build","portalCollectorFor"],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":"A,qNAuCA,IAAaA,EAAb,KAAmD,CACjD,wBAA2B,IAAI,IAE/B,IAAI,EAAa,EAAoB,CACnC,GAAI,CAAC,KAAK,QAAQ,IAAIC,CAAG,GAAK,KAAK,QAAQ,MAAA,IACzC,MAAM,IAAIC,EACR,mBACA,kFACF,EAEF,KAAK,QAAQ,IAAID,EAAKE,CAAI,CAC5B,CAGA,OAAc,CACZ,KAAK,QAAQ,MAAM,CACrB,CAEA,MAAe,CACb,IAAIC,EAAM,GACV,IAAK,GAAM,CAACH,EAAKE,KAAS,KAAK,QAC7B,GAAO,cAAcF,EAAI,KAAKE,EAAK,cAAcF,EAAI,KAEvD,OAAOG,CACT,CACF,EAEA,MAAMC,kBAAa,IAAI,QAmBvB,SAAgBC,GAAqC,CACnD,IAAMC,EAAY,IAAIP,EAChBQ,EAAyB,CAAE,SAAYD,EAAU,KAAK,CAAE,EAE9D,OADAF,EAAW,IAAIG,EAASD,CAAS,EAC1BC,CACT,CAOA,SAAgBC,EAAY,EAAyC,CACnE,IAAMF,EAAYF,EAAW,IAAIG,CAAO,EACxC,GAAID,IAAc,IAAA,GAChB,MAAU,UAAU,qDAAqD,EAE3E,OAAOA,CACT,CAaA,SAAgBG,EACd,EACA,EACA,EACM,CACN,GAAIC,IAAS,MAAQV,IAAQ,IAAA,GAAW,OACxC,IAAME,EAAOS,EAAUC,EAAWZ,CAAG,MAASa,EAAOC,EAAS,CAAC,CAAC,EAChEJ,EAAK,IAAIV,EAAKE,CAAI,CACpB,CAOA,SAAgBa,EAAkB,EAAyB,EAAmB,CAO5E,OANaC,EAAc,CACzB,MAAON,EACP,IAAI,UAAW,CACb,OAAOO,EAAM,CACf,CACF,CACW,CAAC,CAAa,CAC3B,CAOA,SAAgBC,EAAmB,EAA4D,CAC7F,GAAIX,IAAY,IAAA,GAAW,OAAO,KAClC,IAAMD,EAAYE,EAAYD,CAAO,EAErC,OADAD,EAAU,MAAM,EACTA,CACT,C"}
1
+ {"version":3,"file":"portals.js","names":["PortalCollector","key","SsrError","html","renderServerPortal","children","out","collectors","createServerPortals","collector","portals","collectorOf","sink","withScope","childScope","escape","withPortalSink","PortalContext","build","portalCollectorFor"],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n render(key: string | undefined, children: () => unknown): void {\n renderServerPortal(key, children, this);\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":"A,qNAuCA,IAAaA,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AAM,EACTA,CACT,C"}
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{portalCollectorFor as s,withPortalSink as c}from"./portals.js";import{runWithServerHead as l}from"../head/server-head.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(t,r,i,s,d,f){return o(f),c(d,()=>u({value:i,get children(){return l(s,()=>n(e(r),()=>a(t())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=s(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(t=>(i?.clear(),a?.clear(),{html:h(e,n,p,i,a,u),requested:s,tracked:c,errors:l,dispose:t}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new i(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,a,o,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:a,maxPasses:o}=C(t),c={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{c.canceled=!0,t(new i(`SSR_TIMEOUT`,`The render did not finish within ${a} ms.`))},Math.min(a,r))});try{let r=s(t?.portals);return await Promise.race([S(e,n,o,c,t?.head,r,m(t)),u])}finally{clearTimeout(l),c.canceled=!0;for(let e of c.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
1
+ import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{attachRootErrors as o}from"../control-flow/root-errors.js";import{runWithServerHead as s}from"../head/server-head.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{ResourceCacheContext as u,createRoot as d}from"@shadow-js/core";const f=/^[A-Za-z0-9_-]+$/;function p(e){if(typeof e!=`string`||!f.test(e))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);return e}function m(e){return{...e?.onCaughtError===void 0?{}:{onCaughtError:e.onCaughtError},...e?.onUncaughtError===void 0?{}:{onUncaughtError:e.onUncaughtError}}}function h(t,r,i,c,d,f){return o(f),l(d,()=>u({value:i,get children(){return s(c,()=>n(e(r),()=>a(t())))}}))()}function g(e,t){let n=p(t?.renderId??`0`),r=c(t?.portals),i=m(t);return d(a=>{try{return h(e,n,null,t?.head,r,i)}finally{a()}})}function _(e,n,r,i,a,o){let s=/* @__PURE__ */ new Set,c=[],l={caught:[],uncaught:[]},u={onCaughtError:e=>{l.caught.push(e)},...o.onUncaughtError===void 0?{}:{onUncaughtError:e=>{l.uncaught.push(e)}}},f=/* @__PURE__ */ new Set,p={key:e=>{let n=t(e);return s.add(n),n},read:e=>r.has(e)?{value:r.get(e)}:void 0,track:(e,t)=>{f.has(e)||(f.add(e),c.push({key:e,promise:t}))}};return d(t=>(i?.clear(),a?.clear(),{html:h(e,n,p,i,a,u),requested:s,tracked:c,errors:l,dispose:t}))}function v(e,t){for(let n of e.caught)t.onCaughtError?.(n);for(let n of e.uncaught)t.onUncaughtError?.(n)}function y(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function b(e,t){let n={};for(let r of e)t.has(r)&&y(n,r,t.get(r));return n}function x(e){if(e.canceled)throw new i(`SSR_TIMEOUT`,`The render was canceled after its time budget.`)}async function S(e,t,n,r,a,o,s){let c=/* @__PURE__ */ new Map;for(let l=1;;l+=1){x(r);let u=_(e,t,c,a,o,s);if(r.roots.push(u.dispose),u.tracked.length===0)return u.dispose(),v(u.errors,s),{html:u.html,data:b(u.requested,c)};let d=await Promise.allSettled(u.tracked.map(e=>e.promise));x(r);let f=!1;if(d.forEach((e,t)=>{let n=u.tracked[t];n!==void 0&&e.status===`fulfilled`&&(c.has(n.key)||(f=!0),c.set(n.key,e.value))}),u.dispose(),!f)return v(u.errors,s),{html:u.html,data:b(u.requested,c)};if(l>=n)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept loading new resources after ${n} passes; raise maxPasses or flatten the data flow.`)}}function C(e){let t=e?.timeoutMs??1e4,n=e?.maxPasses??10;if(typeof t!=`number`||!(t>0)||!Number.isFinite(t))throw TypeError(`render options: timeoutMs must be a positive finite number.`);if(!Number.isInteger(n)||n<1)throw TypeError(`render options: maxPasses must be an integer of at least 1.`);return{timeoutMs:t,maxPasses:n}}async function w(e,t){let n=p(t?.renderId??`0`),{timeoutMs:a,maxPasses:o}=C(t),s={canceled:!1,roots:[]},l,u=new Promise((e,t)=>{l=setTimeout(()=>{s.canceled=!0,t(new i(`SSR_TIMEOUT`,`The render did not finish within ${a} ms.`))},Math.min(a,r))});try{let r=c(t?.portals);return await Promise.race([S(e,n,o,s,t?.head,r,m(t)),u])}finally{clearTimeout(l),s.canceled=!0;for(let e of s.roots.splice(0))e()}}export{g as renderToString,w as renderToStringAsync};
2
2
  //# sourceMappingURL=render.js.map
@@ -1,2 +1,2 @@
1
- import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{portalCollectorFor as c,withPortalSink as l}from"./portals.js";import{runWithServerHead as u}from"../head/server-head.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=c(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(c){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||c.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},c={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:c,get children(){return l(S,()=>f({value:i,get children(){return u(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||c.close()}catch(e){F(),E||c.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
1
+ import{createRootScope as e,resourceKey as t,withScope as n}from"../internal/hydration-scope.js";import{MAX_TIMER_MS as r,SsrError as i}from"./errors.js";import{escape as a}from"./escape.js";import{StreamContext as o}from"../internal/stream-context.js";import{attachRootErrors as s}from"../control-flow/root-errors.js";import{runWithServerHead as c}from"../head/server-head.js";import{portalCollectorFor as l,withPortalSink as u}from"./portals.js";import{serialize as d}from"./serialize.js";import{ResourceCacheContext as f,createRoot as p,untrack as m}from"@shadow-js/core";const h=/^[A-Za-z0-9_-]+$/;function g(e,t){return`<script${t===void 0?``:` nonce="${t.replace(/[^A-Za-z0-9+/=_-]/g,``)}"`}>${e}<\/script>`}function _(_,v={}){let y=v.renderId??`0`;if(typeof y!=`string`||!h.test(y))throw TypeError(`render options: renderId must be made of letters, digits, _ and -.`);let b=v.timeoutMs??3e4;if(typeof b!=`number`||!(b>0)||!Number.isFinite(b))throw TypeError(`render options: timeoutMs must be a positive finite number.`);let x=v.signal,S=l(v.portals),C=new TextEncoder,w=[],T=()=>{let e=[];for(let t of w.splice(0))try{t.dispose()}catch(t){e.push(t)}if(e.length>0)throw e.length===1?e[0]:AggregateError(e,`Stream cleanup failed.`)},E=!1,D,O=()=>void 0;return new ReadableStream({async start(l){let h=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=e=>{if(x?.aborted)throw x.reason;E||l.enqueue(C.encode(e))},j=()=>{let r={html:``,boundaries:[],requested:/* @__PURE__ */ new Set,held:[],inFlight:/* @__PURE__ */ new Set,caught:[],uncaught:[],answered:!1,dispose:()=>void 0};w.push(r);let i={key:e=>{let n=t(e);return r.requested.add(n),n},read:e=>h.has(e)?{value:h.get(e)}:void 0,track:(e,t,n)=>{k.set(e,t);let i=t.then(t=>{h.set(e,t)},()=>void 0);r.inFlight.add(i),i.finally(()=>r.inFlight.delete(i)),n?.deferStream===!0&&r.held.push({key:e,entry:i})},pending:e=>k.get(e)},l={defer:e=>{r.boundaries.push(e)}},d={onCaughtError:e=>{r.answered?v.onCaughtError?.(e):r.caught.push(e)},...v.onUncaughtError===void 0?{}:{onUncaughtError:e=>{r.answered?v.onUncaughtError?.(e):r.uncaught.push(e)}}};return v.head?.clear(),S?.clear(),r.html=p(t=>(r.dispose=t,s(d),o({value:l,get children(){return u(S,()=>f({value:i,get children(){return c(v.head,()=>n(e(y),()=>a(_())))}}))}})()())),r},M=()=>void 0,N=new Promise((e,t)=>{M=t,D=setTimeout(()=>t(new i(`SSR_TIMEOUT`,`The stream did not finish within ${b} ms.`)),Math.min(b,r))}),P=()=>M(x?.reason??/* @__PURE__ */ Error(`The render was aborted.`));x?.addEventListener(`abort`,P,{once:!0});let F=()=>{clearTimeout(D),x?.removeEventListener(`abort`,P),T()};O=e=>{M(e),F()},N.catch(()=>void 0);try{if(x?.aborted)throw x.reason;let e=j();for(let t=1;e.held.length>0&&(await Promise.race([N,Promise.allSettled(e.held.map(e=>e.entry))]),e.held.some(e=>h.has(e.key)));t+=1){if(t>=10)throw new i(`SSR_BOUNDARY_WATERFALL`,`Resources kept holding the stream after 10 shell renders; flatten the data flow.`);e=j()}e.answered=!0,m(()=>{for(let t of e.caught)v.onCaughtError?.(t);for(let t of e.uncaught)v.onUncaughtError?.(t);v.onShellReady?.(e.html)}),A(e.boundaries.length>0?e.html+g(`window.$S=function(i,f){var t=document.getElementById("s:"+i);if(!t)return;if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){if(c.data==="[b:"+i){var d=1,n=c.nextSibling,e=null;while(n){if(n.nodeType===8){if(n.data.charAt(0)==="["){d++}else if(n.data==="]"){d--;if(d===0){e=n;break}}}n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};`,v.nonce):e.html);let t=()=>{for(let t of e.boundaries.splice(0))A(`<template id="s:${t.id}"></template>`+g(`$S(${JSON.stringify(t.id)},1)`,v.nonce))},n=0;for(;e.boundaries.length>0;){if(e.inFlight.size===0){t();break}let r=h.size;await Promise.race([N,Promise.race([...e.inFlight])]);let i=e.boundaries;e.boundaries=[];let a=!1;for(let e of i){let t=e.rebuild();t!==null&&(a=!0,A(`<template id="s:${e.id}">${t}</template>`+g(`$S(${JSON.stringify(e.id)})`,v.nonce)))}n=h.size===r&&!a?n+1:0,e.boundaries.length>0&&n>=2&&t()}let r={};for(let t of e.requested)h.has(t)&&Object.defineProperty(r,t,{value:h.get(t),enumerable:!0,writable:!0,configurable:!0});Object.keys(r).length>0&&A(`<script type="application/json" data-sh="${y}">${d(r)}<\/script>`),F(),E||l.close()}catch(e){F(),E||l.error(e)}},cancel(e){E=!0,O(e)}})}export{_ as renderToStream};
2
2
  //# sourceMappingURL=stream.js.map
@@ -1 +1 @@
1
- import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssrRawText as o}from"./server/raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./server/element.js";import{createServerPortals as d}from"./server/portals.js";import{normalizeTags as f}from"./head/validate.js";import{createServerHead as p}from"./head/server-head.js";import{createComponent as m,memo as h}from"./server/component.js";import{derived as g}from"./server/derived.js";import{HydrationScript as _,generateHydrationScript as v}from"./server/hydration-script.js";import{renderToString as y,renderToStringAsync as b}from"./server/render.js";import{deserialize as x,serialize as S}from"./server/serialize.js";import{renderToStream as C}from"./server/stream.js";import{mergeProps as w}from"./server/index.js";export{_ as HydrationScript,m as createComponent,p as createServerHead,d as createServerPortals,g as derived,x as deserialize,e as escape,v as generateHydrationScript,h as memo,w as mergeProps,f as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
1
+ import{escape as e}from"./server/escape.js";import{ssrAttribute as t}from"./server/attributes.js";import{ssrClass as n,ssrStyle as r}from"./server/class-style.js";import{ssrSelectValue as i,ssrTextArea as a}from"./server/form-controls.js";import{ssrRawText as o}from"./server/raw-text.js";import{ssr as s,ssrElement as c,ssrHydrationKey as l,ssrRaw as u}from"./server/element.js";import{normalizeTags as d}from"./head/validate.js";import{createServerHead as f}from"./head/server-head.js";import{createComponent as p,memo as m}from"./server/component.js";import{derived as h}from"./server/derived.js";import{HydrationScript as g,generateHydrationScript as _}from"./server/hydration-script.js";import{createServerPortals as v}from"./server/portals.js";import{renderToString as y,renderToStringAsync as b}from"./server/render.js";import{deserialize as x,serialize as S}from"./server/serialize.js";import{renderToStream as C}from"./server/stream.js";import{mergeProps as w}from"./server/index.js";export{g as HydrationScript,p as createComponent,f as createServerHead,v as createServerPortals,h as derived,x as deserialize,e as escape,_ as generateHydrationScript,m as memo,w as mergeProps,d as normalizeTags,C as renderToStream,y as renderToString,b as renderToStringAsync,S as serialize,s as ssr,t as ssrAttribute,n as ssrClass,c as ssrElement,l as ssrHydrationKey,u as ssrRaw,o as ssrRawText,i as ssrSelectValue,r as ssrStyle,a as ssrTextArea};
@@ -1,2 +1,2 @@
1
- import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u}from"./insert.js";import{IGNORED_KEYS as d,attributeName as f,eventPlan as p}from"./internal/react-names.js";import{bindEvent as m}from"./events.js";import{plainText as h,setSelectValue as g}from"./select-value.js";import{onCleanup as _,untrack as v,useRenderEffect as y}from"@shadow-js/core";function b(e){return typeof e!=`object`||!e?``:h(Reflect.get(e,`__html`))}const x=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]);function S(e){return e.length>2&&e.startsWith(`on`)}function C(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function w(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))x.has(C(a))||d.has(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function T(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,v(t))}function E(e,t,n,c,l){if(t===`ref`){if(T(c),typeof n==`function`){let t=n,r=v(()=>t(e));typeof r==`function`&&(c.refCleanup=r)}}else if(t===`autoFocus`)c.autoFocused||(c.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,l);else if(t===`style`)c.styleValue=s(e,n,c.styleValue);else if(t===`classList`)c.classListValue=o(e,a(n),c.classListValue);else if(S(t)){c.unbinders.get(t)?.(),c.unbinders.delete(t);let r=p(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=m(e,r.type,i,!0,r.capture);a!==void 0&&c.unbinders.set(t,a)}else t===`innerHTML`||t===`dangerouslySetInnerHTML`?e.innerHTML=t===`innerHTML`?h(n):b(n):t===`textContent`?e.textContent=h(n):!l&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?g(e,n):!l&&O.has(t)&&t in e?(A(e,t,n,l)&&Reflect.set(e,t,k.has(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=h(n))):D(e,t,n,l)}function D(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let n=f(i,o);n.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,n,a):e(r,n,a)}}const O=/* @__PURE__ */ new Set([`value`,`checked`,`selected`,`muted`,`indeterminate`,`defaultValue`,`defaultChecked`]),k=/* @__PURE__ */ new Set([`value`,`defaultValue`]);function A(e,t,n,r){if(r||!O.has(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return k.has(t)?i!==h(n):i!==!!n}function j(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!A(e,a,o,r))&&(n.values.set(a,o),E(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),E(e,t,void 0,n,r))}function M(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=e.localName===`textarea`;if(!r&&!a){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,n=u(e,null,t);l(n,()=>i()?.children)}let o={values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0};_(()=>{for(let e of o.unbinders.values())e();o.unbinders.clear(),T(o)}),y(()=>w(i(),a),t=>{j(e,t,o,n)})}export{M as spread};
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{applyClass as i,asRecord as a,classList as o,style as s}from"./class-style.js";import{claims as c}from"./internal/hydration-hooks.js";import{bindRegion as l,createRegion as u,watchCommits as d}from"./insert.js";import{IGNORED_KEYS as f,attributeName as p,eventPlan as m,isFlagAttribute as h}from"./internal/react-names.js";import{bindEvent as g}from"./events.js";import{plainText as _,setSelectValue as v}from"./select-value.js";import{onCleanup as y,untrack as b,useRenderEffect as x}from"@shadow-js/core";function S(e){return typeof e!=`object`||!e?``:_(Reflect.get(e,`__html`))}const C=/^(?:__proto__|constructor|prototype)$/;function w(e){return e.length>2&&e.startsWith(`on`)}function T(e){let t=e.indexOf(`:`);return t===-1?e:e.slice(t+1)}function E(e,t){let n=[];if(typeof e!=`object`||!e)return n;let r,i=!1;for(let a of Object.keys(e))C.test(T(a))||f.test(a)||(a===`children`?t&&(r=Reflect.get(e,a),i=!0):n.push([a,Reflect.get(e,a)]));return i&&!n.some(([e])=>e===`value`)&&n.push([`value`,r]),n}function D(e){let t=e.refCleanup;t!==void 0&&(e.refCleanup=void 0,b(t))}function O(e,t,n,c,l){if(t===`ref`){if(D(c),typeof n==`function`){let t=n,r=b(()=>t(e));typeof r==`function`&&(c.refCleanup=r)}}else if(t===`autoFocus`)c.autoFocused||(c.autoFocused=!0,r(e,n));else if(t===`class`||t===`className`)i(e,n,l);else if(t===`style`)c.styleValue=s(e,n,c.styleValue);else if(t===`classList`)c.classListValue=o(e,a(n),c.classListValue);else if(w(t)){c.unbinders.get(t)?.(),c.unbinders.delete(t);let r=m(t,e.localName,e.getAttribute(`type`)?.toLowerCase()??null),i=r.passive&&typeof n==`function`?{handleEvent:n,passive:!0}:n,a=g(e,r.type,i,!0,r.capture);a!==void 0&&c.unbinders.set(t,a)}else t===`innerHTML`||t===`dangerouslySetInnerHTML`?e.innerHTML=t===`innerHTML`?_(n):S(n):t===`textContent`?e.textContent=_(n):!l&&(t===`value`||t===`defaultValue`)&&e instanceof HTMLSelectElement?v(e,n):!l&&A.test(t)&&t in e?(M(e,t,n,l)&&Reflect.set(e,t,j.test(t)?n??``:!!n),t===`value`&&e instanceof HTMLInputElement&&(e.defaultValue=_(n))):k(e,t,n,l)}function k(r,i,a,o){if(i.startsWith(`prop:`))Reflect.set(r,i.slice(5),a);else if(i.startsWith(`attr:`))e(r,i.slice(5),a);else if(i.startsWith(`bool:`))n(r,i.slice(5),a);else{let s=p(i,o);h(s,a)?n(r,s,a):s.startsWith(`xlink:`)?t(r,`http://www.w3.org/1999/xlink`,s,a):e(r,s,a)}}const A=/^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/,j=/^(?:value|defaultValue)$/;function M(e,t,n,r){if(r||!A.test(t)||!(t in e))return!1;if(t===`value`&&e instanceof HTMLSelectElement)return!0;let i=Reflect.get(e,t);return j.test(t)?i!==_(n):i!==!!n}function N(e,t,n,r){let i=/* @__PURE__ */ new Set;for(let[a,o]of t)i.add(a),!(n.values.has(a)&&Object.is(n.values.get(a),o)&&!M(e,a,o,r))&&(n.values.set(a,o),O(e,a,o,n,r));for(let t of[...n.values.keys()])i.has(t)||(n.values.delete(t),O(e,t,void 0,n,r))}function P(e,t,n=!1,r=!1){if(t===null||typeof t!=`object`&&typeof t!=`function`)return;let i=()=>typeof t==`function`?t():t,a=I();if(!r&&e.localName!==`textarea`){let t=c.current.isClaiming()?c.current.takeRegion(e,null)??Array.from(e.childNodes):void 0,r=u(e,null,t);l(r,()=>i()?.children),F(e,n,a)}L(e,i,n,a)}function F(e,t,n){!t&&e instanceof HTMLSelectElement&&d(e,()=>{let t=n.values.has(`value`)?`value`:`defaultValue`;n.values.has(t)&&v(e,n.values.get(t))})}function I(){return{values:/* @__PURE__ */ new Map,unbinders:/* @__PURE__ */ new Map,styleValue:void 0,classListValue:void 0,refCleanup:void 0}}function L(e,t,n,r){let i=e.localName===`textarea`;y(()=>{for(let e of r.unbinders.values())e();r.unbinders.clear(),D(r)}),x(()=>E(t(),i),t=>{N(e,t,r,n)})}export{P as spread};
2
2
  //# sourceMappingURL=spread.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","setAttributeNS","live","applyEntries","current","spread","read","skipChildren","initial","claims","region","createRegion","bindRegion","onCleanup","useRenderEffect","isSVG"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.has(nameOf(key)) || IGNORED_KEYS.has(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.has(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.has(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES: ReadonlySet<string> = new Set([\n \"value\",\n \"checked\",\n \"selected\",\n \"muted\",\n \"indeterminate\",\n \"defaultValue\",\n \"defaultChecked\",\n]);\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES: ReadonlySet<string> = new Set([\"value\", \"defaultValue\"]);\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.has(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.has(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const textarea = el.localName === \"textarea\";\n if (!skipChildren && !textarea) {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n }\n const state: SpreadState = {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,+lBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAAU,WAAnCA,EAAoD,GACjDC,EA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GlCP,EAAM,OAAO,IAAIX,EAAKJ,CAAK,EAC3BiB,EAASE,EAAIf,EAAKJ,EAAOe,EAAOO,CAAG,GAErC,IAAK,IAAMlB,IAAO,CAAC,GAAGW,EAAM,OAAO,KAAK,CAAC,EACnC4B,EAAQ,IAAIvC,CAAG,IACnBW,EAAM,OAAO,OAAOX,CAAG,EAGvBa,EAASE,EAAIf,EAAK,IAAA,GAAWW,EAAOO,CAAG,EAE3C,CA+CA,SAAgBsB,EAAO,EAAa,EAAgB,EAAQ,GAAO,EAAe,GAAa,CAC7F,GAAInC,IAAU,MAAS,OAAOA,GAAU,UAAY,OAAOA,GAAU,WAAa,OAGlF,IAAMoC,MAAuB,OAAOpC,GAAU,WAAcA,EAAwB,EAAIA,EAClFG,EAAWO,EAAG,YAAc,WAClC,GAAI,CAAC2B,GAAgB,CAAClC,EAAU,CAE9B,IAAMmC,EAAUC,EAAO,QAAQ,WAAW,EACrCA,EAAO,QAAQ,WAAW7B,EAAI,IAAI,GAAK,MAAM,KAAKA,EAAG,UAAU,EAChE,IAAA,GACE8B,EAASC,EAAa/B,EAAI,KAAM4B,CAAO,EAC7CI,EAAWF,MAAeJ,EAAK,CAAC,EAA6C,QAAQ,CACvF,CACA,IAAM9B,EAAqB,CACzB,uBAAQ,IAAI,IACZ,0BAAW,IAAI,IACf,WAAY,IAAA,GACZ,eAAgB,IAAA,GAChB,WAAY,IAAA,EACd,EAEAqC,MAAgB,CACd,IAAK,IAAMvB,KAAUd,EAAM,UAAU,OAAO,EAAGc,EAAO,EACtDd,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACDsC,MACQ9C,EAAYsC,EAAK,EAAGjC,CAAQ,EACjC,GAAY,CACX8B,EAAavB,EAAIX,EAASO,EAAOuC,CAAK,CACxC,CACF,CACF,C"}
1
+ {"version":3,"file":"spread.js","names":["innerHtmlValue","value","plainText","FORBIDDEN_NAMES","isEventKey","key","nameOf","colon","readEntries","entries","props","hasValue","IGNORED_KEYS","textarea","runRefCleanup","cleanup","state","untrack","applyKey","callRef","el","autoFocus","applyClass","svg","style","classList","asRecord","plan","eventPlan","handler","unbind","bindEvent","setSelectValue","LIVE_PROPERTIES","liveDiffers","STRING_PROPERTIES","writeKey","setAttribute","setBoolAttribute","wire","attributeName","isFlagAttribute","setAttributeNS","live","applyEntries","current","spread","read","newState","skipChildren","initial","claims","region","createRegion","bindRegion","followOptions","isSVG","applyProps","watchCommits","onCleanup","useRenderEffect"],"sources":["../../src/spread.ts"],"sourcesContent":["import { onCleanup, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute, setAttributeNS, setBoolAttribute } from \"./attributes\";\nimport { autoFocus } from \"./autofocus\";\nimport { applyClass, asRecord, classList, style } from \"./class-style\";\nimport { bindEvent } from \"./events\";\nimport { bindRegion, createRegion, watchCommits } from \"./insert\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { attributeName, eventPlan, IGNORED_KEYS, isFlagAttribute } from \"./internal/react-names\";\nimport { plainText, setSelectValue } from \"./select-value\";\n\n/** The namespace of `xlink:` attributes (SVG's legacy links). */\nconst XLINK_NS = \"http://www.w3.org/1999/xlink\";\n\n/** The HTML of a `dangerouslySetInnerHTML` value (`{ __html }`); null and undefined mean empty. */\nfunction innerHtmlValue(value: unknown): string {\n if (value === null || typeof value !== \"object\") return \"\";\n return plainText(Reflect.get(value, \"__html\"));\n}\n\n/** Keys that would reach a prototype if written as properties. Ignored everywhere. */\nconst FORBIDDEN_NAMES = /^(?:__proto__|constructor|prototype)$/;\n\n/** Mutable bookkeeping for one spread: the values last applied and the event bindings. */\ninterface SpreadState {\n readonly values: Map<string, unknown>;\n readonly unbinders: Map<string, () => void>;\n styleValue: unknown;\n classListValue: Record<string, unknown> | undefined;\n /** Cleanup returned by the `ref` callback currently applied (React 19 ref cleanup). */\n refCleanup: (() => void) | undefined;\n /** `autoFocus` acts on the first application only, as React applies it once at commit. */\n autoFocused?: boolean;\n}\n\n/** True for `on*` keys, which bind event handlers. */\nfunction isEventKey(key: string): boolean {\n return key.length > 2 && key.startsWith(\"on\");\n}\n\n/** The name after a `prop:`, `attr:` or `bool:` namespace, or the whole key. */\nfunction nameOf(key: string): string {\n const colon = key.indexOf(\":\");\n return colon === -1 ? key : key.slice(colon + 1);\n}\n\n/** Reads every prop except children, inside the render effect so each read is tracked. */\nfunction readEntries(props: unknown, textarea: boolean): Array<[string, unknown]> {\n const entries: Array<[string, unknown]> = [];\n if (props === null || typeof props !== \"object\") return entries;\n let value: unknown;\n let hasValue = false;\n for (const key of Object.keys(props)) {\n if (FORBIDDEN_NAMES.test(nameOf(key)) || IGNORED_KEYS.test(key)) continue;\n if (key === \"children\") {\n // A textarea's children are its value (the server writes them as its content): a text node\n // child would not follow the data once the user has typed.\n if (textarea) {\n value = Reflect.get(props, key);\n hasValue = true;\n }\n continue;\n }\n entries.push([key, Reflect.get(props, key)]);\n }\n if (hasValue && !entries.some(([key]) => key === \"value\")) entries.push([\"value\", value]);\n return entries;\n}\n\n/** Runs and forgets the cleanup the last ref callback returned, if any. */\nfunction runRefCleanup(state: SpreadState): void {\n const cleanup = state.refCleanup;\n if (cleanup === undefined) return;\n state.refCleanup = undefined;\n untrack(cleanup);\n}\n\n/** Applies one prop that is new or changed. */\nfunction applyKey(\n el: Element,\n key: string,\n value: unknown,\n state: SpreadState,\n svg: boolean,\n): void {\n if (key === \"ref\") {\n // The ref that was replaced is undone first: its cleanup runs, as for a ref attribute.\n runRefCleanup(state);\n if (typeof value === \"function\") {\n const callRef = value as (node: Element) => unknown;\n const cleanup = untrack(() => callRef(el));\n if (typeof cleanup === \"function\") state.refCleanup = cleanup as () => void;\n }\n return;\n }\n if (key === \"autoFocus\") {\n if (!state.autoFocused) {\n state.autoFocused = true;\n autoFocus(el, value);\n }\n return;\n }\n if (key === \"class\" || key === \"className\") {\n applyClass(el, value, svg);\n return;\n }\n if (key === \"style\") {\n state.styleValue = style(el as HTMLElement | SVGElement, value, state.styleValue);\n return;\n }\n if (key === \"classList\") {\n state.classListValue = classList(el, asRecord(value), state.classListValue);\n return;\n }\n if (isEventKey(key)) {\n state.unbinders.get(key)?.();\n state.unbinders.delete(key);\n // React's spelling: `onChange`, `onFocus`, `...Capture` and passive `onWheel` bind as React does.\n const plan = eventPlan(key, el.localName, el.getAttribute(\"type\")?.toLowerCase() ?? null);\n const handler =\n plan.passive && typeof value === \"function\" ? { handleEvent: value, passive: true } : value;\n const unbind = bindEvent(el, plan.type, handler, true, plan.capture);\n if (unbind !== undefined) state.unbinders.set(key, unbind);\n return;\n }\n if (key === \"innerHTML\" || key === \"dangerouslySetInnerHTML\") {\n el.innerHTML = key === \"innerHTML\" ? plainText(value) : innerHtmlValue(value);\n return;\n }\n if (key === \"textContent\") {\n el.textContent = plainText(value);\n return;\n }\n if (!svg && (key === \"value\" || key === \"defaultValue\") && el instanceof HTMLSelectElement) {\n // A select's value may be an array (`multiple`).\n setSelectValue(el, value);\n return;\n }\n if (!svg && LIVE_PROPERTIES.test(key) && key in el) {\n // State the user changes (a typed value, a toggled box) lives in the property; the attribute is\n // only the default, and writing it stops the element following the data once it is dirty.\n liveDiffers(el, key, value, svg) &&\n Reflect.set(el, key, STRING_PROPERTIES.test(key) ? (value ?? \"\") : Boolean(value));\n // An input's `value` attribute is its default (what a form reset restores) and what the server\n // wrote; keep it equal to the live value like server markup, so both renders match.\n if (key === \"value\" && el instanceof HTMLInputElement) {\n el.defaultValue = plainText(value);\n }\n return;\n }\n writeKey(el, key, value, svg);\n}\n\n/**\n * Writes one prop by its key: a `prop:` property, an `attr:` or `bool:` attribute, or an attribute\n * under its React name. An `undefined` value removes the attribute or resets the property, which is how\n * a prop that disappeared is undone.\n */\nfunction writeKey(el: Element, key: string, value: unknown, svg: boolean): void {\n if (key.startsWith(\"prop:\")) {\n Reflect.set(el, key.slice(5), value);\n } else if (key.startsWith(\"attr:\")) {\n setAttribute(el, key.slice(5), value);\n } else if (key.startsWith(\"bool:\")) {\n setBoolAttribute(el, key.slice(5), value);\n } else {\n const wire = attributeName(key, svg);\n // The server writes these names as flags by truthiness (`disabled: 0` is absent): so does the client.\n if (isFlagAttribute(wire, value)) setBoolAttribute(el, wire, value);\n else if (wire.startsWith(\"xlink:\")) setAttributeNS(el, XLINK_NS, wire, value);\n else setAttribute(el, wire, value);\n }\n}\n\n/** Props written as element properties, like the compiler does for the same names in JSX. */\nconst LIVE_PROPERTIES =\n /^(?:value|checked|selected|muted|indeterminate|defaultValue|defaultChecked)$/;\n/** The properties of {@link LIVE_PROPERTIES} that hold text; the others are booleans. */\nconst STRING_PROPERTIES = /^(?:value|defaultValue)$/;\n\n/**\n * True when a live property (typed value, toggled box) no longer matches the value last applied, so\n * an unchanged prop is written again and the element follows the data.\n */\nfunction liveDiffers(el: Element, key: string, value: unknown, svg: boolean): boolean {\n if (svg || !LIVE_PROPERTIES.test(key) || !(key in el)) return false;\n // A select is written again whenever its props run: setting the value it already shows changes nothing.\n if (key === \"value\" && el instanceof HTMLSelectElement) return true;\n const live = Reflect.get(el, key);\n return STRING_PROPERTIES.test(key) ? live !== plainText(value) : live !== Boolean(value);\n}\n\n/**\n * Applies the entries that changed since the last run and undoes the ones that disappeared.\n * Unchanged values are skipped by identity, so only changed keys touch the DOM.\n */\nfunction applyEntries(\n el: Element,\n entries: Array<[string, unknown]>,\n state: SpreadState,\n svg: boolean,\n): void {\n const current = new Set<string>();\n for (const [key, value] of entries) {\n current.add(key);\n if (\n state.values.has(key) &&\n Object.is(state.values.get(key), value) &&\n !liveDiffers(el, key, value, svg)\n )\n continue;\n state.values.set(key, value);\n applyKey(el, key, value, state, svg);\n }\n for (const key of [...state.values.keys()]) {\n if (current.has(key)) continue;\n state.values.delete(key);\n // A prop that disappeared is applied as `undefined`: every branch of applyKey then undoes it (a ref cleanup\n // runs, a handler is unbound, the class, style and attribute go, a live property returns to empty).\n applyKey(el, key, undefined, state, svg);\n }\n}\n\n/**\n * Applies a whole props object to an element and keeps it in sync: the helper compiled JSX calls for\n * `{...props}` on an element. The props are read inside a render effect, so a getter (or the props\n * accessor) that changes rewrites only the keys whose values changed, and a key that disappears is\n * undone. Event listeners and the last `ref` cleanup are released when the owner is disposed.\n *\n * Keys: `class`/`className`, `classList` and `style` use the class and style helpers; `ref` is called\n * untracked with the element (a returned function is its cleanup); `on*` keys bind with React's\n * spelling (`onChange` on a text input is `input`, `onFocus` is `focusin`, `...Capture` listens\n * in the capture phase, `onWheel` is passive), delegated when the event allows it; `prop:` writes a\n * property, `attr:` and `bool:` an attribute; `innerHTML`, `dangerouslySetInnerHTML` and\n * `textContent` set the content; `value`, `checked`, `selected`, `muted`, `indeterminate`,\n * `defaultValue` and `defaultChecked` are written as properties and re-applied when the user changed\n * them; `autoFocus` applies once. Other keys are attributes, with React names mapped (`htmlFor` is\n * `for`, SVG `strokeWidth` is `stroke-width`). `key`, `suppressHydrationWarning`,\n * `suppressContentEditableWarning`, `__proto__`, `constructor` and `prototype` are ignored.\n *\n * @param el Target element.\n * @param props A props object, or a function returning one (read in the effect). `null` and other\n * values do nothing.\n * @param isSVG `true` for SVG elements: `class` is written as an attribute and SVG names are mapped.\n * Default: `false`.\n * @param skipChildren `true` ignores `children` (the compiler sets it when the JSX has its own\n * children). Default: `false`, which inserts `children` as the element's content; on a `<textarea>`,\n * `children` is its value instead.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` for an attribute name that is not valid, and\n * `SHADOW_EVENT_HANDLER` for an `on*` value that is not a handler.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { spread } from \"@shadow-js/web\";\n *\n * function SaveButton() {\n * const [busy] = useSignal(false);\n * const button = document.createElement(\"button\");\n * spread(button, {\n * class: \"btn\",\n * onClick: () => console.log(\"save\"),\n * get disabled() { return busy(); },\n * children: \"Save\",\n * });\n * return button;\n * }\n * @see element\n * @since 1.0.0\n */\nexport function spread(el: Element, props: unknown, isSVG = false, skipChildren = false): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n // A function is an accessor of the props (`{...props.attrs}` compiles to one): read it inside\n // the effects below so the element follows it.\n const read = (): unknown => (typeof props === \"function\" ? (props as () => unknown)() : props);\n const state = newState();\n if (!skipChildren && el.localName !== \"textarea\") {\n // Spread children own the whole element; ssrElement may emit their text without region markers.\n const initial = claims.current.isClaiming()\n ? (claims.current.takeRegion(el, null) ?? Array.from(el.childNodes))\n : undefined;\n const region = createRegion(el, null, initial);\n bindRegion(region, () => (read() as { readonly children?: unknown } | null)?.children);\n followOptions(el, isSVG, state);\n }\n applyProps(el, read, isSVG, state);\n}\n\n/**\n * New options replace the ones that held the selection, and the value effect does not read\n * `children`: a select spread selects its value again after every commit to its children, as the\n * compiled path does.\n */\nfunction followOptions(el: Element, isSVG: boolean, state: SpreadState): void {\n if (isSVG || !(el instanceof HTMLSelectElement)) return;\n watchCommits(el, () => {\n const key = state.values.has(\"value\") ? \"value\" : \"defaultValue\";\n if (state.values.has(key)) setSelectValue(el, state.values.get(key));\n });\n}\n\n/** The bookkeeping of a spread that has applied nothing yet. */\nfunction newState(): SpreadState {\n return {\n values: new Map(),\n unbinders: new Map(),\n styleValue: undefined,\n classListValue: undefined,\n refCleanup: undefined,\n };\n}\n\n/**\n * Applies the props of `read()` to `el` and keeps them in sync, without a children region: what\n * {@link spread} does after it has bound the children. `Dynamic` calls it directly, because it binds\n * the children itself, so an app that only renders `Dynamic` does not carry the code for a spread's\n * children. A select still selects its value again when `Dynamic` commits new options.\n * @internal\n */\nexport function spreadProps(el: Element, props: unknown, isSVG: boolean): void {\n if (props === null || (typeof props !== \"object\" && typeof props !== \"function\")) return;\n const state = newState();\n followOptions(el, isSVG, state);\n applyProps(\n el,\n () => (typeof props === \"function\" ? (props as () => unknown)() : props),\n isSVG,\n state,\n );\n}\n\nfunction applyProps(el: Element, read: () => unknown, isSVG: boolean, state: SpreadState): void {\n const textarea = el.localName === \"textarea\";\n // Native listeners come off with the owner, even if the element outlives it.\n onCleanup(() => {\n for (const unbind of state.unbinders.values()) unbind();\n state.unbinders.clear();\n runRefCleanup(state);\n });\n useRenderEffect(\n () => readEntries(read(), textarea),\n (entries) => {\n applyEntries(el, entries, state, isSVG);\n },\n );\n}\n"],"mappings":"A,soBAcA,SAASA,EAAe,EAAwB,CAE9C,OADsB,OAAOC,GAAU,WAAnCA,EAAoD,GACjDC,EAAU,QAAQ,IAAID,EAAO,QAAQ,CAAC,CAC/C,CAGA,MAAME,EAAkB,wCAexB,SAASC,EAAW,EAAsB,CACxC,OAAOC,EAAI,OAAS,GAAKA,EAAI,WAAW,IAAI,CAC9C,CAGA,SAASC,EAAO,EAAqB,CACnC,IAAMC,EAAQF,EAAI,QAAQ,GAAG,EAC7B,OAAOE,IAAU,GAAKF,EAAMA,EAAI,MAAME,EAAQ,CAAC,CACjD,CAGA,SAASC,EAAY,EAAgB,EAA6C,CAChF,IAAMC,EAAoC,CAAC,EAC3C,GAAsB,OAAOC,GAAU,WAAnCA,EAA6C,OAAOD,EACxD,IAAIR,EACAU,EAAW,GACf,IAAK,IAAMN,KAAO,OAAO,KAAKK,CAAK,EAC7BP,EAAgB,KAAKG,EAAOD,CAAG,CAAC,GAAKO,EAAa,KAAKP,CAAG,IAC1DA,IAAQ,WAGNQ,IACF,EAAQ,QAAQ,IAAIH,EAAOL,CAAG,EAC9B,EAAW,IAIfI,EAAQ,KAAK,CAACJ,EAAK,QAAQ,IAAIK,EAAOL,CAAG,CAAC,CAAC,GAG7C,OADIM,GAAY,CAACF,EAAQ,MAAM,CAACJ,KAASA,IAAQ,OAAO,GAAGI,EAAQ,KAAK,CAAC,QAASR,CAAK,CAAC,EACjFQ,CACT,CAGA,SAASK,EAAc,EAA0B,CAC/C,IAAMC,EAAUC,EAAM,WAClBD,IAAY,IAAA,KAChB,EAAM,WAAa,IAAA,GACnBE,EAAQF,CAAO,EACjB,CAGA,SAASG,EACP,EACA,EACA,EACA,EACA,EACM,CACN,GAAIb,IAAQ,MAGV,IADAS,EAAcE,CAAK,EACf,OAAOf,GAAU,WAAY,CAC/B,IAAMkB,EAA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B,CAC/B,MAAO,CACL,uBAAQ,IAAI,IACZ,0BAAW,IAAI,IACf,WAAY,IAAA,GACZ,eAAgB,IAAA,GAChB,WAAY,IAAA,EACd,CACF,CAqBA,SAASS,EAAW,EAAa,EAAqB,EAAgB,EAA0B,CAC9F,IAAM5C,EAAWO,EAAG,YAAc,WAElCuC,MAAgB,CACd,IAAK,IAAM7B,KAAUd,EAAM,UAAU,OAAO,EAAGc,EAAO,EACtDd,EAAM,UAAU,MAAM,EACtBF,EAAcE,CAAK,CACrB,CAAC,EACD4C,MACQpD,EAAYuC,EAAK,EAAGlC,CAAQ,EACjC,GAAY,CACX+B,EAAaxB,EAAIX,EAASO,EAAOwC,CAAK,CACxC,CACF,CACF,C"}
@@ -1,2 +1,2 @@
1
- import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let e=a.pop();if(e===void 0)break;let[t,i]=e;for(let e of Array.from(t.childNodes))if(e instanceof Element){let t=r(e);i.appendChild(t),a.push([e,t])}else e instanceof Text&&i.appendChild(n.createTextNode(e.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
1
+ import{MATHML_NS as e}from"./internal/names.js";import{nextKey as t}from"./internal/hydration-scope.js";import{claims as n}from"./internal/hydration-hooks.js";function r(e,t){let n=document,r=e=>{let r=n.createElementNS(t,e.localName);for(let t of Array.from(e.attributes))r.setAttribute(t.name,t.value);return r},i=r(e),a=[[e,i]];for(;a.length>0;){let[e,t]=a.pop();for(let i of Array.from(e.childNodes))if(i instanceof Element){let e=r(i);t.appendChild(e),a.push([i,e])}else i instanceof Text&&t.appendChild(n.createTextNode(i.data))}return i}function i(t,n){let i=document.createElement(`template`),a=n&1?`svg`:n&2?`math`:null;if(a===null)return i.innerHTML=t,Array.from(i.content.childNodes);i.innerHTML=`<${a}>${t}</${a}>`;let o=i.content.firstChild;return o instanceof Element?a===`math`&&o.namespaceURI!==`http://www.w3.org/1998/Math/MathML`?Array.from(r(o,e).childNodes):Array.from(o.childNodes):[]}function a(e,r=0){let a=!!(r&4),o,s=e=>a?document.importNode(e,!0):e.cloneNode(!0);return()=>{let a=n.current.claimElement(t());if(a!==null)return a;let c=o??=i(e,r);if(c.length===1){let[e]=c;if(e!==void 0)return s(e)}let l=document.createDocumentFragment();for(let e of c)l.appendChild(s(e));return l}}export{a as template};
2
2
  //# sourceMappingURL=template.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"template.js","names":["inNamespace","doc","copyOf","copy","namespace","element","attribute","root","source","stack","pair","from","to","child","parse","holder","wrapper","flags","html","MATHML_NS","template","importNode","roots","node","claimed","claims","nextKey","parsed","only","fragment"],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const pair = stack.pop();\n if (pair === undefined) break;\n const [from, to] = pair;\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":"A,+JAmCA,SAASA,EAAY,EAAiB,EAA4B,CAChE,IAAMC,EAAM,SACNC,EAAU,GAA8B,CAC5C,IAAMC,EAAOF,EAAI,gBAAgBG,EAAWC,EAAQ,SAAS,EAC7D,IAAK,IAAMC,KAAa,MAAM,KAAKD,EAAQ,UAAU,EACnDF,EAAK,aAAaG,EAAU,KAAMA,EAAU,KAAK,EAEnD,OAAOH,CACT,EACMI,EAAOL,EAAOM,CAAM,EACpBC,EAAmC,CAAC,CAACD,EAAQD,CAAI,CAAC,EACxD,KAAOE,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAOD,EAAM,IAAI,EACvB,GAAIC,IAAS,IAAA,GAAW,MACxB,GAAM,CAACC,EAAMC,GAAMF,EACnB,IAAK,IAAMG,KAAS,MAAM,KAAKF,EAAK,UAAU,EAC5C,GAAIE,aAAiB,QAAS,CAC5B,IAAMV,EAAOD,EAAOW,CAAK,EACzBD,EAAG,YAAYT,CAAI,EACnBM,EAAM,KAAK,CAACI,EAAOV,CAAI,CAAC,CAC1B,MAAWU,aAAiB,MAC1BD,EAAG,YAAYX,EAAI,eAAeY,EAAM,IAAI,CAAC,CAGnD,CACA,OAAON,CACT,CAGA,SAASO,EAAM,EAAc,EAAuB,CAElD,IAAMC,EAAS,SAAS,cAAc,UAAU,EAC1CC,EACHC,EAAA,EAA8B,MAASA,EAAA,EAAiC,OAAS,KACpF,GAAID,IAAY,KAEd,MADA,GAAO,UAAYE,EACZ,MAAM,KAAKH,EAAO,QAAQ,UAAU,EAE7C,EAAO,UAAY,IAAIC,EAAQ,GAAGE,EAAK,IAAIF,EAAQ,GACnD,IAAMT,EAAOQ,EAAO,QAAQ,WAK5B,OAJMR,aAAgB,QAClBS,IAAY,QAAUT,EAAK,eAAA,qCACtB,MAAM,KAAKP,EAAYO,EAAMY,CAAS,CAAC,CAAC,UAAU,EAEpD,MAAM,KAAKZ,EAAK,UAAU,EAJM,CAAC,CAK1C,CAwBA,SAAgBa,EAAS,EAAc,EAAQ,EAAe,CAC5D,IAAMC,EAAA,GAAcJ,EAAA,GAChBK,EAYEnB,EAAQ,GACZkB,EAAa,SAAS,WAAWE,EAAM,EAAI,EAAIA,EAAK,UAAU,EAAI,EACpE,UAAa,CAEX,IAAMC,EAAUC,EAAO,QAAQ,aAAaC,EAAQ,CAAC,EACrD,GAAIF,IAAY,KAQd,OAAOA,EAGT,IAAMG,EAAiC,IAAUb,EAAMI,EAAMD,CAAK,EAClE,GAAIU,EAAO,SAAW,EAAG,CACvB,GAAM,CAACC,GAAQD,EACf,GAAIC,IAAS,IAAA,GAAW,OAAOzB,EAAKyB,CAAI,CAC1C,CACA,IAAMC,EAAW,SAAS,uBAAuB,EACjD,IAAK,IAAMtB,KAAQoB,EAAQE,EAAS,YAAY1B,EAAKI,CAAI,CAAC,EAC1D,OAAOsB,CACT,CACF,C"}
1
+ {"version":3,"file":"template.js","names":["inNamespace","doc","copyOf","copy","namespace","element","attribute","root","source","stack","from","to","child","parse","holder","wrapper","flags","html","MATHML_NS","template","importNode","roots","node","claimed","claims","nextKey","parsed","only","fragment"],"sources":["../../src/template.ts"],"sourcesContent":["import { checkClaimedTag } from \"./internal/claim\";\nimport { warnOnce } from \"./internal/diagnostics\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { MATHML_NS, TEMPLATE_IMPORT_NODE, TEMPLATE_MATHML, TEMPLATE_SVG } from \"./internal/names\";\n\n/** One start tag: its name, then its attribute text (group 1). */\nconst START_TAG =\n /<[a-zA-Z][^\\s/>]*((?:\\s+[^\\s\"'>/=]+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?)*)\\s*\\/?>/g;\n/** One attribute inside the attribute text of a start tag: its name (group 1). */\nconst ATTRIBUTE = /([^\\s\"'>/=]+)(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s\"'>]+))?/g;\n\n/**\n * Development check for the markup a template is parsed from. The HTML parser keeps the first of two\n * same-named attributes and drops the rest, so `class` and `className` on one element (both compiled\n * to `class`) lose one silently. Warns `DUPLICATE_CLASS_ATTRIBUTE` once; the first attribute still wins.\n */\nfunction warnDuplicateClass(html: string): void {\n for (const tag of html.matchAll(START_TAG)) {\n const attributes = [...(tag[1] ?? \"\").matchAll(ATTRIBUTE)];\n const classes = attributes.filter((match) => match[1]?.toLowerCase() === \"class\");\n if (classes.length < 2) continue;\n const name = /^<([^\\s/>]+)/.exec(tag[0])?.[1] ?? \"element\";\n warnOnce(\n \"DUPLICATE_CLASS_ATTRIBUTE\",\n `<${name}> has two class attributes (class and className both write class). The parser drops the second; keep one.`,\n );\n return;\n }\n}\n\n/**\n * Copies an element subtree into `namespace`, iteratively. Used only when the engine parsed a\n * MathML wrapper as HTML (some DOM implementations do not parse foreign content).\n */\nfunction inNamespace(source: Element, namespace: string): Element {\n const doc = document;\n const copyOf = (element: Element): Element => {\n const copy = doc.createElementNS(namespace, element.localName);\n for (const attribute of Array.from(element.attributes)) {\n copy.setAttribute(attribute.name, attribute.value);\n }\n return copy;\n };\n const root = copyOf(source);\n const stack: Array<[Element, Element]> = [[source, root]];\n while (stack.length > 0) {\n const [from, to] = stack.pop() as [Element, Element];\n for (const child of Array.from(from.childNodes)) {\n if (child instanceof Element) {\n const copy = copyOf(child);\n to.appendChild(copy);\n stack.push([child, copy]);\n } else if (child instanceof Text) {\n to.appendChild(doc.createTextNode(child.data));\n }\n }\n }\n return root;\n}\n\n/** Parses the markup once and returns its top-level nodes. SVG and MathML are parsed in a wrapper. */\nfunction parse(html: string, flags: number): Node[] {\n if (__DEV__) warnDuplicateClass(html);\n const holder = document.createElement(\"template\");\n const wrapper =\n (flags & TEMPLATE_SVG) !== 0 ? \"svg\" : (flags & TEMPLATE_MATHML) !== 0 ? \"math\" : null;\n if (wrapper === null) {\n holder.innerHTML = html;\n return Array.from(holder.content.childNodes);\n }\n holder.innerHTML = `<${wrapper}>${html}</${wrapper}>`;\n const root = holder.content.firstChild;\n if (!(root instanceof Element)) return [];\n if (wrapper === \"math\" && root.namespaceURI !== MATHML_NS) {\n return Array.from(inNamespace(root, MATHML_NS).childNodes);\n }\n return Array.from(root.childNodes);\n}\n\n/**\n * Turns a static HTML string into a factory of fresh DOM copies: the helper compiled JSX uses for the\n * static part of every element tree. The markup is parsed on the first call and cloned on every call\n * after that, so creating a template touches no DOM. Each call draws the next hydration key; during\n * `hydrate()` it returns the server's element for that key instead of a clone.\n *\n * @param html Markup of one or more sibling roots. It is trusted: it is parsed as written, never\n * escaped.\n * @param flags Bit set: `1` parses the content inside `<svg>` so it gets the SVG namespace, `2` does\n * the same for MathML, `4` clones with `document.importNode` (needed for custom elements).\n * Default: `0` (HTML, `cloneNode`).\n * @returns A function that returns a new, detached node on every call: the root itself when the\n * markup has one root, otherwise a `DocumentFragment` holding the roots.\n * @example\n * import { template } from \"@shadow-js/web\";\n *\n * const makeCard = template(`<div class=\"card\"><h2></h2></div>`);\n * const card = makeCard() as HTMLDivElement;\n * (card.firstChild as HTMLElement).textContent = \"Title\";\n * document.body.append(card);\n * @since 1.0.0\n */\nexport function template(html: string, flags = 0): () => Node {\n const importNode = (flags & TEMPLATE_IMPORT_NODE) !== 0;\n let roots: Node[] | undefined;\n // Development holds the parsed roots weakly: the browser never frees an evaluated module, so a\n // hot-updated template would otherwise keep its parsed copy alive for the whole session. Only the\n // `__DEV__` branches reach this helper and `weakRoots`, so production builds carry neither.\n let weakRoots: WeakRef<Node[]> | undefined;\n const devRoots = (): Node[] => {\n const live = weakRoots?.deref();\n if (live !== undefined) return live;\n const fresh = parse(html, flags);\n weakRoots = new WeakRef(fresh);\n return fresh;\n };\n const copy = (node: Node): Node =>\n importNode ? document.importNode(node, true) : node.cloneNode(true);\n return () => {\n // While hydrating, the next template root is the server's element, not a clone.\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null) {\n if (__DEV__) {\n // The template's only root names the tag the server element must have.\n const parsed = devRoots();\n const [only] = parsed;\n if (parsed.length === 1 && only instanceof Element)\n checkClaimedTag(claimed, only.localName);\n }\n return claimed;\n }\n // biome-ignore lint/suspicious/noAssignInExpressions: the first call parses the template once; the assignment is the cache.\n const parsed = __DEV__ ? devRoots() : (roots ??= parse(html, flags));\n if (parsed.length === 1) {\n const [only] = parsed;\n if (only !== undefined) return copy(only);\n }\n const fragment = document.createDocumentFragment();\n for (const root of parsed) fragment.appendChild(copy(root));\n return fragment;\n };\n}\n"],"mappings":"A,+JAmCA,SAASA,EAAY,EAAiB,EAA4B,CAChE,IAAMC,EAAM,SACNC,EAAU,GAA8B,CAC5C,IAAMC,EAAOF,EAAI,gBAAgBG,EAAWC,EAAQ,SAAS,EAC7D,IAAK,IAAMC,KAAa,MAAM,KAAKD,EAAQ,UAAU,EACnDF,EAAK,aAAaG,EAAU,KAAMA,EAAU,KAAK,EAEnD,OAAOH,CACT,EACMI,EAAOL,EAAOM,CAAM,EACpBC,EAAmC,CAAC,CAACD,EAAQD,CAAI,CAAC,EACxD,KAAOE,EAAM,OAAS,GAAG,CACvB,GAAM,CAACC,EAAMC,GAAMF,EAAM,IAAI,EAC7B,IAAK,I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YAAYzB,EAAKI,CAAI,CAAC,EAC1D,OAAOqB,CACT,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"view-transition.js","names":["startViewTransition","doc","flushSync","update","error","failure","callback","types","options","ViewTransition","props"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists.\n useEffect(() => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", props.class);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":"A,4CAkDA,SAAgBA,EACd,EACA,EACe,CACf,IAAMC,EAAM,OAAO,SAAa,IAAc,IAAA,GAAa,SAC3D,GAAIA,IAAQ,IAAA,IAAa,OAAOA,EAAI,qBAAwB,WAAY,CACtE,GAAI,CACFC,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,OAAO,QAAQ,OAAOA,CAAK,CAC7B,CACA,OAAO,QAAQ,QAAQ,CACzB,CACA,IAAIC,EACEC,MAAuB,CAC3B,GAAI,CACFJ,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,EAAU,CAAE,OAAM,CACpB,CACF,EACMG,EAAQC,GAAS,MAIvB,OAHmBP,EAAI,oBACrBM,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAID,EAAW,CAAE,OAAQA,EAAU,MAAO,CAAC,GAAGC,CAAK,CAAE,CAE/E,CAAC,CAAC,SAAS,SAAW,CACpC,GAAIF,IAAY,IAAA,GAAW,MAAMA,EAAQ,KAC3C,CAAC,CACH,CAsDA,SAAgBI,EAAe,EAA+C,CAC5D,UAAaC,EAAM,QAuBrC,C"}
1
+ {"version":3,"file":"view-transition.js","names":["startViewTransition","doc","flushSync","update","error","failure","callback","types","options","ViewTransition","props"],"sources":["../../src/view-transition.ts"],"sourcesContent":["import { type Accessor, flushSync, untrack, useEffect, useId } from \"@shadow-js/core\";\nimport { watchCommits } from \"./insert\";\n\n/** The subset of `Document` the View Transitions API adds (not yet in every TypeScript lib). */\ntype ViewTransitionDocument = Document & {\n startViewTransition?: (callback: (() => void) | { update: () => void; types?: string[] }) => {\n finished: Promise<unknown>;\n };\n};\n\n/**\n * Options of {@link startViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionOptions {\n /**\n * Transition types for this update. CSS selects phases with `:active-view-transition-type(name)`,\n * so one update can animate differently from another (for example forward and back navigation).\n * Ignored where the browser has no View Transitions API.\n * @default undefined (no types: the update runs as a plain transition)\n */\n readonly types?: readonly string[];\n}\n\n/**\n * Runs `update` inside a browser view transition, so the change animates from the old screen to the\n * new one, and resolves when the animation has finished. Without the API (older browsers, or a\n * server) the update runs at once and the promise resolves. Motion preferences are handled by the\n * browser and by the CSS of the page (`prefers-reduced-motion`).\n *\n * The update runs synchronously inside the transition's callback, flushed with {@link flushSync},\n * so the new DOM is what the browser captures. An error thrown by the update rejects the promise.\n *\n * @param update Changes the state the page shows. Called once, synchronously inside the transition\n * (or at once without the API).\n * @param options `types` for CSS phase selectors; see {@link ViewTransitionOptions}. Undefined\n * starts a transition without types.\n * @returns A promise that resolves when the transition has finished (or at once without the API).\n * It rejects with the error `update` threw.\n * @throws Nothing synchronously. An error thrown by `update` rejects the returned promise.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { startViewTransition } from \"@shadow-js/web\";\n *\n * const [, setPage] = useSignal(\"home\");\n * async function openSettings() {\n * await startViewTransition(() => setPage(\"settings\"), { types: [\"forward\"] });\n * }\n * @see ViewTransition\n * @since 1.0.0\n */\nexport function startViewTransition(\n update: () => void,\n options?: ViewTransitionOptions,\n): Promise<void> {\n const doc = typeof document === \"undefined\" ? undefined : (document as ViewTransitionDocument);\n if (doc === undefined || typeof doc.startViewTransition !== \"function\") {\n try {\n flushSync(update);\n } catch (error) {\n return Promise.reject(error);\n }\n return Promise.resolve();\n }\n let failure: { readonly error: unknown } | undefined;\n const callback = (): void => {\n try {\n flushSync(update);\n } catch (error) {\n failure = { error };\n }\n };\n const types = options?.types;\n const transition = doc.startViewTransition(\n types === undefined || types.length === 0 ? callback : { update: callback, types: [...types] },\n );\n return transition.finished.then(() => {\n if (failure !== undefined) throw failure.error;\n });\n}\n\n/**\n * Props of {@link ViewTransition}.\n * @since 1.0.0\n */\nexport interface ViewTransitionProps {\n /**\n * The transition name (`view-transition-name`). Elements with the same name in the old and the new\n * screen are animated as one (`share`); an element that appears or disappears with a name animates\n * in (`enter`) or out (`exit`). `true` makes a unique name.\n * @default undefined (no inline `view-transition-name` is set on the element)\n */\n readonly name?: string | true;\n /**\n * The transition class (`view-transition-class`), to style a group of named elements at once.\n * @default undefined (no inline `view-transition-class` is set)\n */\n readonly class?: string;\n /**\n * The content. Its first element receives the name and class.\n * @default undefined (renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Gives the first element of its children a view transition name and class, so the browser animates\n * that element between the old and the new screen: it enters (an element that appears with the name),\n * exits (one that disappears), updates (the same name with new content) and shares (the same name on\n * both screens, moved or resized). The phases are the browser's own; select them in CSS with\n * `::view-transition-old(name)`, `::view-transition-new(name)` and `:active-view-transition-type()`.\n * `exit=\"none\"` is not offered: the browser decides an exit before the update runs.\n *\n * No wrapper element is added. Without the browser API the name and class are only styles, so the\n * component renders correctly everywhere.\n *\n * @param props See {@link ViewTransitionProps}.\n * @returns An accessor of the content (two anchors and the children).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { ViewTransition } from \"@shadow-js/web\";\n *\n * function Hero() {\n * const [src] = useSignal(\"/hero.png\");\n * return (\n * <ViewTransition name=\"hero\">\n * <img src={src()} />\n * </ViewTransition>\n * );\n * }\n * @see startViewTransition\n * @since 1.0.0\n */\nexport function ViewTransition(props: ViewTransitionProps): Accessor<unknown> {\n if (__SERVER__) return () => props.children;\n // Built once, when the parent first renders it (as Activity does): the server builds it at the same point.\n let built: unknown;\n let ready = false;\n const contentValue = (): unknown => {\n if (!ready) {\n ready = true;\n built = untrack(() => props.children);\n }\n return built;\n };\n const start = document.createTextNode(\"\");\n const end = document.createTextNode(\"\");\n const generated = props.name === true ? `vt-${useId()}` : undefined;\n // Runs after the DOM is committed, so the element it styles exists. The content can change later\n // (a Show that opens, a fallback replaced by content) and the first element is then another one:\n // the name is applied again after each commit to the parent's regions, where that change lands.\n useEffect(() => {\n const name = generated ?? (typeof props.name === \"string\" ? props.name : undefined);\n const transitionClass = props.class;\n const apply = (): void => {\n const element = firstElementBetween(start, end);\n if (element === null) return;\n setOrClear(element, \"view-transition-name\", name);\n setOrClear(element, \"view-transition-class\", transitionClass);\n };\n apply();\n const parent = start.parentNode;\n if (parent !== null) watchCommits(parent, apply);\n });\n return () => [start, contentValue(), end];\n}\n\n/** The first element between two anchors, or null. */\nfunction firstElementBetween(start: Node, end: Node): HTMLElement | null {\n for (let node = start.nextSibling; node !== null && node !== end; node = node.nextSibling) {\n if (node.nodeType === 1) return node as HTMLElement;\n }\n return null;\n}\n\nfunction setOrClear(element: HTMLElement, property: string, value: string | undefined): void {\n if (value === undefined || value === \"\") element.style.removeProperty(property);\n else element.style.setProperty(property, value);\n}\n"],"mappings":"A,4CAmDA,SAAgBA,EACd,EACA,EACe,CACf,IAAMC,EAAM,OAAO,SAAa,IAAc,IAAA,GAAa,SAC3D,GAAIA,IAAQ,IAAA,IAAa,OAAOA,EAAI,qBAAwB,WAAY,CACtE,GAAI,CACFC,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,OAAO,QAAQ,OAAOA,CAAK,CAC7B,CACA,OAAO,QAAQ,QAAQ,CACzB,CACA,IAAIC,EACEC,MAAuB,CAC3B,GAAI,CACFJ,EAAUC,CAAM,CAClB,OAASC,EAAO,CACd,EAAU,CAAE,OAAM,CACpB,CACF,EACMG,EAAQC,GAAS,MAIvB,OAHmBP,EAAI,oBACrBM,IAAU,IAAA,IAAaA,EAAM,SAAW,EAAID,EAAW,CAAE,OAAQA,EAAU,MAAO,CAAC,GAAGC,CAAK,CAAE,CAE/E,CAAC,CAAC,SAAS,SAAW,CACpC,GAAIF,IAAY,IAAA,GAAW,MAAMA,EAAQ,KAC3C,CAAC,CACH,CAsDA,SAAgBI,EAAe,EAA+C,CAC5D,UAAaC,EAAM,QA+BrC,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n el.toggleAttribute(name, Boolean(value));\n}\n"],"mappings":";;;AAGA,MAAM,iBAAiB;;;;;AAMvB,MAAM,iBAAiB;;;;;AAMvB,MAAM,gBAAgB;;AAGtB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,oBAAoB,MAAoB;CACtD,IAAI,CAAC,eAAe,KAAK,IAAI,GAAG,MAAM,qBAAqB,IAAI;AACjE;;AAGA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,YAAY,EAAE;AACpC;;AAGA,SAAS,YAAY,OAAwB;CAC3C,OAAO,oBAAoB,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AAC3E;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,qBAAqB,MAAc,OAAwB;CACzE,MAAM,YAAY,KAAK,YAAY;CACnC,IAAI,CAAC,eAAe,KAAK,SAAS,GAAG,OAAO;CAE5C,OAAO,cAAc,WAAW,MAAM,MAAM,GAAG,CAAC,CAAC,KAAK,WAAW,IAAI,YAAY,KAAK;AACxF;;AAGA,SAAS,cAAc,WAAmB,OAA+B;CACvE,IAAI,UAAU,QAAQ,UAAU,KAAA,GAAW,OAAO;CAClD,IAAI,UAAU,OAA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AAI;CACxB,GAAG,gBAAgB,MAAM,QAAQ,KAAK,CAAC;AACzC"}
1
+ {"version":3,"file":"attributes.js","names":[],"sources":["../../src/attributes.ts"],"sourcesContent":["import { invalidAttributeName, SRCDOC_DYNAMIC_DETAIL, warnOnce } from \"./internal/diagnostics\";\n\n/** Names that can appear in markup: an XML-name subset without `@` or whitespace. */\nconst ATTRIBUTE_NAME = /^[A-Za-z_:][A-Za-z0-9_:.-]*$/;\n\n/**\n * Attributes whose value is a URL and therefore checked for script schemes. The SVG animation values\n * (`animate`, `set`) are checked too: with `attributeName=\"href\"` they write an `href` by animation.\n */\nconst URL_ATTRIBUTES = /^(?:href|src|action|formaction|xlink:href|poster|data|values|from|to|by)$/;\n\n/**\n * `aria-*`, `data-*` and the enumerated attributes: their boolean values are the strings \"true\" and \"false\"\n * rather than a present or absent attribute.\n */\nconst STRING_VALUED = /^(?:aria-|data-|draggable$|spellcheck$|contenteditable$)/;\n\n/** URL prefixes (after normalization) that are never written. */\nconst UNSAFE_URL_PREFIXES = /^(?:javascript:|data:text\\/html|vbscript:)/;\n\n/**\n * Throws a TypeError unless `name` is a valid attribute name. Runs for every name, including the\n * ones that come from spread, so no unvalidated name reaches `setAttribute`.\n * @internal\n */\nexport function assertAttributeName(name: string): void {\n if (!ATTRIBUTE_NAME.test(name)) throw invalidAttributeName(name);\n}\n\n/** Removes C0 and C1 control characters (`\\p{Cc}`), which browsers ignore inside a URL scheme. */\nfunction stripControls(text: string): string {\n return text.replace(/\\p{Cc}/gu, \"\");\n}\n\n/** True when the URL would run script: browsers ignore the controls and case that hide the scheme. */\nfunction isUnsafeUrl(value: string): boolean {\n return UNSAFE_URL_PREFIXES.test(stripControls(value).trim().toLowerCase());\n}\n\n/**\n * Reports whether writing `value` to the attribute `name` would run script: the URL check that\n * {@link setAttribute}, the head registry and the server renderer share. Use it in a custom renderer\n * before writing a URL that came from user data. URL attributes (`href`, `src`, `action`,\n * `formaction`, `xlink:href`, `poster`, `data`) are unsafe when, after removing control\n * characters, trimming and lowercasing, they start with `javascript:`, `data:text/html` or\n * `vbscript:`. The SVG animation attributes `values`, `from`, `to` and `by` are checked the same way,\n * each `;`-separated entry of `values` on its own. `srcdoc` is not a URL but an HTML document, with the\n * trust of `innerHTML`: no scheme check applies to it, so this returns `false` for it (see {@link setAttribute}).\n *\n * @param name Attribute name, in any case.\n * @param value The text that would be written.\n * @returns `true` when the value must not be written; `false` for every other attribute or value.\n * @example\n * import { isUnsafeUrlAttribute } from \"@shadow-js/web/extend\";\n *\n * isUnsafeUrlAttribute(\"href\", \" JavaScript:alert(1)\"); // true\n * isUnsafeUrlAttribute(\"href\", \"https://example.com\"); // false\n * isUnsafeUrlAttribute(\"title\", \"javascript:alert(1)\"); // false: not a URL attribute\n * @see setAttribute\n * @since 1.0.0\n */\nexport function isUnsafeUrlAttribute(name: string, value: string): boolean {\n const lowerName = name.toLowerCase();\n if (!URL_ATTRIBUTES.test(lowerName)) return false;\n // `values` is a `;` list: every entry is a URL of its own.\n return lowerName === \"values\" ? value.split(\";\").some(isUnsafeUrl) : isUnsafeUrl(value);\n}\n\n/** Text to write for `value`, or null when the attribute must be removed. */\nfunction attributeText(lowerName: string, value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (value === false) return STRING_VALUED.test(lowerName) ? \"false\" : null;\n if (value === true) return STRING_VALUED.test(lowerName) ? \"true\" : \"\";\n return String(value);\n}\n\n/** The part of a qualified name after the prefix (`xlink:href` gives `href`). */\nfunction localPart(qualified: string): string {\n const colon = qualified.indexOf(\":\");\n return colon === -1 ? qualified : qualified.slice(colon + 1);\n}\n\n/** Writes or removes one attribute, applying the value rules and the URL check. */\nfunction commit(el: Element, namespace: string | null, qualified: string, value: unknown): void {\n const lowerName = qualified.toLowerCase();\n const text = attributeText(lowerName, value);\n if (text === null) {\n if (namespace === null) el.removeAttribute(qualified);\n else el.removeAttributeNS(namespace, localPart(qualified));\n return;\n }\n // Event handlers are bound as functions, never written as attributes: a string there is script the\n // page would run. The server drops the same names, so both renders agree.\n if (/^on./.test(lowerName)) return;\n if (__DEV__ && lowerName === \"srcdoc\") warnOnce(\"SRCDOC_DYNAMIC\", SRCDOC_DYNAMIC_DETAIL);\n if (isUnsafeUrlAttribute(lowerName, text)) {\n if (__DEV__)\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL in the \"${qualified}\" attribute.`);\n return;\n }\n if (namespace === null) {\n if (el.getAttribute(qualified) !== text) el.setAttribute(qualified, text);\n } else if (el.getAttributeNS(namespace, localPart(qualified)) !== text) {\n el.setAttributeNS(namespace, qualified, text);\n }\n}\n\n/**\n * Sets or removes one attribute with the JSX value rules: the helper compiled templates call for a\n * dynamic attribute, also usable on elements you create yourself. The DOM is touched only when the\n * text changes. A URL attribute whose value would run script (see {@link isUnsafeUrlAttribute}) is\n * left unchanged, and development builds warn once with `UNSAFE_URL_BLOCKED`. Names that start with\n * `on` (`onclick`, ...) are never written, only removed: handlers are bound with `addEventListener`.\n *\n * `srcdoc` is an HTML sink: the value is a document the frame runs, written as it is and trusted like\n * `innerHTML`. Sanitize it, and give the frame a `sandbox` attribute. Compiled templates call this for a\n * computed value only (a literal `srcdoc` is part of the template), so development builds warn once with\n * `SRCDOC_DYNAMIC` for every value written here.\n *\n * @param el Target element.\n * @param name Attribute name. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value `null`, `undefined` and `false` remove the attribute, except that `false` writes\n * `\"false\"` for `aria-*`, `data-*`, `draggable`, `spellcheck` and `contenteditable`. `true` writes\n * `\"\"` (or `\"true\"` for those same names). Any other value is written as `String(value)`.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttribute } from \"@shadow-js/web\";\n *\n * const link = document.createElement(\"a\");\n * setAttribute(link, \"href\", \"https://example.com\");\n * setAttribute(link, \"aria-hidden\", false); // aria-hidden=\"false\"\n * setAttribute(link, \"title\", null); // removes title\n * @see setBoolAttribute\n * @see setAttributeNS\n * @since 1.0.0\n */\nexport function setAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, null, name, value);\n}\n\n/**\n * Sets or removes a namespaced attribute such as `xlink:href` or `xml:lang`, with the value rules\n * and the URL check of {@link setAttribute}. Removal uses the local part of the name (`href` for\n * `xlink:href`).\n *\n * @param el Target element.\n * @param namespace Namespace URI. `\"\"` means no namespace, which behaves exactly like\n * {@link setAttribute}.\n * @param name Qualified name (`prefix:local`). It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value The value, with the same rules as {@link setAttribute}.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setAttributeNS } from \"@shadow-js/web\";\n *\n * const XLINK = \"http://www.w3.org/1999/xlink\";\n * const use = document.createElementNS(\"http://www.w3.org/2000/svg\", \"use\");\n * setAttributeNS(use, XLINK, \"xlink:href\", \"#icon-star\");\n * setAttributeNS(use, XLINK, \"xlink:href\", null); // removes it\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setAttributeNS(el: Element, namespace: string, name: string, value: unknown): void {\n assertAttributeName(name);\n commit(el, namespace === \"\" ? null : namespace, name, value);\n}\n\n/**\n * Sets or removes a presence (boolean) attribute such as `disabled` or `hidden`: the helper compiled\n * templates call for the `bool:` prefix. A truthy value sets the attribute to `\"\"`, a falsy value\n * removes it; the DOM is touched only when presence changes. No URL check applies.\n *\n * @param el Target element.\n * @param name Attribute name, such as `disabled`. It must match `[A-Za-z_:][A-Za-z0-9_:.-]*`.\n * @param value Any value: only its truthiness is read.\n * @throws TypeError `INVALID_ATTRIBUTE_NAME` when `name` is not a valid attribute name.\n * @example\n * import { setBoolAttribute } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * setBoolAttribute(button, \"disabled\", true); // disabled=\"\"\n * setBoolAttribute(button, \"disabled\", 0); // removed\n * @see setAttribute\n * @since 1.0.0\n */\nexport function setBoolAttribute(el: Element, name: string, value: unknown): void {\n assertAttributeName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