@shadow-js/web 1.1.0 → 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/dev/attributes.d.ts +1 -2
  4. package/dist/dev/autofocus.d.ts +1 -2
  5. package/dist/dev/class-style.d.ts +1 -2
  6. package/dist/dev/component.d.ts +1 -2
  7. package/dist/dev/control-flow/activity.d.ts +1 -2
  8. package/dist/dev/control-flow/client-only.d.ts +1 -2
  9. package/dist/dev/control-flow/dynamic.d.ts +1 -2
  10. package/dist/dev/control-flow/error-boundary.d.ts +1 -2
  11. package/dist/dev/control-flow/for.d.ts +1 -2
  12. package/dist/dev/control-flow/fragment.d.ts +1 -2
  13. package/dist/dev/control-flow/index-list.d.ts +1 -2
  14. package/dist/dev/control-flow/lazy.d.ts +1 -2
  15. package/dist/dev/control-flow/no-hydration.d.ts +1 -2
  16. package/dist/dev/control-flow/portal.d.ts +1 -2
  17. package/dist/dev/control-flow/portal.js.map +1 -1
  18. package/dist/dev/control-flow/root-errors.d.ts +2 -3
  19. package/dist/dev/control-flow/show.d.ts +1 -2
  20. package/dist/dev/control-flow/suspense-list.d.ts +2 -3
  21. package/dist/dev/control-flow/suspense.d.ts +1 -2
  22. package/dist/dev/control-flow/switch.d.ts +1 -2
  23. package/dist/dev/derived.d.ts +1 -2
  24. package/dist/dev/element.d.ts +1 -2
  25. package/dist/dev/events.d.ts +1 -2
  26. package/dist/dev/extend.d.ts +9 -0
  27. package/dist/dev/head/components.d.ts +1 -2
  28. package/dist/dev/head/server-head.d.ts +2 -3
  29. package/dist/dev/head/use-head.d.ts +1 -2
  30. package/dist/dev/head/validate.d.ts +1 -2
  31. package/dist/dev/hmr.d.ts +1 -2
  32. package/dist/dev/hmr.js.map +1 -1
  33. package/dist/dev/hydration.d.ts +1 -2
  34. package/dist/dev/insert.d.ts +1 -2
  35. package/dist/dev/insert.js.map +1 -1
  36. package/dist/dev/internal/claim.d.ts +1 -2
  37. package/dist/dev/internal/diagnostics.d.ts +1 -2
  38. package/dist/dev/internal/hydration-hooks.d.ts +1 -2
  39. package/dist/dev/internal/hydration-scope.d.ts +1 -2
  40. package/dist/dev/internal/names.d.ts +1 -2
  41. package/dist/dev/internal/portal-context.d.ts +1 -2
  42. package/dist/dev/internal/reconcile.d.ts +1 -2
  43. package/dist/dev/internal/reconcile.js.map +1 -1
  44. package/dist/dev/internal/stream-context.d.ts +1 -2
  45. package/dist/dev/jsx/aria.d.ts +7 -2
  46. package/dist/dev/jsx/component.d.ts +7 -2
  47. package/dist/dev/jsx/events.d.ts +1 -2
  48. package/dist/dev/jsx/global.d.ts +11 -2
  49. package/dist/dev/jsx/html.d.ts +8 -2
  50. package/dist/dev/jsx/intrinsic.d.ts +10 -2
  51. package/dist/dev/jsx/mathml.d.ts +8 -2
  52. package/dist/dev/jsx/svg.d.ts +13 -2
  53. package/dist/dev/jsx/types.d.ts +1 -2
  54. package/dist/dev/jsx-dev-runtime.d.ts +6 -0
  55. package/dist/dev/jsx-runtime.d.ts +13 -2
  56. package/dist/dev/reactive.d.ts +1 -2
  57. package/dist/dev/render.d.ts +1 -2
  58. package/dist/dev/resource-hints.d.ts +1 -2
  59. package/dist/dev/select-value.d.ts +1 -2
  60. package/dist/dev/server/attributes.d.ts +1 -2
  61. package/dist/dev/server/class-style.d.ts +1 -2
  62. package/dist/dev/server/component.d.ts +1 -2
  63. package/dist/dev/server/derived.d.ts +1 -2
  64. package/dist/dev/server/element.d.ts +1 -2
  65. package/dist/dev/server/errors.js.map +1 -1
  66. package/dist/dev/server/escape.d.ts +1 -2
  67. package/dist/dev/server/form-controls.d.ts +1 -2
  68. package/dist/dev/server/hydration-script.d.ts +1 -2
  69. package/dist/dev/server/index.d.ts +7 -2
  70. package/dist/dev/server/index.js +2 -2
  71. package/dist/dev/server/node.d.ts +1 -2
  72. package/dist/dev/server/node.js.map +1 -1
  73. package/dist/dev/server/portals.d.ts +1 -2
  74. package/dist/dev/server/portals.js.map +1 -1
  75. package/dist/dev/server/raw-text.d.ts +1 -2
  76. package/dist/dev/server/render.d.ts +1 -2
  77. package/dist/dev/server/serialize.d.ts +1 -2
  78. package/dist/dev/server/stream.d.ts +1 -2
  79. package/dist/dev/server/stream.js.map +1 -1
  80. package/dist/dev/server.d.ts +1 -0
  81. package/dist/dev/spread.d.ts +1 -2
  82. package/dist/dev/template.d.ts +1 -2
  83. package/dist/dev/view-transition.d.ts +1 -2
  84. package/dist/prod/attributes.js.map +1 -1
  85. package/dist/prod/autofocus.js.map +1 -1
  86. package/dist/prod/class-style.js.map +1 -1
  87. package/dist/prod/component.js.map +1 -1
  88. package/dist/prod/control-flow/activity.js.map +1 -1
  89. package/dist/prod/control-flow/branch.js.map +1 -1
  90. package/dist/prod/control-flow/client-only.js.map +1 -1
  91. package/dist/prod/control-flow/dynamic.js.map +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/for.js.map +1 -1
  94. package/dist/prod/control-flow/fragment.js.map +1 -1
  95. package/dist/prod/control-flow/hot-link.js.map +1 -1
  96. package/dist/prod/control-flow/index-list.js.map +1 -1
  97. package/dist/prod/control-flow/lazy.js.map +1 -1
  98. package/dist/prod/control-flow/no-hydration.js.map +1 -1
  99. package/dist/prod/control-flow/portal.js.map +1 -1
  100. package/dist/prod/control-flow/root-errors.js.map +1 -1
  101. package/dist/prod/control-flow/show.js.map +1 -1
  102. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  103. package/dist/prod/control-flow/suspense.js.map +1 -1
  104. package/dist/prod/control-flow/switch.js.map +1 -1
  105. package/dist/prod/derived.js.map +1 -1
  106. package/dist/prod/element.js.map +1 -1
  107. package/dist/prod/events.js.map +1 -1
  108. package/dist/prod/head/components.js.map +1 -1
  109. package/dist/prod/head/registry.js.map +1 -1
  110. package/dist/prod/head/server-head.js.map +1 -1
  111. package/dist/prod/head/sink.js.map +1 -1
  112. package/dist/prod/head/use-head.js.map +1 -1
  113. package/dist/prod/head/validate.js.map +1 -1
  114. package/dist/prod/hmr.js.map +1 -1
  115. package/dist/prod/hydration.js.map +1 -1
  116. package/dist/prod/insert.js.map +1 -1
  117. package/dist/prod/internal/accessor.js.map +1 -1
  118. package/dist/prod/internal/claim.js.map +1 -1
  119. package/dist/prod/internal/css-units.js.map +1 -1
  120. package/dist/prod/internal/diagnostics.js.map +1 -1
  121. package/dist/prod/internal/early-events.js.map +1 -1
  122. package/dist/prod/internal/hydration-hooks.js.map +1 -1
  123. package/dist/prod/internal/hydration-scope.js.map +1 -1
  124. package/dist/prod/internal/portal-context.js.map +1 -1
  125. package/dist/prod/internal/react-names.js.map +1 -1
  126. package/dist/prod/internal/reconcile.js.map +1 -1
  127. package/dist/prod/internal/stream-context.js.map +1 -1
  128. package/dist/prod/reactive.js.map +1 -1
  129. package/dist/prod/render.js.map +1 -1
  130. package/dist/prod/resource-hints.js.map +1 -1
  131. package/dist/prod/select-value.js.map +1 -1
  132. package/dist/prod/server/attributes.js.map +1 -1
  133. package/dist/prod/server/class-style.js.map +1 -1
  134. package/dist/prod/server/component.js.map +1 -1
  135. package/dist/prod/server/derived.js.map +1 -1
  136. package/dist/prod/server/element.js.map +1 -1
  137. package/dist/prod/server/errors.js.map +1 -1
  138. package/dist/prod/server/escape.js.map +1 -1
  139. package/dist/prod/server/form-controls.js.map +1 -1
  140. package/dist/prod/server/hydration-script.js.map +1 -1
  141. package/dist/prod/server/node.js.map +1 -1
  142. package/dist/prod/server/portals.js.map +1 -1
  143. package/dist/prod/server/raw-text.js.map +1 -1
  144. package/dist/prod/server/render.js.map +1 -1
  145. package/dist/prod/server/serialize.js.map +1 -1
  146. package/dist/prod/server/stream.js.map +1 -1
  147. package/dist/prod/spread.js.map +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js.map +1 -1
  150. package/dist/server/attributes.js.map +1 -1
  151. package/dist/server/autofocus.js.map +1 -1
  152. package/dist/server/class-style.js.map +1 -1
  153. package/dist/server/component.js.map +1 -1
  154. package/dist/server/control-flow/activity.js.map +1 -1
  155. package/dist/server/control-flow/branch.js.map +1 -1
  156. package/dist/server/control-flow/client-only.js.map +1 -1
  157. package/dist/server/control-flow/dynamic.js.map +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/for.js.map +1 -1
  160. package/dist/server/control-flow/fragment.js.map +1 -1
  161. package/dist/server/control-flow/index-list.js.map +1 -1
  162. package/dist/server/control-flow/lazy.js.map +1 -1
  163. package/dist/server/control-flow/no-hydration.js.map +1 -1
  164. package/dist/server/control-flow/portal.js.map +1 -1
  165. package/dist/server/control-flow/root-errors.js.map +1 -1
  166. package/dist/server/control-flow/show.js.map +1 -1
  167. package/dist/server/control-flow/suspense-list.js.map +1 -1
  168. package/dist/server/control-flow/suspense.js.map +1 -1
  169. package/dist/server/control-flow/switch.js.map +1 -1
  170. package/dist/server/derived.js.map +1 -1
  171. package/dist/server/element.js.map +1 -1
  172. package/dist/server/events.js.map +1 -1
  173. package/dist/server/head/components.js.map +1 -1
  174. package/dist/server/head/registry.js.map +1 -1
  175. package/dist/server/head/server-head.js.map +1 -1
  176. package/dist/server/head/sink.js.map +1 -1
  177. package/dist/server/head/use-head.js.map +1 -1
  178. package/dist/server/head/validate.js.map +1 -1
  179. package/dist/server/hydration.js.map +1 -1
  180. package/dist/server/insert.js.map +1 -1
  181. package/dist/server/internal/accessor.js.map +1 -1
  182. package/dist/server/internal/claim.js.map +1 -1
  183. package/dist/server/internal/css-units.js.map +1 -1
  184. package/dist/server/internal/diagnostics.js.map +1 -1
  185. package/dist/server/internal/early-events.js.map +1 -1
  186. package/dist/server/internal/hydration-hooks.js.map +1 -1
  187. package/dist/server/internal/hydration-scope.js.map +1 -1
  188. package/dist/server/internal/portal-context.js.map +1 -1
  189. package/dist/server/internal/react-names.js.map +1 -1
  190. package/dist/server/internal/reconcile.js.map +1 -1
  191. package/dist/server/internal/stream-context.js.map +1 -1
  192. package/dist/server/reactive.js.map +1 -1
  193. package/dist/server/render.js.map +1 -1
  194. package/dist/server/resource-hints.js.map +1 -1
  195. package/dist/server/select-value.js.map +1 -1
  196. package/dist/server/server/attributes.js.map +1 -1
  197. package/dist/server/server/class-style.js.map +1 -1
  198. package/dist/server/server/component.js.map +1 -1
  199. package/dist/server/server/derived.js.map +1 -1
  200. package/dist/server/server/element.js.map +1 -1
  201. package/dist/server/server/errors.js.map +1 -1
  202. package/dist/server/server/escape.js.map +1 -1
  203. package/dist/server/server/form-controls.js.map +1 -1
  204. package/dist/server/server/hydration-script.js.map +1 -1
  205. package/dist/server/server/node.js.map +1 -1
  206. package/dist/server/server/portals.js.map +1 -1
  207. package/dist/server/server/raw-text.js.map +1 -1
  208. package/dist/server/server/render.js.map +1 -1
  209. package/dist/server/server/serialize.js.map +1 -1
  210. package/dist/server/server/stream.js.map +1 -1
  211. package/dist/server/spread.js.map +1 -1
  212. package/dist/server/template.js.map +1 -1
  213. package/dist/server/view-transition.js.map +1 -1
  214. package/dist/server-dev/control-flow/portal.js.map +1 -1
  215. package/dist/server-dev/insert.js.map +1 -1
  216. package/dist/server-dev/internal/reconcile.js.map +1 -1
  217. package/dist/server-dev/server/errors.js.map +1 -1
  218. package/dist/server-dev/server/index.js +2 -2
  219. package/dist/server-dev/server/node.js.map +1 -1
  220. package/dist/server-dev/server/portals.js.map +1 -1
  221. package/dist/server-dev/server/stream.js.map +1 -1
  222. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"portal.js","names":[],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n onCleanup,\n runWithOwner,\n useContext,\n useRenderEffect,\n} from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n moveRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content: the children are built once, and\n * their nodes and effects keep their identity while they move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) sink?.render?.(key, () => props.children);\n return null;\n }\n // The content is built under the portal's own owner, not under the effect that picks the mount:\n // that effect runs again for each new mount and would dispose what it owns.\n const owner = getOwner();\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = runWithOwner(owner, () =>\n createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n }),\n );\n return { host, region, stopEffects };\n };\n\n /** Mounts the content in `target` the first time, and moves it there afterward. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n // The children were built once, under an owner that stays: the nodes and their effects move, so\n // an input keeps what was typed and a component is neither disposed nor set up again.\n moveRegion(previous.region, target, (node) => appendMoved(target, node));\n mounted = { host: target, region: previous.region, stopEffects: previous.stopEffects };\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":";;;;;;;AAyEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,Y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B,MAAM,UAAU,WAAW,CAAC;GAC5B,IAAI,OAAkB;GACtB,IAAI,YAAY,KAAA,GAAW,OAAO;QAC7B,IAAI,QAAQ,KAAA,KAAa,OAAO,QAAQ,WAAW,GAAG,OAAO;GAClE,UAAU,KAAA;GACV,KAAK,MAAM,QAAQ,SACjB,IAAI,KAAK,eAAe,QAAQ,YAAY,QAAQ,IAAI;GAE1D,UAAU,UAAU,QAAQ,SAAS,IAAI;GACzC;EACF;EAGA,WAAW,SAAS,QAAQ,SAAS,SAAS,YAAY,QAAQ,IAAI,CAAC;EACvE,UAAU;GAAE,MAAM;GAAQ,QAAQ,SAAS;GAAQ,aAAa,SAAS;EAAY;CACvF;CAEA,sBACQ;EAGJ,OAAO;GAAE,MAFI,aAAa,MAAM,KAEpB;GAAG,QADA,MAAM,cAAc;EACb;CACxB,IACC,EAAE,MAAM,aAAa;EACpB,IAAI,SAAS,MAAM;GACjB,QAAQ;GAGR,KAAK,MAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,YAAY,YAAY,IAAI;GACnE,UAAU,KAAA;GACV,IAAe,CAAC,QAAQ;IACtB,SAAS;IACT,QAAQ,KACN,kFACF;GACF;GACA;EACF;EACA,MAAM,SAAe,SAAS,aAAa,IAAI,IAAI;EACnD,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,QAAQ;EACtD,OAAO,MAAM;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
1
+ {"version":3,"file":"portal.js","names":[],"sources":["../../../src/control-flow/portal.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n onCleanup,\n runWithOwner,\n useContext,\n useRenderEffect,\n} from \"@shadow-js/core\";\nimport {\n bindRegion,\n childScope,\n claims,\n createRegion,\n moveRegion,\n nextKey,\n PortalContext,\n type Region,\n removeRegion,\n withScope,\n} from \"../extend\";\n\n/**\n * Props of {@link Portal}.\n * @since 1.0.0\n */\nexport interface PortalProps {\n /**\n * The element that receives the content, or a function returning it (read reactively). A null\n * target, or a function that returns null or undefined, renders nothing and warns once in\n * development (`PORTAL_TARGET_MISSING`).\n * @default document.body (when the prop is omitted)\n */\n readonly mount?: Element | null | (() => Element | null | undefined);\n /**\n * Put the content in a shadow root of the mount, created once and reused. A portal with a shadow\n * root is not server-rendered; the browser creates it.\n * @default false\n */\n readonly useShadow?: boolean;\n /**\n * Reserved for namespace handling. Nodes are inserted as they were created, so the flag does not\n * change the output yet.\n * @default false\n */\n readonly isSVG?: boolean;\n /**\n * The content: a node, text, an array, or an accessor returning them.\n * @default undefined (nothing is rendered)\n */\n readonly children?: unknown;\n}\n\n/** What the portal holds while content is mounted: where it is, its region, and its effects. */\ninterface Mounted {\n readonly host: Node;\n readonly region: Region;\n /** Stops the content's effects. The nodes stay where they are. */\n readonly stopEffects: () => void;\n}\n\n/**\n * How the content of a mount is built. `claimed`: the server markup is adopted (the templates claim\n * it). `unclaimed`: hydrating, but the server sent nothing for this portal, so it is built fresh.\n */\ntype MountMode = \"plain\" | \"claimed\" | \"unclaimed\";\n\n/** A node that can be moved in place (`Element.prototype.moveBefore`, where implemented). */\ninterface MovableNode extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/** Appends `node` to `target`, moving it in place when the target supports `moveBefore`. */\nfunction appendMoved(target: Node, node: Node): void {\n if (typeof (target as Partial<MovableNode>).moveBefore === \"function\") {\n (target as MovableNode).moveBefore(node, null);\n } else {\n target.appendChild(node);\n }\n}\n\n/** The shadow root of an element, attached once when the element has none. */\nfunction shadowRootOf(host: Element): ShadowRoot {\n return host.shadowRoot ?? host.attachShadow({ mode: \"open\" });\n}\n\n/** The mount target of a `mount` prop: the default body, the element, or the function's result. */\nfunction resolveMount(mount: PortalProps[\"mount\"]): Element | null {\n if (mount === undefined) return document.body;\n const value = typeof mount === \"function\" ? mount() : mount;\n return value ?? null;\n}\n\n/**\n * Renders `children` into another part of the document, without a wrapper: the content nodes are\n * inserted directly into the mount element (or its shadow root). Nothing is left at the call site.\n * Disposing the owner removes exactly the nodes the portal inserted; nodes that were already in the\n * mount stay. A reactive `mount` moves the content: the children are built once, and\n * their nodes and effects keep their identity while they move.\n *\n * On the server the content is rendered into the render's `portals` collector (see\n * `createServerPortals`), and the document emits it at the end of `<body>`. When the browser hydrates\n * the portal it adopts that markup instead of creating it again, moving it into the mount if the mount\n * is not `body`. A portal with `useShadow` is not server-rendered; the browser creates it.\n *\n * Events follow the DOM tree. Delegated handlers inside the content fire when the mount is in the\n * document, because the document listener sees the event bubble past the mount. Handlers on\n * elements that wrap the call site do not fire.\n *\n * @param props See {@link PortalProps}.\n * @returns Always null: the portal renders nothing in place.\n * @example\n * import { Portal } from \"@shadow-js/web\";\n *\n * function Modal() {\n * return <div role=\"dialog\">Hello</div>;\n * }\n *\n * function App() {\n * return (\n * <Portal mount={document.getElementById(\"modal-root\")}>\n * <Modal />\n * </Portal>\n * );\n * }\n * @see Dynamic\n * @since 1.0.0\n */\nexport function Portal(props: PortalProps): null {\n // The key of this portal's server block, taken at the call site on the server and in the browser\n // alike. The content renders in a scope of its own (`childScope`), so the keys of the siblings do\n // not depend on whether the content rendered.\n const key = nextKey();\n // A server render provides the portal collector (`renderToString` and friends), so it is recognized\n // by the collector as well as by the build's `isServer` flag: the same server code runs in both.\n const sink = useContext(PortalContext);\n if (isServer || sink !== null) {\n if (props.useShadow !== true) sink?.render?.(key, () => props.children);\n return null;\n }\n // The content is built under the portal's own owner, not under the effect that picks the mount:\n // that effect runs again for each new mount and would dispose what it owns.\n const owner = getOwner();\n let mounted: Mounted | undefined;\n let warned = false;\n // The server block of this portal, taken out of the markers while hydrating; used by the first mount.\n let adopted: Node[] | undefined = claims.current.claimPortal(key);\n\n /** Stops the content's effects, then removes its nodes. Safe to call when nothing is mounted. */\n const unmount = (): void => {\n const current = mounted;\n if (current === undefined) return;\n mounted = undefined;\n current.stopEffects();\n removeRegion(current.region);\n };\n\n /** Creates the content region in `host`, adopting the nodes that are already there. */\n const mountInto = (host: Node, initial: Node[], mode: MountMode): Mounted => {\n const region = createRegion(host, null, initial);\n const stopEffects = runWithOwner(owner, () =>\n createRoot((dispose) => {\n const bind = (): void => {\n bindRegion(region, () => props.children);\n };\n if (mode === \"plain\") bind();\n else if (mode === \"claimed\") withScope(childScope(key), bind);\n else claims.current.withoutClaiming(() => withScope(childScope(key), bind));\n return dispose;\n }),\n );\n return { host, region, stopEffects };\n };\n\n /** Mounts the content in `target` the first time, and moves it there afterward. */\n const moveTo = (target: Node): void => {\n const previous = mounted;\n if (previous === undefined) {\n const initial = adopted ?? [];\n let mode: MountMode = \"plain\";\n if (adopted !== undefined) mode = \"claimed\";\n else if (key !== undefined && claims.current.isClaiming()) mode = \"unclaimed\";\n adopted = undefined;\n for (const node of initial) {\n if (node.parentNode !== target) appendMoved(target, node);\n }\n mounted = mountInto(target, initial, mode);\n return;\n }\n // The children were built once, under an owner that stays: the nodes and their effects move, so\n // an input keeps what was typed and a component is neither disposed nor set up again.\n moveRegion(previous.region, target, (node) => appendMoved(target, node));\n mounted = { host: target, region: previous.region, stopEffects: previous.stopEffects };\n };\n\n useRenderEffect(\n () => {\n const host = resolveMount(props.mount);\n const shadow = props.useShadow === true;\n return { host, shadow };\n },\n ({ host, shadow }) => {\n if (host === null) {\n unmount();\n // The server block was adopted at the call site but has nowhere to live: leaving it would show\n // content the client does not render (stripLeftovers removes the blocks nobody claimed).\n for (const node of adopted ?? []) node.parentNode?.removeChild(node);\n adopted = undefined;\n if (__DEV__ && !warned) {\n warned = true;\n console.warn(\n \"[shadow PORTAL_TARGET_MISSING] Portal has no mount element; nothing is rendered.\",\n );\n }\n return;\n }\n const target: Node = shadow ? shadowRootOf(host) : host;\n if (mounted !== undefined && mounted.host === target) return;\n moveTo(target);\n },\n );\n onCleanup(unmount);\n return null;\n}\n"],"mappings":";;;;;;;AAyEA,SAAS,YAAY,QAAc,MAAkB;CACnD,IAAI,OAAQ,OAAgC,eAAe,YACxD,OAAuB,WAAW,MAAM,IAAI;MAE7C,OAAO,YAAY,IAAI;A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I,YAAY,KAAA,GAAW,OAAO;QAC7B,IAAI,QAAQ,KAAA,KAAa,OAAO,QAAQ,WAAW,GAAG,OAAO;GAClE,UAAU,KAAA;GACV,KAAK,MAAM,QAAQ,SACjB,IAAI,KAAK,eAAe,QAAQ,YAAY,QAAQ,IAAI;GAE1D,UAAU,UAAU,QAAQ,SAAS,IAAI;GACzC;EACF;EAGA,WAAW,SAAS,QAAQ,SAAS,SAAS,YAAY,QAAQ,IAAI,CAAC;EACvE,UAAU;GAAE,MAAM;GAAQ,QAAQ,SAAS;GAAQ,aAAa,SAAS;EAAY;CACvF;CAEA,sBACQ;EAGJ,OAAO;GAAE,MAFI,aAAa,MAAM,KAEpB;GAAG,QADA,MAAM,cAAc;EACb;CACxB,IACC,EAAE,MAAM,aAAa;EACpB,IAAI,SAAS,MAAM;GACjB,QAAQ;GAGR,KAAK,MAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,YAAY,YAAY,IAAI;GACnE,UAAU,KAAA;GACV,IAAe,CAAC,QAAQ;IACtB,SAAS;IACT,QAAQ,KACN,kFACF;GACF;GACA;EACF;EACA,MAAM,SAAe,SAAS,aAAa,IAAI,IAAI;EACnD,IAAI,YAAY,KAAA,KAAa,QAAQ,SAAS,QAAQ;EACtD,OAAO,MAAM;CACf,CACF;CACA,UAAU,OAAO;CACjB,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;MAC9B,IAAI,iBAAiB,KAAK,MAAM,IAAI,IAAI;MACxC,IAAI,UAAU,MAAM,OAAO,wBAAQ,IAAI,IAAI,CAAC,OAAO,IAAI,CAAC;AAC/D;;AAGA,SAAS,WAAW,QAAgB,MAA6B;CAC/D,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU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AAI,QAAQ,IAAI,EAAE,GAAG;KACrB,MAAM,OAAO,EAAE;KACf,aAAa,IAAI;IACnB;IACA,OAAO;GACT,IACC,UAAU;IACT,OAAO,QAAQ,KAAK;GACtB,CACF;EACF,OACE,YAAY,QAAQ,GAAG;CAE3B,CAAC;CACD,OAAO;AACT;;;;;;;;;;;AAYA,SAAgB,WAAW,QAAgB,QAAc,MAAkC;CACzF,MAAM,WAAW,OAAO,MAAM,QAAQ,SAAS,KAAK,eAAe,OAAO,MAAM;CAEhF,UAAU,OAAO,cAAc;EAC7B,KAAK,MAAM,QAAQ,UAAU,KAAK,IAAI;CACxC,CAAC;CAED,OAA6B,SAAS;CACtC,OAAO,SAAS,SAAS,EAAE,EAAE,mBAAmB,OAAO;AACzD;;;;;;AAOA,SAAgB,aAAa,QAAsB;CACjD,KAAK,MAAM,QAAQ,OAAO,OACxB,IAAI,KAAK,eAAe,OAAO,QAAQ,OAAO,OAAO,YAAY,IAAI;CAEvE,OAAO,QAAQ,CAAC;CAChB,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;AAkBA,SAAgB,OAAO,QAAc,QAA2B;CAC9D,MAAM,OAAO,WAAW,MAAM,CAAC,CAAC,eAAe,EAAE;CACjD,OAAO,aAAa,MAAM,MAAM;CAChC,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,OACd,QACA,OACA,YACA,SACS;CACT,MAAM,iBAAiB,cAAc;CAIrC,OAAO,WADQ,aAAa,QAAQ,gBADlC,YAAY,KAAA,IAAY,OAAO,QAAQ,WAAW,QAAQ,cAAc,IAAI,OAEvD,GAAG,OAAO,mBAAmB,IAAI;AAC1D"}
1
+ {"version":3,"file":"insert.js","names":[],"sources":["../../src/insert.ts"],"sourcesContent":["import { onCleanup, useRenderEffect } from \"@shadow-js/core\";\nimport {\n addCleanup,\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n type Owner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { leaves } from \"./internal/accessor\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { keepFocus, reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty. A marker can be a node\n * another region owns and later replaces, so the region created right behind another one on the same parent\n * gives that one an anchor of its own (see `linkRegion`): the marker of every region is then either static\n * content or an anchor nobody replaces.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n anchor: Node | null;\n marker: Node | null;\n /** The owner of the effect that keeps a reactive region up to date; unset until then (and for a static region). */\n owner?: Owner | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The newest reactive unanchored region of each parent: the one the next such region may have to give an anchor. */\nconst tails = new WeakMap<Node, Region>();\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * The children a fragment held when it was first inserted. Inserting empties a fragment, and an effect\n * that runs again flattens the same fragment value once more: it must still give those nodes.\n */\nconst fragmentChildren = new WeakMap<DocumentFragment, Node[]>();\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call?: (fn: () => unknown) => unknown): Part[] {\n const parts: Part[] = [];\n const cycle = __DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\";\n for (const item of leaves(root, cycle, call)) {\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (item instanceof DocumentFragment) {\n const kids = fragmentChildren.get(item) ?? [...item.childNodes];\n fragmentChildren.set(item, kids);\n for (const child of kids) parts.push(child);\n } else parts.push(item instanceof Node ? item : String(item)); // strings, numbers and anything else that is text\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child (`last`), or its marker. */\nfunction endOf(region: Region, last: Node | undefined): Node | null {\n if (region.anchor !== null) return region.anchor;\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Callbacks to run after a region of a parent has committed (see `watchCommits`). */\nconst commitWatchers = new WeakMap<Node, Set<() => void>>();\n\n/**\n * Runs `run` after every commit to a region of `parent`, so code that depends on which nodes the\n * parent holds (a name on the first element of a content region) can follow a change of content.\n * The watch ends with the owner that is current when this is called.\n * @internal\n */\nexport function watchCommits(parent: Node, run: () => void): void {\n const set = commitWatchers.get(parent) ?? new Set<() => void>();\n commitWatchers.set(parent, set.add(run));\n onCleanup(() => {\n set.delete(run);\n });\n}\n\n/**\n * Like {@link watchCommits}, for a watch that lives as long as `parent` does: it is not tied to the owner that is\n * current, so a binding that runs again does not end it. The select's value (see `setSelectValue`) uses it.\n * @internal\n */\nexport function keepWatchingCommits(parent: Node, run: () => void): void {\n commitWatchers.set(parent, (commitWatchers.get(parent) ?? new Set<() => void>()).add(run));\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n // Makes the DOM show the new nodes for this region.\n const next = materialize(region, parts);\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const first = attached[0];\n const end = endOf(region, attached.at(-1));\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n commitWatchers.get(parent)?.forEach((run) => {\n run();\n });\n // The options of an optgroup are the select's options.\n if (parent.nodeName === \"OPTGROUP\" && parent.parentNode !== null) {\n commitWatchers.get(parent.parentNode)?.forEach((run) => {\n run();\n });\n }\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, undefined));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n // The nodes of `initial` (already in the parent) that the region adopts as its current content.\n const nodes: Node[] = [];\n if (initial !== undefined) {\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n nodes.push(part);\n }\n }\n const marker = nodes.length > 0 ? (nodes[0] as Node).previousSibling : parent.lastChild;\n const region: Region = {\n parent,\n anchor: anchorNode,\n marker,\n nodes,\n texts: null,\n };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * Called for a region that keeps changing and has no anchor. When the previous such region of the parent is alive\n * and ends exactly where this one starts, that region gets an empty Text node there as its anchor. Its content then\n * always goes before that node, and this region's marker is the node, so no region has a marker that a sibling\n * region can replace: the order of the calls holds however the regions change. A region with static content\n * between it and this one needs nothing, because its marker and its end are the static nodes. (A function of its\n * own, so the cleanup it registers holds nothing but the anchor: a closure made inside `bindRegion` would keep\n * the regions of that call alive as long as the parent's owner.)\n */\nfunction linkRegion(region: Region): void {\n const parent = region.parent;\n const tail = tails.get(parent);\n region.owner = currentOwner();\n tails.set(parent, region);\n const start = region.nodes[0] ?? null;\n if (tail === undefined || tail.owner?.disposed || endOf(tail, tail.nodes.at(-1)) !== start)\n return;\n const text = anchor(parent, start);\n tail.anchor = region.marker = text;\n // The anchor is the tail's alone and goes with it, so a region replaced by another one over and over adds\n // nothing to the parent. The region behind it, if empty, is then placed at the end like any region whose marker\n // is gone.\n if (tail.owner) addCleanup(tail.owner, () => text.remove());\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() as unknown[];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once. `ordered` is for `insert()` without an anchor: a region that keeps changing then keeps\n * its place among the other such regions of its parent (see `linkRegion`).\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown, ordered?: boolean): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n if (ordered === true) linkRegion(region);\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n // One memo per accessor function, owned by this effect (the effect that evaluates the region's expression,\n // so a new result drops them all; the effect that resolves the result runs many times and must not own\n // them). The memos of accessors the last run did not meet are disposed, which bounds the cache by what the\n // region currently shows.\n const owner = currentOwner();\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n const call = (fn: () => unknown): unknown => {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n };\n useRenderEffect(\n () => {\n touched = new Set();\n const parts = flatten(raw, call);\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Moves a region to a new parent: its nodes still in the old parent go through `move` (which puts\n * each at the end of `parent`), and later commits reconcile there. The region keeps its effects, so\n * what it shows is not built again. Only for a region without an anchor.\n * @param region The region to move.\n * @param parent The node that receives the region's nodes.\n * @param move Puts one node at the end of `parent` (`appendChild`, or `moveBefore` where it exists).\n * @since 1.0.3\n * @internal\n */\nexport function moveRegion(region: Region, parent: Node, move: (node: Node) => void): void {\n const attached = region.nodes.filter((node) => node.parentNode === region.parent);\n // A move that is not in place (appendChild) blurs a focused input: it gets the focus back.\n keepFocus(region.parent, () => {\n for (const node of attached) move(node);\n });\n // Read-only for everyone else: only a move changes where a region lives.\n (region as { parent: Node }).parent = parent;\n region.marker = attached[0]?.previousSibling ?? parent.lastChild;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted. Regions without an\n * anchor on one parent keep the order of the calls, whatever they show and however often a sibling\n * region replaces its nodes: when a reactive region is created right where the previous one ends, the\n * previous one gets an empty Text node as its anchor there (removed again when that region is disposed).\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value, resolvedAnchor === null);\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,wBAAQ,IAAI,QAAsB;;AAGxC,SAAS,WAAW,MAAsB;CACxC,OAAO,gBAAgB,WAAW,OAAQ,KAAK,iBAAiB;AAClE;;AAGA,SAAS,SAAS,QAAgB,MAAqB;CACrD,MAAM,QAAQ,OAAO;CACrB,OAAO,UAAU,QAAS,iBAAiB,OAAO,MAAM,IAAI,IAAY;AAC1E;;AAGA,SAAS,QAAQ,QAAgB,MAAkB;CACjD,MAAM,QAAQ,OAAO;CACrB,IAAI,UAAU,MAAM,OAAO,QAAQ;M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,mBAAmB,IAAI;AAC1D"}
@@ -1 +1 @@
1
- {"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":";;;;;;;;AAYA,SAAgB,UAAU,IAAU,KAAuB;CACzD,MAAM,OAAO,GAAG,YAAY;CAC5B,MAAM,SAAS,KAAK;CACpB,IAAI;CACJ,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F;;AAGA,SAAS,WAAW,QAAc,MAA8B;CAC9D,IAAI,SAAS,KAAA,KAAa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GAAG;EACnD,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,KAAA,GAAW,OAAO,IAAI,MAAM,KAAK;CAChD;CAEA,MAAM,YAAsB,CAAC;CAC7B,KAAK,IAAI,QAAQ,MAAM,QAAQ,UAAU,SAAS,GAAG;EACnD,MAAM,OAAO,KAAK;EAClB,MAAM,WAAW,OAAO,IAAI,IAAI;EAChC,IAAI,aAAa,KAAA,GAAW,WAAW,QAAQ,IAAI;OAC9C,UAAU,KAAK,QAAQ;CAC9B;CAKA,IAAI,UAAU,WAAW,GAAG;EAC1B,KAAK,MAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,GAAG,OAAO,aAAa,MAAM,MAAM;EAC/E;CACF;CAEA,MAAM,SAAS,IAAI,WAAW,WAAW,IAAI;CAC7C,sBAAsB,WAAW,MAAM,MAAM;CAC7C,MAAM,UAAU,OAAQ,OAAkC,eAAe;CAIzE,MAAM,OAAO,OAAO,YAAY;CAChC,MAAM,SAAS,UAAU,OAAQ,KAAK;CACtC,IAAI,aAAa;CACjB,KAAK,IAAI,QAAQ,WAAW,GAAG,SAAS,MAAM,SAAS,GAAG;EACxD,MAAM,OAAO,KAAK;EAClB,IAAI,OAAO,QAAQ,UAAU,GAAG;GAC9B,IAAI,WAAW,KAAK,eAAe,QACjC,OAA0B,WAAW,MAAM,UAAU;QAClD,OAAO,aAAa,MAAM,UAAU;EAC3C;EACA,aAAa;CACf;CACA,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F"}
1
+ {"version":3,"file":"reconcile.js","names":[],"sources":["../../../src/internal/reconcile.ts"],"sourcesContent":["/** A parent that can move a child in place (Element.prototype.moveBefore, where implemented). */\ninterface MovableParent extends Node {\n moveBefore(node: Node, child: Node | null): void;\n}\n\n/**\n * Runs `run`, which moves nodes in the tree of `at` without `moveBefore`: a browser blurs a focused\n * element that `insertBefore` moves, so a focused element of that tree that lost the focus gets it\n * back, without scrolling. A text control keeps its selection across the move, and `focus()` keeps\n * it. The focused element is read once, before `run`.\n * @internal\n */\nexport function keepFocus(at: Node, run: () => void): void {\n const root = at.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = root.activeElement as HTMLElement | null | undefined;\n run();\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n\n/** Removes `node` only when it is still a child of `parent`, so detached nodes are ignored. */\nfunction removeNode(parent: Node, node: Node | undefined): void {\n if (node !== undefined && node.parentNode === parent) parent.removeChild(node);\n}\n\n/**\n * Marks the members of one longest strictly increasing subsequence of `values` in `marks`, where\n * `values[k]` is the target position of the k-th surviving node and `marks[v - offset]` is set for\n * target position `v`. Patience sorting: O(n log n).\n */\nfunction markLongestIncreasing(values: readonly number[], offset: number, marks: Uint8Array): void {\n // tails[k]: index into `values` of the smallest tail of an increasing run of length k + 1.\n const tails: number[] = [];\n const previous: number[] = values.map(() => -1);\n for (let index = 0; index < values.length; index += 1) {\n const value = values[index] as number;\n let low = 0;\n let high = tails.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n const probe = values[tails[middle] as number] as number;\n if (probe < value) low = middle + 1;\n else high = middle;\n }\n // `tails[-1]` is undefined, which reads as no predecessor.\n previous[index] = tails[low - 1] ?? -1;\n tails[low] = index;\n }\n let cursor = tails.at(-1) ?? -1;\n while (cursor !== -1) {\n marks[(values[cursor] as number) - offset] = 1;\n cursor = previous[cursor] as number;\n }\n}\n\n/**\n * Updates one region of `parent`'s children from the nodes `prev` to the nodes `next`, keeping every\n * node that stays and moving as few as possible: the list reconciliation `insert` performs for arrays\n * (and so for `For`). Use it in a custom list renderer.\n *\n * Preconditions: `prev` are the nodes this region owns, in DOM order and all children of `parent`;\n * `next` holds no duplicates; `end` is the node after the region (null for the end of `parent`).\n *\n * Strategy, in three steps:\n * 1. Trim the common prefix and suffix: appends, prepends, and removals at either end touch\n * only the nodes that changed (no move at all).\n * 2. Remove the nodes that left the value. A node that is still present is never removed.\n * 3. Place the rest from the end of `next` backwards. Nodes on a longest increasing subsequence of\n * surviving positions stay where they are; every other node is moved (or inserted) directly\n * before the node that follows it in `next`. Moves use `moveBefore` when the parent has it,\n * which keeps focus and iframe state, and `insertBefore` otherwise (a focused element that the move\n * blurred gets the focus back). Each node moves at most once,\n * and the number of moves is minimal for the surviving order.\n *\n * @param parent The parent of the region.\n * @param prev The nodes the region holds now, in DOM order, all children of `parent`.\n * @param next The nodes the region must hold, in order, without duplicates. A node of `prev` that is\n * not in `next` is removed; a node of `next` that is not in `prev` is inserted.\n * @param end The node right after the region; `null` when the region runs to the end of `parent`.\n * @example\n * import { reconcileNodes } from \"@shadow-js/web/extend\";\n *\n * const item = (text: string): HTMLLIElement =>\n * Object.assign(document.createElement(\"li\"), { textContent: text });\n * const list = document.createElement(\"ul\");\n * const a = item(\"a\");\n * const b = item(\"b\");\n * const c = item(\"c\");\n * list.append(a, b, c);\n * reconcileNodes(list, [a, b, c], [c, a], null); // removes b, moves c before a\n * @since 1.0.0\n */\nexport function reconcileNodes(\n parent: Node,\n prev: readonly Node[],\n next: readonly Node[],\n end: Node | null,\n): void {\n const prevLength = prev.length;\n const nextLength = next.length;\n\n let head = 0;\n while (head < prevLength && head < nextLength && prev[head] === next[head]) head += 1;\n let prevTail = prevLength;\n let nextTail = nextLength;\n while (prevTail > head && nextTail > head && prev[prevTail - 1] === next[nextTail - 1]) {\n prevTail -= 1;\n nextTail -= 1;\n }\n if (prevTail === head && nextTail === head) return;\n\n // Everything in the common suffix is already in place, so the middle goes before its first node.\n const before = nextTail < nextLength ? (next[nextTail] ?? null) : end;\n\n if (nextTail === head) {\n for (let index = head; index < prevTail; index += 1) removeNode(parent, prev[index]);\n return;\n }\n\n const target = new Map<Node, number>();\n for (let index = head; index < nextTail; index += 1) {\n const node = next[index];\n if (node !== undefined) target.set(node, index);\n }\n\n const survivors: number[] = [];\n for (let index = head; index < prevTail; index += 1) {\n const node = prev[index] as Node;\n const position = target.get(node);\n if (position === undefined) removeNode(parent, node);\n else survivors.push(position);\n }\n\n // Nothing survived: the new nodes go in document order. Inserting them back to front (the move loop below)\n // ends with the same tree but not the same steps, and a `<select>` picks its shown option while its options\n // arrive, so a replaced option list would show the wrong value.\n if (survivors.length === 0) {\n for (const node of next.slice(head, nextTail)) parent.insertBefore(node, before);\n return;\n }\n\n const stable = new Uint8Array(nextTail - head);\n markLongestIncreasing(survivors, head, stable);\n const movable = typeof (parent as Partial<MovableParent>).moveBefore === \"function\";\n\n // Without moveBefore, insertBefore blurs a focused element it moves: the focused element is read once\n // for the pass and gets the focus back (without scrolling) when the moves took it.\n const root = parent.getRootNode() as Partial<DocumentOrShadowRoot>;\n const active = movable ? null : (root.activeElement as HTMLElement | null | undefined);\n let anchorNode = before;\n for (let index = nextTail - 1; index >= head; index -= 1) {\n const node = next[index] as Node;\n if (stable[index - head] !== 1) {\n if (movable && node.parentNode === parent)\n (parent as MovableParent).moveBefore(node, anchorNode);\n else parent.insertBefore(node, anchorNode);\n }\n anchorNode = node;\n }\n if (active != null && root.activeElement !== active) active.focus({ preventScroll: true });\n}\n"],"mappings":";;;;;;;;AAYA,SAAgB,UAAU,IAAU,KAAuB;CACzD,MAAM,OAAO,GAAG,YAAY;CAC5B,MAAM,SAAS,KAAK;CACpB,IAAI;CACJ,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F;;AAGA,SAAS,WAAW,QAAc,MAA8B;CAC9D,IAAI,SAAS,KAAA,KAAa,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI;AAC/E;;;;;;AAOA,SAAS,sBAAsB,QAA2B,QAAgB,OAAyB;CAEjG,MAAM,QAAkB,CAAC;CACzB,MAAM,WAAqB,OAAO,UAAU,EAAE;CAC9C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS,GAAG;EACrD,MAAM,QAAQ,OAAO;EACrB,IAAI,MAAM;EACV,IAAI,OAAO,MAAM;EACjB,OAA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AK,QAAQ;CAC9B;CAKA,IAAI,UAAU,WAAW,GAAG;EAC1B,KAAK,MAAM,QAAQ,KAAK,MAAM,MAAM,QAAQ,GAAG,OAAO,aAAa,MAAM,MAAM;EAC/E;CACF;CAEA,MAAM,SAAS,IAAI,WAAW,WAAW,IAAI;CAC7C,sBAAsB,WAAW,MAAM,MAAM;CAC7C,MAAM,UAAU,OAAQ,OAAkC,eAAe;CAIzE,MAAM,OAAO,OAAO,YAAY;CAChC,MAAM,SAAS,UAAU,OAAQ,KAAK;CACtC,IAAI,aAAa;CACjB,KAAK,IAAI,QAAQ,WAAW,GAAG,SAAS,MAAM,SAAS,GAAG;EACxD,MAAM,OAAO,KAAK;EAClB,IAAI,OAAO,QAAQ,UAAU,GAAG;GAC9B,IAAI,WAAW,KAAK,eAAe,QAChC,OAAyB,WAAW,MAAM,UAAU;QAClD,OAAO,aAAa,MAAM,UAAU;EAC3C;EACA,aAAa;CACf;CACA,IAAI,UAAU,QAAQ,KAAK,kBAAkB,QAAQ,OAAO,MAAM,EAAE,eAAe,KAAK,CAAC;AAC3F"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":";;;;;;AAQA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA,YAAY,MAAoB,QAAgB;EAC9C,MAAgB,WAAW,KAAK,IAAI,QAA2B;EAC/D,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,QAAQ,MAAc,QAA2B;CAC/D,uBAAO,IAAI,UAAoB,WAAW,KAAK,IAAI,QAA2B;AAChF;;;;;;AAOA,MAAa,eAAe"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../../src/server/errors.ts"],"sourcesContent":["/** Diagnostic codes raised by the server renderer. @internal */\nexport type SsrErrorCode = \"SSR_BOUNDARY_WATERFALL\" | \"SSR_PORTAL_LIMIT\" | \"SSR_TIMEOUT\";\n\n/**\n * Error thrown by the server renderer, carrying a stable code. Dev builds carry the full text;\n * production builds keep only the code (the same split as core's diagnostics).\n * @internal\n */\nexport class SsrError extends Error {\n readonly code: SsrErrorCode;\n constructor(code: SsrErrorCode, detail: string) {\n super(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n this.name = \"SsrError\";\n this.code = code;\n }\n}\n\n/**\n * A TypeError for input the renderer refuses: a value that could become unsafe markup, or a\n * malformed argument. Dev builds carry the detail; production builds keep the code.\n * @internal\n */\nexport function invalid(code: string, detail: string): TypeError {\n return new TypeError(__DEV__ ? `[shadow ${code}] ${detail}` : `SHADOW_${code}`);\n}\n\n/**\n * The longest delay `setTimeout` honors: larger values fire after one millisecond. A budget above it\n * (`Number.MAX_SAFE_INTEGER` for \"no limit\") is clamped here instead of ending every render at once.\n * @internal\n */\nexport const MAX_TIMER_MS = 2_147_483_647;\n"],"mappings":";;;;;;AAQA,IAAa,WAAb,cAA8B,MAAM;CACzB;CACT,YAAY,MAAoB,QAAgB;EAC9C,MAAgB,WAAW,KAAK,IAAI,QAA2B;EAC/D,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACF;;;;;;AAOA,SAAgB,QAAQ,MAAc,QAA2B;CAC/D,uBAAO,IAAI,UAAoB,WAAW,KAAK,IAAI,QAA2B;AAChF;;;;;;AAOA,MAAa,eAAe"}
@@ -13,5 +13,5 @@ import { createServerPortals } from "./portals.js";
13
13
  import { renderToString, renderToStringAsync } from "./render.js";
14
14
  import { deserialize, serialize } from "./serialize.js";
15
15
  import { renderToStream } from "./stream.js";
16
- import { mergeProps as mergeProps$1 } from "@shadow-js/core";
17
- export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
16
+ import { mergeProps } from "@shadow-js/core";
17
+ export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../../../src/server/node.ts"],"sourcesContent":["/**\n * Markup that is already safe to insert: the only value `escape` writes without encoding.\n * A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be\n * mistaken for trusted markup.\n * @internal\n */\nexport class SsrNode {\n readonly t: string;\n constructor(t: string) {\n this.t = t;\n }\n}\n\n/** True for values created by the server helpers. @internal */\nexport function isSsrNode(value: unknown): value is SsrNode {\n return value instanceof SsrNode;\n}\n"],"mappings":";;;;;;;AAMA,IAAa,UAAb,MAAqB;CACnB;CACA,YAAY,GAAW;EACrB,KAAK,IAAI;CACX;AACF;;AAGA,SAAgB,UAAU,OAAkC;CAC1D,OAAO,iBAAiB;AAC1B"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../../src/server/node.ts"],"sourcesContent":["/**\n * Markup that is already safe to insert: the only value `escape` writes without encoding.\n * A class instance, not a `{ t }` shape, so a plain object parsed from user input can never be\n * mistaken for trusted markup.\n * @internal\n */\nexport class SsrNode {\n readonly t: string;\n constructor(t: string) {\n this.t = t;\n }\n}\n\n/** True for values created by the server helpers. @internal */\nexport function isSsrNode(value: unknown): value is SsrNode {\n return value instanceof SsrNode;\n}\n"],"mappings":";;;;;;;AAMA,IAAa,UAAb,MAAqB;CACV;CACT,YAAY,GAAW;EACrB,KAAK,IAAI;CACX;AACF;;AAGA,SAAgB,UAAU,OAAkC;CAC1D,OAAO,iBAAiB;AAC1B"}
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":[],"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":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CACjD,0BAA2B,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IAAI,CAAC,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAA,KACzC,MAAM,IAAI,SACR,oBACA,kFACF;EAEF,KAAK,QAAQ,IAAI,KAAK,IAAI;CAC5B;;CAGA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;CAEA,OAAO,KAAyB,UAA+B;EAC7D,mBAAmB,KAAK,UAAU,IAAI;CACxC;CAEA,OAAe;EACb,IAAI,MAAM;EACV,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAC7B,OAAO,cAAc,IAAI,KAAK,KAAK,cAAc,IAAI;EAEvD,OAAO;CACT;AACF;AAEA,MAAM,6BAAa,IAAI,QAAwC;;;;;;;;;;;;;;;;;;AAmB/D,SAAgB,sBAAqC;CACnD,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,UAAyB,EAAE,YAAY,UAAU,KAAK,EAAE;CAC9D,WAAW,IAAI,SAAS,SAAS;CACjC,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,SAAyC;CACnE,MAAM,YAAY,WAAW,IAAI,OAAO;CACxC,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,UAAU,qDAAqD;CAE3E,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,mBACd,KACA,UACA,MACM;CACN,IAAI,SAAS,QAAQ,QAAQ,KAAA,GAAW;CACxC,MAAM,OAAO,UAAU,WAAW,GAAG,SAAS,OAAO,SAAS,CAAC,CAAC;CAChE,KAAK,IAAI,KAAK,IAAI;AACpB;;;;;;AAOA,SAAgB,eAAkB,MAAyB,OAAmB;CAO5E,OANa,cAAc;EACzB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CACW,CAAC,CAAa;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,SAA4D;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,YAAY,YAAY,OAAO;CACrC,UAAU,MAAM;CAChB,OAAO;AACT"}
1
+ {"version":3,"file":"portals.js","names":[],"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":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CAChC,0BAAU,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IA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"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAmC;CAG/D,OAAO,UADL,UAAU,KAAA,IAAY,KAAK,WAAW,MAAM,QAAQ,sBAAsB,EAAE,EAAE,GACrD,GAAG,KAAK;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACd,MACA,UAAyB,CAAC,GACE;CAC5B,MAAM,WAAW,QAAQ,YAAY;CACrC,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,cAAc,YAAY,EAAE,YAAY,MAAM,CAAC,OAAO,SAAS,SAAS,GACjF,MAAM,IAAI,UAAU,6DAA6D;CAEnF,MAAM,SAAS,QAAQ;CACvB,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,MAAM,UAAU,IAAI,YAAY;CAEhC,MAAM,SAAsB,CAAC;CAC7B,MAAM,mBAAyB;EAC7B,MAAM,SAAoB,CAAC;EAC3B,KAAK,MAAM,QAAQ,OAAO,OAAO,CAAC,GAChC,IAAI;GACF,KAAK,QAAQ;EACf,SAAS,OAAO;GACd,OAAO,KAAK,KAAK;EACnB;EA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OAAO,SAAS,QAAQ;MAC9B,IAAI,SAAS,MAAM;MACnB,UAAU;MACV,KACE,mBAAmB,SAAS,GAAG,IAAI,KAAK,eACtC,OAAO,MAAM,KAAK,UAAU,SAAS,EAAE,EAAE,IAAI,QAAQ,KAAK,CAC9D;KACF;KAEA,UAAU,QAAQ,SAAS,iBAAiB,CAAC,UAAU,UAAU,IAAI;KACrE,IAAI,OAAO,WAAW,SAAS,KAAK,WAAW,GAAG,cAAc;IAClE;IAEA,MAAM,OAAgC,CAAC;IACvC,KAAK,MAAM,OAAO,OAAO,WAAW;KAClC,IAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;KACvB,OAAO,eAAe,MAAM,KAAK;MAC/B,OAAO,QAAQ,IAAI,GAAG;MACtB,YAAY;MACZ,UAAU;MACV,cAAc;KAChB,CAAC;IACH;IACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,q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,OAAO,eAAe,MAAM,KAAK;MAC/B,OAAO,QAAQ,IAAI,GAAG;MACtB,YAAY;MACZ,UAAU;MACV,cAAc;KAChB,CAAC;IACH;IACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shadow-js/web",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "A DOM renderer with no virtual DOM, plus control flow, server rendering and hydration",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -109,19 +109,19 @@
109
109
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.test-types.json"
110
110
  },
111
111
  "peerDependencies": {
112
- "@shadow-js/core": "^1.1.0"
112
+ "@shadow-js/core": "^1.1.2"
113
113
  },
114
114
  "devDependencies": {
115
- "@biomejs/biome": "2.5.15",
115
+ "@biomejs/biome": "2.6.6",
116
116
  "@shadow-js/compiler": "*",
117
117
  "@shadow-js/core": "*",
118
118
  "@types/node": "^24.0.0",
119
- "esbuild": "0.27.0",
119
+ "esbuild": "0.28.2",
120
120
  "fast-check": "^4.10.2",
121
121
  "happy-dom": "21.0.4",
122
- "tsdown": "0.23.0",
122
+ "tsdown": "0.23.7",
123
123
  "typescript": "7.0.2",
124
- "vitest": "5.0.3"
124
+ "vitest": "5.1.0"
125
125
  },
126
126
  "homepage": "https://shadowjs.net/reference/web/",
127
127
  "keywords": [