@shadow-js/web 0.0.0-stage → 1.0.0

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 (611) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +190 -2
  4. package/dist/dev/attributes.d.ts +90 -0
  5. package/dist/dev/attributes.js +196 -0
  6. package/dist/dev/attributes.js.map +1 -0
  7. package/dist/dev/autofocus.d.ts +32 -0
  8. package/dist/dev/autofocus.js +45 -0
  9. package/dist/dev/autofocus.js.map +1 -0
  10. package/dist/dev/class-style.d.ts +89 -0
  11. package/dist/dev/class-style.js +197 -0
  12. package/dist/dev/class-style.js.map +1 -0
  13. package/dist/dev/component.d.ts +23 -0
  14. package/dist/dev/component.js +42 -0
  15. package/dist/dev/component.js.map +1 -0
  16. package/dist/dev/control-flow/activity.d.ts +58 -0
  17. package/dist/dev/control-flow/activity.js +136 -0
  18. package/dist/dev/control-flow/activity.js.map +1 -0
  19. package/dist/dev/control-flow/branch.js +104 -0
  20. package/dist/dev/control-flow/branch.js.map +1 -0
  21. package/dist/dev/control-flow/client-only.d.ts +48 -0
  22. package/dist/dev/control-flow/client-only.js +50 -0
  23. package/dist/dev/control-flow/client-only.js.map +1 -0
  24. package/dist/dev/control-flow/dynamic.d.ts +82 -0
  25. package/dist/dev/control-flow/dynamic.js +134 -0
  26. package/dist/dev/control-flow/dynamic.js.map +1 -0
  27. package/dist/dev/control-flow/error-boundary.d.ts +72 -0
  28. package/dist/dev/control-flow/error-boundary.js +115 -0
  29. package/dist/dev/control-flow/error-boundary.js.map +1 -0
  30. package/dist/dev/control-flow/for.d.ts +80 -0
  31. package/dist/dev/control-flow/for.js +23 -0
  32. package/dist/dev/control-flow/for.js.map +1 -0
  33. package/dist/dev/control-flow/fragment.d.ts +38 -0
  34. package/dist/dev/control-flow/fragment.js +31 -0
  35. package/dist/dev/control-flow/fragment.js.map +1 -0
  36. package/dist/dev/control-flow/hot-link.js +64 -0
  37. package/dist/dev/control-flow/hot-link.js.map +1 -0
  38. package/dist/dev/control-flow/index-list.d.ts +48 -0
  39. package/dist/dev/control-flow/index-list.js +31 -0
  40. package/dist/dev/control-flow/index-list.js.map +1 -0
  41. package/dist/dev/control-flow/index.d.ts +15 -0
  42. package/dist/dev/control-flow/lazy.d.ts +58 -0
  43. package/dist/dev/control-flow/lazy.js +64 -0
  44. package/dist/dev/control-flow/lazy.js.map +1 -0
  45. package/dist/dev/control-flow/no-hydration.d.ts +39 -0
  46. package/dist/dev/control-flow/no-hydration.js +58 -0
  47. package/dist/dev/control-flow/no-hydration.js.map +1 -0
  48. package/dist/dev/control-flow/portal.d.ts +69 -0
  49. package/dist/dev/control-flow/portal.js +134 -0
  50. package/dist/dev/control-flow/portal.js.map +1 -0
  51. package/dist/dev/control-flow/root-errors.d.ts +25 -0
  52. package/dist/dev/control-flow/root-errors.js +33 -0
  53. package/dist/dev/control-flow/root-errors.js.map +1 -0
  54. package/dist/dev/control-flow/show.d.ts +101 -0
  55. package/dist/dev/control-flow/show.js +18 -0
  56. package/dist/dev/control-flow/show.js.map +1 -0
  57. package/dist/dev/control-flow/suspense-list.d.ts +65 -0
  58. package/dist/dev/control-flow/suspense-list.js +105 -0
  59. package/dist/dev/control-flow/suspense-list.js.map +1 -0
  60. package/dist/dev/control-flow/suspense.d.ts +53 -0
  61. package/dist/dev/control-flow/suspense.js +102 -0
  62. package/dist/dev/control-flow/suspense.js.map +1 -0
  63. package/dist/dev/control-flow/switch.d.ts +85 -0
  64. package/dist/dev/control-flow/switch.js +90 -0
  65. package/dist/dev/control-flow/switch.js.map +1 -0
  66. package/dist/dev/derived.d.ts +52 -0
  67. package/dist/dev/derived.js +34 -0
  68. package/dist/dev/derived.js.map +1 -0
  69. package/dist/dev/element.d.ts +40 -0
  70. package/dist/dev/element.js +105 -0
  71. package/dist/dev/element.js.map +1 -0
  72. package/dist/dev/events.d.ts +87 -0
  73. package/dist/dev/events.js +265 -0
  74. package/dist/dev/events.js.map +1 -0
  75. package/dist/dev/extend.d.ts +12 -0
  76. package/dist/dev/extend.js +12 -0
  77. package/dist/dev/head/components.d.ts +137 -0
  78. package/dist/dev/head/components.js +170 -0
  79. package/dist/dev/head/components.js.map +1 -0
  80. package/dist/dev/head/registry.js +68 -0
  81. package/dist/dev/head/registry.js.map +1 -0
  82. package/dist/dev/head/server-head.d.ts +54 -0
  83. package/dist/dev/head/server-head.js +76 -0
  84. package/dist/dev/head/server-head.js.map +1 -0
  85. package/dist/dev/head/sink.js +96 -0
  86. package/dist/dev/head/sink.js.map +1 -0
  87. package/dist/dev/head/use-head.d.ts +35 -0
  88. package/dist/dev/head/use-head.js +84 -0
  89. package/dist/dev/head/use-head.js.map +1 -0
  90. package/dist/dev/head/validate.d.ts +85 -0
  91. package/dist/dev/head/validate.js +268 -0
  92. package/dist/dev/head/validate.js.map +1 -0
  93. package/dist/dev/hmr.d.ts +82 -0
  94. package/dist/dev/hmr.js +124 -0
  95. package/dist/dev/hmr.js.map +1 -0
  96. package/dist/dev/hydration.d.ts +61 -0
  97. package/dist/dev/hydration.js +120 -0
  98. package/dist/dev/hydration.js.map +1 -0
  99. package/dist/dev/index.d.ts +45 -0
  100. package/dist/dev/index.js +34 -0
  101. package/dist/dev/insert.d.ts +97 -0
  102. package/dist/dev/insert.js +357 -0
  103. package/dist/dev/insert.js.map +1 -0
  104. package/dist/dev/internal/claim.d.ts +106 -0
  105. package/dist/dev/internal/claim.js +357 -0
  106. package/dist/dev/internal/claim.js.map +1 -0
  107. package/dist/dev/internal/css-units.js +26 -0
  108. package/dist/dev/internal/css-units.js.map +1 -0
  109. package/dist/dev/internal/diagnostics.d.ts +30 -0
  110. package/dist/dev/internal/diagnostics.js +38 -0
  111. package/dist/dev/internal/diagnostics.js.map +1 -0
  112. package/dist/dev/internal/early-events.js +76 -0
  113. package/dist/dev/internal/early-events.js.map +1 -0
  114. package/dist/dev/internal/hydration-hooks.d.ts +43 -0
  115. package/dist/dev/internal/hydration-hooks.js +27 -0
  116. package/dist/dev/internal/hydration-hooks.js.map +1 -0
  117. package/dist/dev/internal/hydration-scope.d.ts +131 -0
  118. package/dist/dev/internal/hydration-scope.js +156 -0
  119. package/dist/dev/internal/hydration-scope.js.map +1 -0
  120. package/dist/dev/internal/names.d.ts +33 -0
  121. package/dist/dev/internal/names.js +35 -0
  122. package/dist/dev/internal/names.js.map +1 -0
  123. package/dist/dev/internal/portal-context.d.ts +39 -0
  124. package/dist/dev/internal/portal-context.js +28 -0
  125. package/dist/dev/internal/portal-context.js.map +1 -0
  126. package/dist/dev/internal/react-names.js +116 -0
  127. package/dist/dev/internal/react-names.js.map +1 -0
  128. package/dist/dev/internal/reconcile.d.ts +40 -0
  129. package/dist/dev/internal/reconcile.js +122 -0
  130. package/dist/dev/internal/reconcile.js.map +1 -0
  131. package/dist/dev/internal/stream-context.d.ts +47 -0
  132. package/dist/dev/internal/stream-context.js +23 -0
  133. package/dist/dev/internal/stream-context.js.map +1 -0
  134. package/dist/dev/jsx/aria.d.ts +72 -0
  135. package/dist/dev/jsx/component.d.ts +89 -0
  136. package/dist/dev/jsx/events.d.ts +364 -0
  137. package/dist/dev/jsx/global.d.ts +211 -0
  138. package/dist/dev/jsx/html.d.ts +879 -0
  139. package/dist/dev/jsx/intrinsic.d.ts +59 -0
  140. package/dist/dev/jsx/mathml.d.ts +186 -0
  141. package/dist/dev/jsx/svg.d.ts +607 -0
  142. package/dist/dev/jsx/types.d.ts +176 -0
  143. package/dist/dev/jsx-dev-runtime.d.ts +10 -0
  144. package/dist/dev/jsx-dev-runtime.js +0 -0
  145. package/dist/dev/jsx-runtime.d.ts +94 -0
  146. package/dist/dev/jsx-runtime.js +0 -0
  147. package/dist/dev/reactive.d.ts +110 -0
  148. package/dist/dev/reactive.js +85 -0
  149. package/dist/dev/reactive.js.map +1 -0
  150. package/dist/dev/render.d.ts +36 -0
  151. package/dist/dev/render.js +52 -0
  152. package/dist/dev/render.js.map +1 -0
  153. package/dist/dev/resource-hints.d.ts +145 -0
  154. package/dist/dev/resource-hints.js +200 -0
  155. package/dist/dev/resource-hints.js.map +1 -0
  156. package/dist/dev/select-value.d.ts +24 -0
  157. package/dist/dev/select-value.js +51 -0
  158. package/dist/dev/select-value.js.map +1 -0
  159. package/dist/dev/server/attributes.d.ts +33 -0
  160. package/dist/dev/server/attributes.js +155 -0
  161. package/dist/dev/server/attributes.js.map +1 -0
  162. package/dist/dev/server/class-style.d.ts +46 -0
  163. package/dist/dev/server/class-style.js +173 -0
  164. package/dist/dev/server/class-style.js.map +1 -0
  165. package/dist/dev/server/component.d.ts +42 -0
  166. package/dist/dev/server/component.js +72 -0
  167. package/dist/dev/server/component.js.map +1 -0
  168. package/dist/dev/server/derived.d.ts +41 -0
  169. package/dist/dev/server/derived.js +26 -0
  170. package/dist/dev/server/derived.js.map +1 -0
  171. package/dist/dev/server/element.d.ts +89 -0
  172. package/dist/dev/server/element.js +216 -0
  173. package/dist/dev/server/element.js.map +1 -0
  174. package/dist/dev/server/errors.js +26 -0
  175. package/dist/dev/server/errors.js.map +1 -0
  176. package/dist/dev/server/escape.d.ts +30 -0
  177. package/dist/dev/server/escape.js +119 -0
  178. package/dist/dev/server/escape.js.map +1 -0
  179. package/dist/dev/server/form-controls.d.ts +50 -0
  180. package/dist/dev/server/form-controls.js +193 -0
  181. package/dist/dev/server/form-controls.js.map +1 -0
  182. package/dist/dev/server/hydration-script.d.ts +65 -0
  183. package/dist/dev/server/hydration-script.js +59 -0
  184. package/dist/dev/server/hydration-script.js.map +1 -0
  185. package/dist/dev/server/index.d.ts +16 -0
  186. package/dist/dev/server/index.js +16 -0
  187. package/dist/dev/server/node.d.ts +13 -0
  188. package/dist/dev/server/node.js +21 -0
  189. package/dist/dev/server/node.js.map +1 -0
  190. package/dist/dev/server/portals.d.ts +46 -0
  191. package/dist/dev/server/portals.js +99 -0
  192. package/dist/dev/server/portals.js.map +1 -0
  193. package/dist/dev/server/render.d.ts +129 -0
  194. package/dist/dev/server/render.js +256 -0
  195. package/dist/dev/server/render.js.map +1 -0
  196. package/dist/dev/server/serialize.d.ts +45 -0
  197. package/dist/dev/server/serialize.js +315 -0
  198. package/dist/dev/server/serialize.js.map +1 -0
  199. package/dist/dev/server/stream.d.ts +94 -0
  200. package/dist/dev/server/stream.js +235 -0
  201. package/dist/dev/server/stream.js.map +1 -0
  202. package/dist/dev/server.d.ts +16 -0
  203. package/dist/dev/server.js +16 -0
  204. package/dist/dev/spread.d.ts +49 -0
  205. package/dist/dev/spread.js +296 -0
  206. package/dist/dev/spread.js.map +1 -0
  207. package/dist/dev/template.d.ts +26 -0
  208. package/dist/dev/template.js +120 -0
  209. package/dist/dev/template.js.map +1 -0
  210. package/dist/dev/view-transition.d.ts +97 -0
  211. package/dist/dev/view-transition.js +121 -0
  212. package/dist/dev/view-transition.js.map +1 -0
  213. package/dist/prod/attributes.js +2 -0
  214. package/dist/prod/attributes.js.map +1 -0
  215. package/dist/prod/autofocus.js +2 -0
  216. package/dist/prod/autofocus.js.map +1 -0
  217. package/dist/prod/class-style.js +2 -0
  218. package/dist/prod/class-style.js.map +1 -0
  219. package/dist/prod/component.js +2 -0
  220. package/dist/prod/component.js.map +1 -0
  221. package/dist/prod/control-flow/activity.js +2 -0
  222. package/dist/prod/control-flow/activity.js.map +1 -0
  223. package/dist/prod/control-flow/branch.js +2 -0
  224. package/dist/prod/control-flow/branch.js.map +1 -0
  225. package/dist/prod/control-flow/client-only.js +2 -0
  226. package/dist/prod/control-flow/client-only.js.map +1 -0
  227. package/dist/prod/control-flow/dynamic.js +2 -0
  228. package/dist/prod/control-flow/dynamic.js.map +1 -0
  229. package/dist/prod/control-flow/error-boundary.js +2 -0
  230. package/dist/prod/control-flow/error-boundary.js.map +1 -0
  231. package/dist/prod/control-flow/for.js +2 -0
  232. package/dist/prod/control-flow/for.js.map +1 -0
  233. package/dist/prod/control-flow/fragment.js +2 -0
  234. package/dist/prod/control-flow/fragment.js.map +1 -0
  235. package/dist/prod/control-flow/hot-link.js +2 -0
  236. package/dist/prod/control-flow/hot-link.js.map +1 -0
  237. package/dist/prod/control-flow/index-list.js +2 -0
  238. package/dist/prod/control-flow/index-list.js.map +1 -0
  239. package/dist/prod/control-flow/lazy.js +2 -0
  240. package/dist/prod/control-flow/lazy.js.map +1 -0
  241. package/dist/prod/control-flow/no-hydration.js +2 -0
  242. package/dist/prod/control-flow/no-hydration.js.map +1 -0
  243. package/dist/prod/control-flow/portal.js +2 -0
  244. package/dist/prod/control-flow/portal.js.map +1 -0
  245. package/dist/prod/control-flow/root-errors.js +2 -0
  246. package/dist/prod/control-flow/root-errors.js.map +1 -0
  247. package/dist/prod/control-flow/show.js +2 -0
  248. package/dist/prod/control-flow/show.js.map +1 -0
  249. package/dist/prod/control-flow/suspense-list.js +2 -0
  250. package/dist/prod/control-flow/suspense-list.js.map +1 -0
  251. package/dist/prod/control-flow/suspense.js +2 -0
  252. package/dist/prod/control-flow/suspense.js.map +1 -0
  253. package/dist/prod/control-flow/switch.js +2 -0
  254. package/dist/prod/control-flow/switch.js.map +1 -0
  255. package/dist/prod/derived.js +2 -0
  256. package/dist/prod/derived.js.map +1 -0
  257. package/dist/prod/element.js +2 -0
  258. package/dist/prod/element.js.map +1 -0
  259. package/dist/prod/events.js +2 -0
  260. package/dist/prod/events.js.map +1 -0
  261. package/dist/prod/extend.js +1 -0
  262. package/dist/prod/head/components.js +2 -0
  263. package/dist/prod/head/components.js.map +1 -0
  264. package/dist/prod/head/registry.js +2 -0
  265. package/dist/prod/head/registry.js.map +1 -0
  266. package/dist/prod/head/server-head.js +2 -0
  267. package/dist/prod/head/server-head.js.map +1 -0
  268. package/dist/prod/head/sink.js +2 -0
  269. package/dist/prod/head/sink.js.map +1 -0
  270. package/dist/prod/head/use-head.js +2 -0
  271. package/dist/prod/head/use-head.js.map +1 -0
  272. package/dist/prod/head/validate.js +2 -0
  273. package/dist/prod/head/validate.js.map +1 -0
  274. package/dist/prod/hmr.js +2 -0
  275. package/dist/prod/hmr.js.map +1 -0
  276. package/dist/prod/hydration.js +2 -0
  277. package/dist/prod/hydration.js.map +1 -0
  278. package/dist/prod/index.js +1 -0
  279. package/dist/prod/insert.js +2 -0
  280. package/dist/prod/insert.js.map +1 -0
  281. package/dist/prod/internal/claim.js +2 -0
  282. package/dist/prod/internal/claim.js.map +1 -0
  283. package/dist/prod/internal/css-units.js +2 -0
  284. package/dist/prod/internal/css-units.js.map +1 -0
  285. package/dist/prod/internal/diagnostics.js +2 -0
  286. package/dist/prod/internal/diagnostics.js.map +1 -0
  287. package/dist/prod/internal/early-events.js +2 -0
  288. package/dist/prod/internal/early-events.js.map +1 -0
  289. package/dist/prod/internal/hydration-hooks.js +2 -0
  290. package/dist/prod/internal/hydration-hooks.js.map +1 -0
  291. package/dist/prod/internal/hydration-scope.js +2 -0
  292. package/dist/prod/internal/hydration-scope.js.map +1 -0
  293. package/dist/prod/internal/names.js +2 -0
  294. package/dist/prod/internal/names.js.map +1 -0
  295. package/dist/prod/internal/portal-context.js +2 -0
  296. package/dist/prod/internal/portal-context.js.map +1 -0
  297. package/dist/prod/internal/react-names.js +2 -0
  298. package/dist/prod/internal/react-names.js.map +1 -0
  299. package/dist/prod/internal/reconcile.js +2 -0
  300. package/dist/prod/internal/reconcile.js.map +1 -0
  301. package/dist/prod/internal/stream-context.js +2 -0
  302. package/dist/prod/internal/stream-context.js.map +1 -0
  303. package/dist/prod/jsx-dev-runtime.js +0 -0
  304. package/dist/prod/jsx-runtime.js +0 -0
  305. package/dist/prod/reactive.js +2 -0
  306. package/dist/prod/reactive.js.map +1 -0
  307. package/dist/prod/render.js +2 -0
  308. package/dist/prod/render.js.map +1 -0
  309. package/dist/prod/resource-hints.js +2 -0
  310. package/dist/prod/resource-hints.js.map +1 -0
  311. package/dist/prod/select-value.js +2 -0
  312. package/dist/prod/select-value.js.map +1 -0
  313. package/dist/prod/server/attributes.js +2 -0
  314. package/dist/prod/server/attributes.js.map +1 -0
  315. package/dist/prod/server/class-style.js +2 -0
  316. package/dist/prod/server/class-style.js.map +1 -0
  317. package/dist/prod/server/component.js +2 -0
  318. package/dist/prod/server/component.js.map +1 -0
  319. package/dist/prod/server/derived.js +2 -0
  320. package/dist/prod/server/derived.js.map +1 -0
  321. package/dist/prod/server/element.js +2 -0
  322. package/dist/prod/server/element.js.map +1 -0
  323. package/dist/prod/server/errors.js +2 -0
  324. package/dist/prod/server/errors.js.map +1 -0
  325. package/dist/prod/server/escape.js +2 -0
  326. package/dist/prod/server/escape.js.map +1 -0
  327. package/dist/prod/server/form-controls.js +3 -0
  328. package/dist/prod/server/form-controls.js.map +1 -0
  329. package/dist/prod/server/hydration-script.js +2 -0
  330. package/dist/prod/server/hydration-script.js.map +1 -0
  331. package/dist/prod/server/index.js +1 -0
  332. package/dist/prod/server/node.js +2 -0
  333. package/dist/prod/server/node.js.map +1 -0
  334. package/dist/prod/server/portals.js +2 -0
  335. package/dist/prod/server/portals.js.map +1 -0
  336. package/dist/prod/server/render.js +2 -0
  337. package/dist/prod/server/render.js.map +1 -0
  338. package/dist/prod/server/serialize.js +2 -0
  339. package/dist/prod/server/serialize.js.map +1 -0
  340. package/dist/prod/server/stream.js +2 -0
  341. package/dist/prod/server/stream.js.map +1 -0
  342. package/dist/prod/server.js +1 -0
  343. package/dist/prod/spread.js +2 -0
  344. package/dist/prod/spread.js.map +1 -0
  345. package/dist/prod/template.js +2 -0
  346. package/dist/prod/template.js.map +1 -0
  347. package/dist/prod/view-transition.js +2 -0
  348. package/dist/prod/view-transition.js.map +1 -0
  349. package/dist/server/attributes.js +2 -0
  350. package/dist/server/attributes.js.map +1 -0
  351. package/dist/server/autofocus.js +2 -0
  352. package/dist/server/autofocus.js.map +1 -0
  353. package/dist/server/class-style.js +2 -0
  354. package/dist/server/class-style.js.map +1 -0
  355. package/dist/server/component.js +2 -0
  356. package/dist/server/component.js.map +1 -0
  357. package/dist/server/control-flow/activity.js +2 -0
  358. package/dist/server/control-flow/activity.js.map +1 -0
  359. package/dist/server/control-flow/branch.js +2 -0
  360. package/dist/server/control-flow/branch.js.map +1 -0
  361. package/dist/server/control-flow/client-only.js +2 -0
  362. package/dist/server/control-flow/client-only.js.map +1 -0
  363. package/dist/server/control-flow/dynamic.js +2 -0
  364. package/dist/server/control-flow/dynamic.js.map +1 -0
  365. package/dist/server/control-flow/error-boundary.js +2 -0
  366. package/dist/server/control-flow/error-boundary.js.map +1 -0
  367. package/dist/server/control-flow/for.js +2 -0
  368. package/dist/server/control-flow/for.js.map +1 -0
  369. package/dist/server/control-flow/fragment.js +2 -0
  370. package/dist/server/control-flow/fragment.js.map +1 -0
  371. package/dist/server/control-flow/index-list.js +2 -0
  372. package/dist/server/control-flow/index-list.js.map +1 -0
  373. package/dist/server/control-flow/lazy.js +2 -0
  374. package/dist/server/control-flow/lazy.js.map +1 -0
  375. package/dist/server/control-flow/no-hydration.js +2 -0
  376. package/dist/server/control-flow/no-hydration.js.map +1 -0
  377. package/dist/server/control-flow/portal.js +2 -0
  378. package/dist/server/control-flow/portal.js.map +1 -0
  379. package/dist/server/control-flow/root-errors.js +2 -0
  380. package/dist/server/control-flow/root-errors.js.map +1 -0
  381. package/dist/server/control-flow/show.js +2 -0
  382. package/dist/server/control-flow/show.js.map +1 -0
  383. package/dist/server/control-flow/suspense-list.js +2 -0
  384. package/dist/server/control-flow/suspense-list.js.map +1 -0
  385. package/dist/server/control-flow/suspense.js +2 -0
  386. package/dist/server/control-flow/suspense.js.map +1 -0
  387. package/dist/server/control-flow/switch.js +2 -0
  388. package/dist/server/control-flow/switch.js.map +1 -0
  389. package/dist/server/derived.js +2 -0
  390. package/dist/server/derived.js.map +1 -0
  391. package/dist/server/element.js +2 -0
  392. package/dist/server/element.js.map +1 -0
  393. package/dist/server/events.js +2 -0
  394. package/dist/server/events.js.map +1 -0
  395. package/dist/server/extend.js +1 -0
  396. package/dist/server/head/components.js +2 -0
  397. package/dist/server/head/components.js.map +1 -0
  398. package/dist/server/head/registry.js +2 -0
  399. package/dist/server/head/registry.js.map +1 -0
  400. package/dist/server/head/server-head.js +2 -0
  401. package/dist/server/head/server-head.js.map +1 -0
  402. package/dist/server/head/sink.js +2 -0
  403. package/dist/server/head/sink.js.map +1 -0
  404. package/dist/server/head/use-head.js +2 -0
  405. package/dist/server/head/use-head.js.map +1 -0
  406. package/dist/server/head/validate.js +2 -0
  407. package/dist/server/head/validate.js.map +1 -0
  408. package/dist/server/hydration.js +2 -0
  409. package/dist/server/hydration.js.map +1 -0
  410. package/dist/server/index.js +1 -0
  411. package/dist/server/insert.js +2 -0
  412. package/dist/server/insert.js.map +1 -0
  413. package/dist/server/internal/claim.js +2 -0
  414. package/dist/server/internal/claim.js.map +1 -0
  415. package/dist/server/internal/css-units.js +2 -0
  416. package/dist/server/internal/css-units.js.map +1 -0
  417. package/dist/server/internal/diagnostics.js +2 -0
  418. package/dist/server/internal/diagnostics.js.map +1 -0
  419. package/dist/server/internal/early-events.js +2 -0
  420. package/dist/server/internal/early-events.js.map +1 -0
  421. package/dist/server/internal/hydration-hooks.js +2 -0
  422. package/dist/server/internal/hydration-hooks.js.map +1 -0
  423. package/dist/server/internal/hydration-scope.js +2 -0
  424. package/dist/server/internal/hydration-scope.js.map +1 -0
  425. package/dist/server/internal/names.js +2 -0
  426. package/dist/server/internal/names.js.map +1 -0
  427. package/dist/server/internal/portal-context.js +2 -0
  428. package/dist/server/internal/portal-context.js.map +1 -0
  429. package/dist/server/internal/react-names.js +2 -0
  430. package/dist/server/internal/react-names.js.map +1 -0
  431. package/dist/server/internal/reconcile.js +2 -0
  432. package/dist/server/internal/reconcile.js.map +1 -0
  433. package/dist/server/internal/stream-context.js +2 -0
  434. package/dist/server/internal/stream-context.js.map +1 -0
  435. package/dist/server/reactive.js +2 -0
  436. package/dist/server/reactive.js.map +1 -0
  437. package/dist/server/render.js +2 -0
  438. package/dist/server/render.js.map +1 -0
  439. package/dist/server/resource-hints.js +2 -0
  440. package/dist/server/resource-hints.js.map +1 -0
  441. package/dist/server/select-value.js +2 -0
  442. package/dist/server/select-value.js.map +1 -0
  443. package/dist/server/server/attributes.js +2 -0
  444. package/dist/server/server/attributes.js.map +1 -0
  445. package/dist/server/server/class-style.js +2 -0
  446. package/dist/server/server/class-style.js.map +1 -0
  447. package/dist/server/server/component.js +2 -0
  448. package/dist/server/server/component.js.map +1 -0
  449. package/dist/server/server/derived.js +2 -0
  450. package/dist/server/server/derived.js.map +1 -0
  451. package/dist/server/server/element.js +2 -0
  452. package/dist/server/server/element.js.map +1 -0
  453. package/dist/server/server/errors.js +2 -0
  454. package/dist/server/server/errors.js.map +1 -0
  455. package/dist/server/server/escape.js +2 -0
  456. package/dist/server/server/escape.js.map +1 -0
  457. package/dist/server/server/form-controls.js +3 -0
  458. package/dist/server/server/form-controls.js.map +1 -0
  459. package/dist/server/server/hydration-script.js +2 -0
  460. package/dist/server/server/hydration-script.js.map +1 -0
  461. package/dist/server/server/index.js +1 -0
  462. package/dist/server/server/node.js +2 -0
  463. package/dist/server/server/node.js.map +1 -0
  464. package/dist/server/server/portals.js +2 -0
  465. package/dist/server/server/portals.js.map +1 -0
  466. package/dist/server/server/render.js +2 -0
  467. package/dist/server/server/render.js.map +1 -0
  468. package/dist/server/server/serialize.js +2 -0
  469. package/dist/server/server/serialize.js.map +1 -0
  470. package/dist/server/server/stream.js +2 -0
  471. package/dist/server/server/stream.js.map +1 -0
  472. package/dist/server/server.js +1 -0
  473. package/dist/server/spread.js +2 -0
  474. package/dist/server/spread.js.map +1 -0
  475. package/dist/server/template.js +2 -0
  476. package/dist/server/template.js.map +1 -0
  477. package/dist/server/view-transition.js +2 -0
  478. package/dist/server/view-transition.js.map +1 -0
  479. package/dist/server-dev/attributes.js +196 -0
  480. package/dist/server-dev/attributes.js.map +1 -0
  481. package/dist/server-dev/autofocus.js +45 -0
  482. package/dist/server-dev/autofocus.js.map +1 -0
  483. package/dist/server-dev/class-style.js +197 -0
  484. package/dist/server-dev/class-style.js.map +1 -0
  485. package/dist/server-dev/component.js +42 -0
  486. package/dist/server-dev/component.js.map +1 -0
  487. package/dist/server-dev/control-flow/activity.js +41 -0
  488. package/dist/server-dev/control-flow/activity.js.map +1 -0
  489. package/dist/server-dev/control-flow/branch.js +104 -0
  490. package/dist/server-dev/control-flow/branch.js.map +1 -0
  491. package/dist/server-dev/control-flow/client-only.js +50 -0
  492. package/dist/server-dev/control-flow/client-only.js.map +1 -0
  493. package/dist/server-dev/control-flow/dynamic.js +106 -0
  494. package/dist/server-dev/control-flow/dynamic.js.map +1 -0
  495. package/dist/server-dev/control-flow/error-boundary.js +115 -0
  496. package/dist/server-dev/control-flow/error-boundary.js.map +1 -0
  497. package/dist/server-dev/control-flow/for.js +23 -0
  498. package/dist/server-dev/control-flow/for.js.map +1 -0
  499. package/dist/server-dev/control-flow/fragment.js +31 -0
  500. package/dist/server-dev/control-flow/fragment.js.map +1 -0
  501. package/dist/server-dev/control-flow/hot-link.js +57 -0
  502. package/dist/server-dev/control-flow/hot-link.js.map +1 -0
  503. package/dist/server-dev/control-flow/index-list.js +31 -0
  504. package/dist/server-dev/control-flow/index-list.js.map +1 -0
  505. package/dist/server-dev/control-flow/lazy.js +64 -0
  506. package/dist/server-dev/control-flow/lazy.js.map +1 -0
  507. package/dist/server-dev/control-flow/no-hydration.js +40 -0
  508. package/dist/server-dev/control-flow/no-hydration.js.map +1 -0
  509. package/dist/server-dev/control-flow/portal.js +134 -0
  510. package/dist/server-dev/control-flow/portal.js.map +1 -0
  511. package/dist/server-dev/control-flow/root-errors.js +33 -0
  512. package/dist/server-dev/control-flow/root-errors.js.map +1 -0
  513. package/dist/server-dev/control-flow/show.js +18 -0
  514. package/dist/server-dev/control-flow/show.js.map +1 -0
  515. package/dist/server-dev/control-flow/suspense-list.js +100 -0
  516. package/dist/server-dev/control-flow/suspense-list.js.map +1 -0
  517. package/dist/server-dev/control-flow/suspense.js +119 -0
  518. package/dist/server-dev/control-flow/suspense.js.map +1 -0
  519. package/dist/server-dev/control-flow/switch.js +90 -0
  520. package/dist/server-dev/control-flow/switch.js.map +1 -0
  521. package/dist/server-dev/derived.js +34 -0
  522. package/dist/server-dev/derived.js.map +1 -0
  523. package/dist/server-dev/element.js +66 -0
  524. package/dist/server-dev/element.js.map +1 -0
  525. package/dist/server-dev/events.js +265 -0
  526. package/dist/server-dev/events.js.map +1 -0
  527. package/dist/server-dev/extend.js +12 -0
  528. package/dist/server-dev/head/components.js +170 -0
  529. package/dist/server-dev/head/components.js.map +1 -0
  530. package/dist/server-dev/head/registry.js +68 -0
  531. package/dist/server-dev/head/registry.js.map +1 -0
  532. package/dist/server-dev/head/server-head.js +76 -0
  533. package/dist/server-dev/head/server-head.js.map +1 -0
  534. package/dist/server-dev/head/sink.js +96 -0
  535. package/dist/server-dev/head/sink.js.map +1 -0
  536. package/dist/server-dev/head/use-head.js +84 -0
  537. package/dist/server-dev/head/use-head.js.map +1 -0
  538. package/dist/server-dev/head/validate.js +268 -0
  539. package/dist/server-dev/head/validate.js.map +1 -0
  540. package/dist/server-dev/hydration.js +120 -0
  541. package/dist/server-dev/hydration.js.map +1 -0
  542. package/dist/server-dev/index.js +34 -0
  543. package/dist/server-dev/insert.js +357 -0
  544. package/dist/server-dev/insert.js.map +1 -0
  545. package/dist/server-dev/internal/claim.js +357 -0
  546. package/dist/server-dev/internal/claim.js.map +1 -0
  547. package/dist/server-dev/internal/css-units.js +26 -0
  548. package/dist/server-dev/internal/css-units.js.map +1 -0
  549. package/dist/server-dev/internal/diagnostics.js +38 -0
  550. package/dist/server-dev/internal/diagnostics.js.map +1 -0
  551. package/dist/server-dev/internal/early-events.js +76 -0
  552. package/dist/server-dev/internal/early-events.js.map +1 -0
  553. package/dist/server-dev/internal/hydration-hooks.js +27 -0
  554. package/dist/server-dev/internal/hydration-hooks.js.map +1 -0
  555. package/dist/server-dev/internal/hydration-scope.js +156 -0
  556. package/dist/server-dev/internal/hydration-scope.js.map +1 -0
  557. package/dist/server-dev/internal/names.js +35 -0
  558. package/dist/server-dev/internal/names.js.map +1 -0
  559. package/dist/server-dev/internal/portal-context.js +28 -0
  560. package/dist/server-dev/internal/portal-context.js.map +1 -0
  561. package/dist/server-dev/internal/react-names.js +116 -0
  562. package/dist/server-dev/internal/react-names.js.map +1 -0
  563. package/dist/server-dev/internal/reconcile.js +122 -0
  564. package/dist/server-dev/internal/reconcile.js.map +1 -0
  565. package/dist/server-dev/internal/stream-context.js +23 -0
  566. package/dist/server-dev/internal/stream-context.js.map +1 -0
  567. package/dist/server-dev/reactive.js +85 -0
  568. package/dist/server-dev/reactive.js.map +1 -0
  569. package/dist/server-dev/render.js +52 -0
  570. package/dist/server-dev/render.js.map +1 -0
  571. package/dist/server-dev/resource-hints.js +200 -0
  572. package/dist/server-dev/resource-hints.js.map +1 -0
  573. package/dist/server-dev/select-value.js +51 -0
  574. package/dist/server-dev/select-value.js.map +1 -0
  575. package/dist/server-dev/server/attributes.js +155 -0
  576. package/dist/server-dev/server/attributes.js.map +1 -0
  577. package/dist/server-dev/server/class-style.js +173 -0
  578. package/dist/server-dev/server/class-style.js.map +1 -0
  579. package/dist/server-dev/server/component.js +72 -0
  580. package/dist/server-dev/server/component.js.map +1 -0
  581. package/dist/server-dev/server/derived.js +26 -0
  582. package/dist/server-dev/server/derived.js.map +1 -0
  583. package/dist/server-dev/server/element.js +216 -0
  584. package/dist/server-dev/server/element.js.map +1 -0
  585. package/dist/server-dev/server/errors.js +26 -0
  586. package/dist/server-dev/server/errors.js.map +1 -0
  587. package/dist/server-dev/server/escape.js +119 -0
  588. package/dist/server-dev/server/escape.js.map +1 -0
  589. package/dist/server-dev/server/form-controls.js +193 -0
  590. package/dist/server-dev/server/form-controls.js.map +1 -0
  591. package/dist/server-dev/server/hydration-script.js +59 -0
  592. package/dist/server-dev/server/hydration-script.js.map +1 -0
  593. package/dist/server-dev/server/index.js +16 -0
  594. package/dist/server-dev/server/node.js +21 -0
  595. package/dist/server-dev/server/node.js.map +1 -0
  596. package/dist/server-dev/server/portals.js +99 -0
  597. package/dist/server-dev/server/portals.js.map +1 -0
  598. package/dist/server-dev/server/render.js +256 -0
  599. package/dist/server-dev/server/render.js.map +1 -0
  600. package/dist/server-dev/server/serialize.js +315 -0
  601. package/dist/server-dev/server/serialize.js.map +1 -0
  602. package/dist/server-dev/server/stream.js +235 -0
  603. package/dist/server-dev/server/stream.js.map +1 -0
  604. package/dist/server-dev/server.js +16 -0
  605. package/dist/server-dev/spread.js +296 -0
  606. package/dist/server-dev/spread.js.map +1 -0
  607. package/dist/server-dev/template.js +120 -0
  608. package/dist/server-dev/template.js.map +1 -0
  609. package/dist/server-dev/view-transition.js +90 -0
  610. package/dist/server-dev/view-transition.js.map +1 -0
  611. package/package.json +136 -4
@@ -0,0 +1,2 @@
1
+ import{createBranches as e}from"./branch.js";import{children as t}from"@shadow-js/core";function n(e){return e}function r(e){return typeof e==`object`&&!!e&&`when`in e}function i(e){let t=[];for(let n of e.toArray()){if(!r(n))throw TypeError(`SHADOW_SWITCH_CHILDREN`);t.push(n)}return t}function a(n){let r=t(()=>n.children);return i(r),e(`Switch`,()=>{let e=i(r);for(let[t,n]of e.entries()){let e=n.when;if(e)return{index:t,keyed:n.keyed===!0,when:e,read:()=>n.when,body:()=>n.children}}return{index:-1,keyed:!1,when:void 0,read:()=>void 0,body:()=>void 0}},()=>n.fallback)}export{n as Match,a as Switch};
2
+ //# sourceMappingURL=switch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"switch.js","names":["resolveChildren","Match","props","isMatch","item","matchesOf","matches","resolved","Switch","children","createBranches","list","index","match","when"],"sources":["../../../src/control-flow/switch.ts"],"sourcesContent":["import { type Accessor, type ResolvedChildren, children as resolveChildren } from \"@shadow-js/core\";\nimport { createBranches, FALLBACK } from \"./branch\";\n\n/**\n * Props of {@link Match}. A Match descriptor is the props object itself.\n * @since 1.0.0\n */\nexport interface MatchProps<T> {\n /** The condition. The first Match whose `when` is truthy is shown. */\n readonly when: T | undefined | null | false | 0 | \"\";\n /**\n * Same meaning as in {@link ShowLooseProps}: `true` rebuilds the branch when the identity of\n * `when` changes.\n * @default false\n */\n readonly keyed?: boolean;\n /**\n * The branch content: plain content, an accessor, or a callback, as the children of\n * {@link ShowProps}.\n * @default undefined (the selected Match renders nothing)\n */\n readonly children?: unknown;\n}\n\n/**\n * Describes one branch of a {@link Switch}. It returns its props unchanged.\n *\n * @param props The condition and the branch content.\n * @returns The same props object, which `Switch` reads.\n * @example\n * import { Match } from \"@shadow-js/web\";\n *\n * const branch = Match({ when: \"ready\", children: \"Loaded\" });\n * console.log(branch.when); // \"ready\"\n * @see Switch\n * @since 1.0.0\n */\nexport function Match<T>(props: MatchProps<T>): MatchProps<T> {\n return props;\n}\n\n/**\n * Props of {@link Switch}.\n * @since 1.0.0\n */\nexport interface SwitchProps {\n /**\n * Shown when no Match is truthy. Read lazily.\n * @default undefined (nothing is rendered when no Match is truthy)\n */\n readonly fallback?: unknown;\n /**\n * One or more {@link Match} descriptors. `null`, `undefined` and booleans are ignored.\n * @default undefined (no branches; the fallback is shown)\n */\n readonly children?: unknown;\n}\n\n/** A Match descriptor is any object with a `when` key. Anything else is not a Match. */\nfunction isMatch(item: unknown): item is MatchProps<unknown> {\n return typeof item === \"object\" && item !== null && \"when\" in item;\n}\n\n/** Resolves the children into Match descriptors. Throws for any other kind of child. */\nfunction matchesOf(resolved: ResolvedChildren): MatchProps<unknown>[] {\n const matches: MatchProps<unknown>[] = [];\n for (const item of resolved.toArray()) {\n if (!isMatch(item))\n throw new TypeError(\n __DEV__ ? \"ShadowJS Switch: children must be <Match>\" : \"SHADOW_SWITCH_CHILDREN\",\n );\n matches.push(item);\n }\n return matches;\n}\n\n/**\n * Shows the first {@link Match} whose `when` is truthy, or the fallback when none is.\n * Re-selecting the same branch with the same truthiness (or, when keyed, the same value) does not\n * rebuild it.\n *\n * @param props See {@link SwitchProps}.\n * @returns An accessor of the selected branch's content.\n * @throws TypeError (production message `SHADOW_SWITCH_CHILDREN`) when a child is neither a Match\n * nor `null`, `undefined` or a boolean.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { Match, Switch } from \"@shadow-js/web\";\n *\n * function Status() {\n * const [error] = useSignal<string | null>(null);\n * const [data] = useSignal<string | null>(\"ready\");\n * return (\n * <Switch fallback={<p>Loading...</p>}>\n * <Match when={error()}>\n * <p>Failed</p>\n * </Match>\n * <Match when={data()}>\n * <p>Ready</p>\n * </Match>\n * </Switch>\n * );\n * }\n * @see Show\n * @since 1.0.0\n */\nexport function Switch(props: SwitchProps): Accessor<unknown> {\n const matches = resolveChildren(() => props.children);\n // Validate now, so that a wrong child is reported where the Switch is written.\n matchesOf(matches);\n return createBranches(\n \"Switch\",\n () => {\n const list = matchesOf(matches);\n for (const [index, match] of list.entries()) {\n const when = match.when;\n if (when) {\n return {\n index,\n keyed: match.keyed === true,\n when,\n read: () => match.when,\n body: () => match.children,\n };\n }\n }\n return {\n index: FALLBACK,\n keyed: false,\n when: undefined,\n read: () => undefined,\n body: () => undefined,\n };\n },\n () => props.fallback,\n );\n}\n"],"mappings":"A,wFAqCA,SAAgBC,EAAS,EAAqC,CAC5D,OAAOC,CACT,CAoBA,SAASC,EAAQ,EAA4C,CAC3D,OAAO,OAAOC,GAAS,YAAYA,GAAiB,SAAUA,CAChE,CAGA,SAASC,EAAU,EAAmD,CACpE,IAAMC,EAAiC,CAAC,EACxC,IAAK,IAAMF,KAAQG,EAAS,QAAQ,EAAG,CACrC,GAAI,CAACJ,EAAQC,CAAI,EACf,MAAU,UACgD,wBAC1D,EACFE,EAAQ,KAAKF,CAAI,CACnB,CACA,OAAOE,CACT,CAgCA,SAAgBE,EAAO,EAAuC,CAC5D,IAAMF,EAAUN,MAAsBE,EAAM,QAAQ,EAGpD,OADAG,EAAUC,CAAO,EACVI,EACL,aACM,CACJ,IAAMC,EAAON,EAAUC,CAAO,EAC9B,IAAK,GAAM,CAACM,EAAOC,KAAUF,EAAK,QAAQ,EAAG,CAC3C,IAAMG,EAAOD,EAAM,KACnB,GAAIC,EACF,MAAO,CACL,QACA,MAAOD,EAAM,QAAU,GACvB,OACA,SAAYA,EAAM,KAClB,SAAYA,EAAM,QACpB,CAEJ,CACA,MAAO,CACL,MAAA,GACA,MAAO,GACP,KAAM,IAAA,GACN,SAAY,IAAA,GACZ,SAAY,IAAA,EACd,CACF,MACMX,EAAM,QACd,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import{useMemo as e}from"@shadow-js/core";function t(t){let n=e(t),r=((...e)=>{let t=n();return typeof t==`function`?t(...e):t});return Object.defineProperty(r,"value",{get:n}),r}export{t as derived};
2
+ //# sourceMappingURL=derived.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"derived.js","names":["derived","memo","useMemo","compute","read","args","current"],"sources":["../../src/derived.ts"],"sourcesContent":["import { useMemo } from \"@shadow-js/core\";\n\n/**\n * A value the compiler keeps live: the result of `const x = <expression reading signals>` inside a\n * component. Read it as `x.value` or call it as `x()`, so `{double}` and `{double()}` both work in\n * JSX. When the value is itself a function, calling the derived calls that function with the\n * arguments, so a derived function stays callable.\n *\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [count, setCount] = useSignal(2);\n * const double = derived(() => count() * 2);\n * console.log(double.value); // 4\n * setCount(5);\n * console.log(double()); // 10\n * }\n * @see derived\n * @since 1.0.0\n */\nexport interface Derived<T> {\n /**\n * Returns the current value, tracked. When the value is a function, calls it with `args` and\n * returns its result instead.\n */\n (...args: unknown[]): unknown;\n /** The current value, tracked: reading it inside an effect or binding subscribes that reader. */\n readonly value: T;\n}\n\n/**\n * Wraps a computation as a {@link Derived} value that recomputes only when the signals it reads\n * change. The compiler emits it for `const x = <expression reading signals>` inside components; it\n * is not meant to be written by hand.\n *\n * @param compute The computation. Runs in a memo, so it is tracked and cached between reads.\n * @returns A {@link Derived} whose `value` (and call result) follows `compute`.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { derived } from \"@shadow-js/web\";\n *\n * function setup() {\n * const [price] = useSignal(20);\n * const total = derived(() => price() * 3);\n * console.log(total.value); // 60\n * }\n * @see Derived\n * @since 1.0.0\n */\nexport function derived<T>(compute: () => T): Derived<T> {\n const memo = useMemo(compute);\n const read = ((...args: unknown[]): unknown => {\n const current = memo();\n return typeof current === \"function\"\n ? (current as (...a: unknown[]) => unknown)(...args)\n : current;\n }) as { (...args: unknown[]): unknown; value: T };\n Object.defineProperty(read, \"value\", { get: memo });\n return read as Derived<T>;\n}\n"],"mappings":"A,0CAmDA,SAAgBA,EAAW,EAA8B,CACvD,IAAMC,EAAOC,EAAQC,CAAO,EACtBC,IAAS,GAAGC,IAA6B,CAC7C,IAAMC,EAAUL,EAAK,EACrB,OAAO,OAAOK,GAAY,WACrBA,EAAyC,GAAGD,CAAI,EACjDC,CACN,GAEA,OADA,OAAO,eAAeF,EAAM,QAAS,CAAE,IAAKH,CAAK,CAAC,EAC3CG,CACT,C"}
@@ -0,0 +1,2 @@
1
+ import{ssrElement as e,ssrRaw as t}from"./server/element.js";import"@shadow-js/core";const n=/^[a-z][a-z0-9-]*$/i;function r(r,i){if(!n.test(r)||r.toLowerCase()===`script`)throw TypeError(`SHADOW_ELEMENT_TAG`);let a=i;return e(r,i,()=>{let e=a.children;return e===void 0?void 0:[t(`<!--[-->`),e,t(`<!--]-->`)]},!0)}export{r as element};
2
+ //# sourceMappingURL=element.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"element.js","names":["TAG_PATTERN","element","tag","read","props","ssrElement","children","\"children\"","ssrRaw"],"sources":["../../src/element.ts"],"sourcesContent":["import { batch, untrack, useRenderEffect } from \"@shadow-js/core\";\nimport { setAttribute } from \"./attributes\";\nimport { style } from \"./class-style\";\nimport { insert } from \"./insert\";\nimport { checkClaimedTag } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { nextKey } from \"./internal/hydration-scope\";\nimport { ssrElement, ssrRaw } from \"./server/element\";\n\n/**\n * The slim element primitive: one HTML element with attributes, event listeners, `ref` and children,\n * and no generic prop runtime. `Dynamic` and `spread` cover every prop shape; this covers the common\n * ones, so a library that renders one fixed element (a link, a button) pays for what it binds.\n *\n * It keeps the renderer's contracts: the hydration key is drawn when the element is created, so it\n * claims the server's element and adopts its children; on the server it writes the same markup `Dynamic`\n * writes for the tag.\n */\n\n/** Tag shape that `Dynamic` accepts. `script` is refused for the same reason. */\nconst TAG_PATTERN = /^[a-z][a-z0-9-]*$/i;\n\n/** `onClick` to `click`, when the key is an event handler name. */\nfunction eventNameOf(key: string): string | undefined {\n return key.length > 2 && key.startsWith(\"on\") && /^[A-Z]/.test(key.charAt(2))\n ? key.slice(2).toLowerCase()\n : undefined;\n}\n\n/**\n * Binds one listener, read once. A function runs with the element as `this`; a `[fn, data]` tuple\n * receives `data` first. `null`, `undefined` and `false` bind nothing. Handlers run in a batch and\n * untracked, as the event binding of `Dynamic` runs them.\n */\nfunction bindListener(el: Element, name: string, handler: unknown): void {\n let call: ((event: Event) => unknown) | undefined;\n if (typeof handler === \"function\") {\n call = (event: Event): unknown => handler.call(el, event);\n } else if (Array.isArray(handler)) {\n const [fn, data] = handler as [unknown, unknown];\n if (typeof fn === \"function\") call = (event: Event): unknown => fn.call(el, data, event);\n }\n if (call === undefined) return;\n const run = call;\n el.addEventListener(name, (event: Event): void => {\n batch(() => untrack(() => run(event)));\n });\n}\n\n/**\n * Creates one HTML element from a tag name and a props object, without the generic prop runtime of\n * `spread` and `Dynamic`: for a library that renders one fixed element (a link, a button) and wants\n * to pay only for what it binds. It draws a hydration key, so during `hydrate()` it adopts the\n * server's element and its children; on the server it returns the markup `Dynamic` writes for the tag.\n *\n * Each prop other than `children`, `ref` and `onX` is read in a render effect, so a getter prop\n * updates the element in place. `class` and the other attributes follow {@link setAttribute} (URL\n * attributes that would run script are refused); `style` follows {@link style}. Use `Dynamic` when the\n * tag is not known in advance, or for SVG, `classList`, delegated events or React prop names.\n *\n * @param tag An HTML tag name matching `[a-z][a-z0-9-]*` (any case), such as `\"a\"`. `script` is\n * refused.\n * @param props The element's props. `onX` keys whose third letter is uppercase are native listeners,\n * read once: the rest of the key lowercased is the event (`onClick` is `click`), and the value is a\n * function (called with the element as `this`) or a `[fn, data]` tuple (called as `fn(data, event)`);\n * handlers run batched and untracked. `ref` is called once with the element. `children` is inserted\n * (a getter keeps it reactive). `class` takes a string; `style` a string or an object.\n * @returns The element on the client; its server markup when rendering on the server.\n * @throws TypeError `SHADOW_ELEMENT_TAG` when `tag` is not an allowed tag name.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { element } from \"@shadow-js/web\";\n *\n * function HomeLink() {\n * const [active] = useSignal(true);\n * return element(\"a\", {\n * href: \"/\",\n * get \"aria-current\"() { return active() ? \"page\" : undefined; },\n * onClick: (event: MouseEvent) => console.log(event.type),\n * children: \"Home\",\n * });\n * }\n * @see spread\n * @since 1.0.0\n */\nexport function element(tag: string, props: object): unknown {\n if (!TAG_PATTERN.test(tag) || tag.toLowerCase() === \"script\") {\n throw new TypeError(__DEV__ ? \"ShadowJS element: invalid tag\" : \"SHADOW_ELEMENT_TAG\");\n }\n const read = props as Readonly<Record<string, unknown>>;\n if (__SERVER__) {\n // The children are read after the hydration key is drawn, in the order the client claims them.\n return ssrElement(\n tag,\n props,\n () => {\n const children = read[\"children\"];\n return children === undefined\n ? undefined\n : [ssrRaw(\"<!--[-->\"), children, ssrRaw(\"<!--]-->\")];\n },\n true,\n );\n }\n const claimed = claims.current.claimElement(nextKey());\n if (claimed !== null && __DEV__) checkClaimedTag(claimed, tag);\n const el = claimed ?? document.createElement(tag);\n for (const key of Object.keys(props)) {\n if (key === \"children\" || key === \"ref\") continue;\n const event = eventNameOf(key);\n if (event !== undefined) {\n bindListener(el, event, read[key]);\n } else if (key === \"style\") {\n // The last value written, so a property that leaves the style object is removed (as spread does).\n let applied: unknown;\n useRenderEffect(\n () => read[key],\n (value) => {\n applied = style(el as HTMLElement, value, applied);\n },\n );\n } else {\n useRenderEffect(\n () => read[key],\n (value) => {\n setAttribute(el, key, value);\n },\n );\n }\n }\n const ref = read[\"ref\"];\n if (typeof ref === \"function\") ref(el);\n insert(el, () => read[\"children\"]);\n return el;\n}\n"],"mappings":"A,qFAoBA,MAAMA,EAAc,qBAiEpB,SAAgBC,EAAQ,EAAa,EAAwB,CAC3D,GAAI,CAACD,EAAY,KAAKE,CAAG,GAAKA,EAAI,YAAY,IAAM,SAClD,MAAU,UAAsD,oBAAoB,EAEtF,IAAMC,EAAOC,EAGX,OAAOC,EACLH,EACAE,MACM,CACJ,IAAME,EAAWH,EAAKI,SACtB,OAAOD,IAAa,IAAA,GAChB,IAAA,GACA,CAACE,EAAO,UAAU,EAAGF,EAAUE,EAAO,UAAU,CAAC,CACvD,EACA,EACF,CAgCJ,C"}
@@ -0,0 +1,2 @@
1
+ import{batch as e,getOwner as t,onCleanup as n,untrack as r}from"@shadow-js/core";const i=/* @__PURE__ */ new Set([`click`,`dblclick`,`input`,`keydown`,`keyup`,`keypress`,`pointerdown`,`pointerup`,`pointermove`,`mousedown`,`mouseup`,`mousemove`,`focusin`,`focusout`,`beforeinput`,`touchstart`,`touchend`,`touchmove`,`contextmenu`,`mouseover`,`mouseout`,`pointerover`,`pointerout`]),a=/* @__PURE__ */ new WeakMap;function o(e,t,n,i){Object.defineProperty(n,"currentTarget",{configurable:!0,get:()=>t});try{r(()=>e.fn.call(t,...i))}finally{Reflect.deleteProperty(n,`currentTarget`)}}function s(e,t){return Reflect.get(e,t)}function c(t){e(()=>l(t))}function l(e){let t=`$$${e.type}`,n=`${t}Data`,r=[];for(let i of e.composedPath()){if(e.cancelBubble)break;let a=s(i,t);if(typeof a!=`function`)continue;let c=s(i,n),l={fn:a,data:c,tuple:c!==void 0};try{o(l,i,e,l.tuple?[c,e]:[e])}catch(e){r.push(e)}}let[i]=r;if(r.length===1)throw i;if(r.length>1)throw AggregateError(r,`SHADOW_EVENT_ERRORS`)}function u(e){return typeof e==`object`&&!!e&&typeof e.handleEvent==`function`}function d(t,n,i,a){let o={capture:i.capture===!0||a};i.once!==void 0&&(o.once=i.once),i.passive!==void 0&&(o.passive=i.passive),i.signal!==void 0&&(o.signal=i.signal);let s=t=>{e(()=>r(()=>i.handleEvent(t)))};return t.addEventListener(n,s,o),()=>{t.removeEventListener(n,s,o)}}function f(e){if(typeof e==`function`)return{fn:e,data:void 0,tuple:!1};if(Array.isArray(e)&&typeof e[0]==`function`)return{fn:e[0],data:e[1],tuple:!0};throw TypeError(`SHADOW_EVENT_HANDLER`)}function p(...e){return function(t){for(let n of e)n.call(this,t)}}function m(e,t=globalThis.document){let n=a.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,a.set(t,n));for(let r of e)n.has(r)||(n.add(r),t.addEventListener(r,c))}function h(e=globalThis.document){let t=a.get(e);if(t!==void 0){for(let n of t)e.removeEventListener(n,c);a.delete(e)}}function g(e){let t=e.ownerDocument;return t!==null&&t.defaultView!==null?t:globalThis.document}function _(t,n,a,o,s=!1){if(a==null||a===!1)return;if(u(a))return d(t,n,a,s);let c=f(a),l=`$$${n}`;if(o&&!s&&i.has(n)&&Reflect.get(t,l)===void 0){m([n],g(t));let e=`${l}Data`;return Reflect.set(t,l,c.fn),c.tuple?Reflect.set(t,e,c.data):Reflect.deleteProperty(t,e),()=>{Reflect.get(t,l)===c.fn&&(Reflect.deleteProperty(t,l),Reflect.deleteProperty(t,e))}}let p=n=>{let i=c.tuple?[c.data,n]:[n];e(()=>r(()=>c.fn.call(t,...i)))};return t.addEventListener(n,p,s),()=>{t.removeEventListener(n,p,s)}}function v(e,r,i,a,o){let s=_(e,r,i,a===!0,o===!0);s!==void 0&&t()!==null&&n(s)}export{v as addEventListener,_ as bindEvent,p as chainEvents,h as clearDelegatedEvents,m as delegateEvents};
2
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","names":["holder","DELEGATED_EVENTS","installed","invoke","event","node","untrack","binding","args","expando","key","dispatchDelegated","batch","dispatchPath","dataKey","errors","fn","data","error","first","isListenerObject","handler","bindListenerObject","options","object","capture","listener","el","name","toBinding","chainEvents","handlers","delegateEvents","known","target","names","clearDelegatedEvents","delegationDocument","owner","bindEvent","slot","delegate","addEventListener","unbind","getOwner","onCleanup"],"sources":["../../src/events.ts"],"sourcesContent":["import { batch, getOwner, onCleanup, untrack } from \"@shadow-js/core\";\n\n/**\n * Events that may be delegated: composed events, which leave a shadow root and reach the document.\n * `change` is not composed, so it is bound on its element (see the note on `bindEvent`).\n */\nconst DELEGATED_EVENTS = new Set([\n \"click\",\n \"dblclick\",\n \"input\",\n \"keydown\",\n \"keyup\",\n \"keypress\",\n \"pointerdown\",\n \"pointerup\",\n \"pointermove\",\n \"mousedown\",\n \"mouseup\",\n \"mousemove\",\n \"focusin\",\n \"focusout\",\n \"beforeinput\",\n \"touchstart\",\n \"touchend\",\n \"touchmove\",\n \"contextmenu\",\n \"mouseover\",\n \"mouseout\",\n \"pointerover\",\n \"pointerout\",\n]);\n\n/** Documents that already carry the delegated listener for a given event name. */\nconst installed = new WeakMap<Document, Set<string>>();\n\n/** A handler together with its optional data; `tuple` records the `[fn, data]` form. */\ninterface Binding {\n readonly fn: (this: EventTarget, ...args: unknown[]) => unknown;\n readonly data: unknown;\n readonly tuple: boolean;\n}\n\n/** Calls `fn` with `this` = node, retargeting `currentTarget` for the duration of the call. */\nfunction invoke(binding: Binding, node: EventTarget, event: Event, args: unknown[]): void {\n Object.defineProperty(event, \"currentTarget\", { configurable: true, get: () => node });\n try {\n untrack(() => binding.fn.call(node, ...args));\n } finally {\n Reflect.deleteProperty(event, \"currentTarget\");\n }\n}\n\n/** Reads a compiler-style expando (`node.$$click`), if present. */\nfunction expando(node: EventTarget, key: string): unknown {\n const holder: object = node;\n return Reflect.get(holder, key);\n}\n\n/**\n * The one listener per (document, event). It walks `composedPath()` from the target outward,\n * calling `node.$$<type>` with `this = node`. Stops when a handler stops propagation.\n */\nfunction dispatchDelegated(event: Event): void {\n // One batch per event: every handler on the path runs first, then the effects, so the DOM is\n // current when the event finishes (ADR-007).\n batch(() => dispatchPath(event));\n}\n\nfunction dispatchPath(event: Event): void {\n const key = `$$${event.type}`;\n const dataKey = `${key}Data`;\n const errors: unknown[] = [];\n for (const node of event.composedPath()) {\n if (event.cancelBubble) break;\n const fn = expando(node, key);\n if (typeof fn !== \"function\") continue;\n const data = expando(node, dataKey);\n const binding: Binding = {\n fn: fn as (this: EventTarget, ...args: unknown[]) => unknown,\n data,\n tuple: data !== undefined,\n };\n try {\n invoke(binding, node, event, binding.tuple ? [data, event] : [event]);\n } catch (error) {\n errors.push(error);\n }\n }\n const [first] = errors;\n if (errors.length === 1) throw first;\n if (errors.length > 1)\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several event handlers threw.\" : \"SHADOW_EVENT_ERRORS\",\n );\n}\n\n/** A DOM-style listener object: `handleEvent` plus the `addEventListener` options. */\ninterface ListenerObject {\n handleEvent(event: Event): unknown;\n once?: boolean;\n passive?: boolean;\n capture?: boolean;\n signal?: AbortSignal;\n}\n\nfunction isListenerObject(handler: unknown): handler is ListenerObject {\n return (\n typeof handler === \"object\" &&\n handler !== null &&\n typeof (handler as { handleEvent?: unknown }).handleEvent === \"function\"\n );\n}\n\n/** Binds a listener object natively (never delegated), honoring its options. */\nfunction bindListenerObject(\n el: Element,\n name: string,\n object: ListenerObject,\n capture: boolean,\n): () => void {\n const options: AddEventListenerOptions = { capture: object.capture === true || capture };\n if (object.once !== undefined) options.once = object.once;\n if (object.passive !== undefined) options.passive = object.passive;\n if (object.signal !== undefined) options.signal = object.signal;\n const listener = (event: Event): void => {\n batch(() => untrack(() => object.handleEvent(event)));\n };\n el.addEventListener(name, listener, options);\n return () => {\n el.removeEventListener(name, listener, options);\n };\n}\n\n/** Normalizes a handler value into a binding; throws for values that are neither. */\nfunction toBinding(handler: unknown): Binding {\n if (typeof handler === \"function\") {\n return { fn: handler as Binding[\"fn\"], data: undefined, tuple: false };\n }\n if (Array.isArray(handler) && typeof handler[0] === \"function\") {\n return { fn: handler[0] as Binding[\"fn\"], data: handler[1], tuple: true };\n }\n throw new TypeError(\n __DEV__\n ? \"addEventListener(): the handler must be a function, [function, data] or an object with handleEvent.\"\n : \"SHADOW_EVENT_HANDLER\",\n );\n}\n\n/**\n * Combines several handlers for one event name on one element into one handler that calls them in\n * order with the same event. The compiler uses it when an element has, for example, both `onInput`\n * and a text input's `onChange`: the delegated slot holds one function.\n *\n * @param handlers The handlers, in source order. None gives a handler that does nothing.\n * @returns A handler that calls each of them with the same `this` and event. An error thrown by one\n * handler propagates and the later handlers do not run.\n * @example\n * import { addEventListener, chainEvents } from \"@shadow-js/web\";\n *\n * const input = document.createElement(\"input\");\n * const onInput = chainEvents(\n * (event) => console.log(\"validate\", event.type),\n * (event) => console.log(\"save\", event.type),\n * );\n * addEventListener(input, \"input\", onInput);\n * @since 1.0.0\n */\nexport function chainEvents(\n ...handlers: Array<(this: EventTarget, event: Event) => unknown>\n): (this: EventTarget, event: Event) => void {\n return function chained(this: EventTarget, event: Event): void {\n for (const handler of handlers) handler.call(this, event);\n };\n}\n\n/**\n * Installs the document listener that runs delegated handlers for each event name, once per\n * document and name; repeated calls do nothing. Compiled modules call it for the events they\n * delegate, so application code rarely needs it. The listener walks `composedPath()` from the target\n * outward and runs each element's delegated handler in one batch, stopping when a handler stops\n * propagation. A non-composed event raised inside a shadow root never reaches the document, so bind\n * such events natively.\n *\n * @param names Event names to delegate, such as `[\"click\", \"input\"]`.\n * @param target Document that receives the listeners. Default: the global `document`.\n * @example\n * import { delegateEvents } from \"@shadow-js/web\";\n *\n * delegateEvents([\"click\", \"input\"]);\n * @see clearDelegatedEvents\n * @since 1.0.0\n */\nexport function delegateEvents(names: string[], target: Document = globalThis.document): void {\n let known = installed.get(target);\n if (known === undefined) {\n known = new Set<string>();\n installed.set(target, known);\n }\n for (const name of names) {\n if (known.has(name)) continue;\n known.add(name);\n target.addEventListener(name, dispatchDelegated);\n }\n}\n\n/**\n * Removes the delegated listeners {@link delegateEvents} installed on `target`. Delegated handlers stop\n * running until `delegateEvents` is called again (Solid's `clearDelegatedEvents`). Use it when a page\n * unmounts ShadowJS entirely, for example a micro-frontend that hands the document back. A document\n * without delegated listeners is left as is.\n *\n * @param target Document whose listeners are removed. Default: the global `document`.\n * @example\n * import { clearDelegatedEvents } from \"@shadow-js/web\";\n *\n * export function unmountApp(dispose: () => void): void {\n * dispose();\n * clearDelegatedEvents();\n * }\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function clearDelegatedEvents(target: Document = globalThis.document): void {\n const known = installed.get(target);\n if (known === undefined) return;\n for (const name of known) target.removeEventListener(name, dispatchDelegated);\n installed.delete(target);\n}\n\n/**\n * The document that must carry the delegated listener for `el`. A template clone is owned by the\n * template's inert document (no window, never receives an event) until it is inserted, and handlers\n * are bound before that: use the page's document then, which is where the element will live.\n */\nfunction delegationDocument(el: Element): Document {\n const owner = el.ownerDocument;\n return owner !== null && owner.defaultView !== null ? owner : globalThis.document;\n}\n\n/**\n * Binds one handler and returns the function that undoes it. A delegated event is stored on the\n * element as an expando; the document listener picks it up. Other events get a native listener.\n * Non-composed events (`change`, `select`, `load`, ...) never leave a shadow root, so they always get\n * a native listener, whatever the caller asked for.\n * @internal\n */\nexport function bindEvent(\n el: Element,\n name: string,\n handler: unknown,\n delegate: boolean,\n capture = false,\n): (() => void) | undefined {\n if (handler === null || handler === undefined || handler === false) return undefined;\n if (isListenerObject(handler)) return bindListenerObject(el, name, handler, capture);\n const binding = toBinding(handler);\n // One delegated slot per event name: a second handler for the same name on this element (React's\n // onInput and onChange on one text input) binds natively, so both run.\n const slot = `$$${name}`;\n if (delegate && !capture && DELEGATED_EVENTS.has(name) && Reflect.get(el, slot) === undefined) {\n delegateEvents([name], delegationDocument(el));\n const dataKey = `${slot}Data`;\n Reflect.set(el, slot, binding.fn);\n if (binding.tuple) Reflect.set(el, dataKey, binding.data);\n else Reflect.deleteProperty(el, dataKey);\n return () => {\n if (Reflect.get(el, slot) === binding.fn) {\n Reflect.deleteProperty(el, slot);\n Reflect.deleteProperty(el, dataKey);\n }\n };\n }\n const listener = (event: Event): void => {\n const args: unknown[] = binding.tuple ? [binding.data, event] : [event];\n batch(() => untrack(() => binding.fn.call(el, ...args)));\n };\n el.addEventListener(name, listener, capture);\n return () => {\n el.removeEventListener(name, listener, capture);\n };\n}\n\n/**\n * Binds an event handler to an element: the helper compiled templates call for `onX` and the `on:`\n * and `oncapture:` prefixes. Handlers run batched and untracked, with `this` set to the element.\n * Inside an owner, the listener is removed when the owner is disposed, even if the element outlives\n * it.\n *\n * @param el Target element.\n * @param name Event name, lowercase, such as `click`.\n * @param handler A function (called with the event), a `[fn, data]` tuple (called as\n * `fn(data, event)`), or a listener object `{ handleEvent, once, passive, capture, signal }`, which\n * is always bound natively with those options. `null`, `undefined` and `false` bind nothing.\n * @param delegate `true` stores the handler on the element for the document listener of\n * {@link delegateEvents} (installed on demand) when `name` is a delegated event (`click`, `input`,\n * `keydown`, pointer, mouse, touch and focus events, ...) and the element has no delegated handler\n * for it yet. Otherwise, and when undefined, the handler gets a native listener.\n * @param capture `true` listens in the capture phase, never delegated. Undefined means the bubble phase.\n * @throws TypeError `SHADOW_EVENT_HANDLER` when `handler` is not a function, a tuple whose first item\n * is a function, or a listener object.\n * @example\n * import { addEventListener } from \"@shadow-js/web\";\n *\n * const button = document.createElement(\"button\");\n * addEventListener(button, \"click\", () => console.log(\"pressed\"), true);\n * addEventListener(button, \"focus\", [(id: string, event: Event) => console.log(id, event.type), \"save\"]);\n * @see delegateEvents\n * @since 1.0.0\n */\nexport function addEventListener(\n el: Element,\n name: string,\n handler: unknown,\n delegate?: boolean,\n capture?: boolean,\n): void {\n const unbind = bindEvent(el, name, handler, delegate === true, capture === true);\n // The listener goes when the owner does, even if the element outlives it (moved, portaled, reused).\n if (unbind !== undefined && getOwner() !== null) onCleanup(unbind);\n}\n"],"mappings":"A,kFAMA,MAAMC,kBAAmB,IAAI,IAAI,CAC/B,QACA,WACA,QACA,UACA,QACA,WACA,cACA,YACA,cACA,YACA,UACA,YACA,UACA,WACA,cACA,aACA,WACA,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,EACd,EACA,EACA,EACA,EACA,EACM,CACN,IAAMC,EAASJ,EAAUZ,EAAIC,EAAMP,EAASoB,IAAa,GAAMhB,IAAY,EAAI,EAE3EkB,IAAW,IAAA,IAAaC,EAAS,IAAM,MAAMC,EAAUF,CAAM,CACnE,C"}
@@ -0,0 +1 @@
1
+ import{warnOnce as e}from"./internal/diagnostics.js";import{isUnsafeUrlAttribute as t}from"./attributes.js";import{HTML_NS as n,MATHML_NS as r,SVG_NS as i}from"./internal/names.js";import{childScope as a,createRootScope as o,currentScope as s,enterComponent as c,nextKey as l,resourceKey as u,withScope as d}from"./internal/hydration-scope.js";import{claimElement as f,claimPortal as p,isClaiming as m,takeRegion as h,withoutClaiming as g}from"./internal/claim.js";import{claims as _}from"./internal/hydration-hooks.js";import{reconcileNodes as v}from"./internal/reconcile.js";import{bindRegion as y,createRegion as b,removeRegion as x}from"./insert.js";import{element as S}from"./element.js";import{PortalContext as C}from"./internal/portal-context.js";import{StreamContext as w}from"./internal/stream-context.js";export{n as HTML_NS,r as MATHML_NS,C as PortalContext,i as SVG_NS,w as StreamContext,y as bindRegion,a as childScope,f as claimElement,p as claimPortal,_ as claims,b as createRegion,o as createRootScope,s as currentScope,S as element,c as enterComponent,m as isClaiming,t as isUnsafeUrlAttribute,l as nextKey,v as reconcileNodes,x as removeRegion,u as resourceKey,h as takeRegion,e as warnOnce,d as withScope,g as withoutClaiming};
@@ -0,0 +1,2 @@
1
+ import{useHead as e}from"./use-head.js";function t(e){if(typeof e==`string`)return e;if(typeof e==`number`)return String(e);if(e==null||e===!1)return``;throw TypeError(`SHADOW_HEAD_TITLE_TEXT`)}function n(e){let n=typeof e==`function`?e():e;return Array.isArray(n)?n.map(t).join(``):t(n)}function r(e){if(e!=null){if(typeof e==`string`&&e!==``)return e;throw TypeError(`SHADOW_HEAD_KEY`)}}function i(e){if(e!=null&&e!==!1){if(e===!0)return!0;if(typeof e==`string`||typeof e==`number`)return e;throw TypeError(`SHADOW_HEAD_ATTRIBUTE_VALUE`)}}function a(e,t){let n=[];for(let r of Object.keys(e))t.includes(r)||n.push([r,i(Reflect.get(e,r))]);return Object.fromEntries(n)}function o(e,t,n){return{tag:e,props:a(t,n)}}function s(t){return e(()=>({tag:`title`,children:n(t.children)})),null}function c(t){return e(()=>o(`meta`,t,[`children`])),null}function l(t){return e(()=>o(`link`,t,[`children`])),null}function u(t){return e(()=>{let e=a(t,[`children`,`key`]),i=t.children===void 0?void 0:n(t.children),o=r(t.key);return{tag:`style`,props:e,...i===void 0?{}:{children:i},...o===void 0?{}:{key:o}}}),null}function d(t){return e(()=>o(`base`,t,[`children`])),null}export{d as Base,l as Link,c as Meta,u as Style,s as Title};
2
+ //# sourceMappingURL=components.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"components.js","names":["partText","value","textOf","resolved","keyOf","attributeValue","attributesOf","entries","key","props","skip","attributeTag","Title","useHead","Meta","Link","Style","attributes","text","Base"],"sources":["../../../src/head/components.ts"],"sourcesContent":["import { useHead } from \"./use-head\";\nimport type { HeadAttributeValue, HeadTag, HeadTagName } from \"./validate\";\n\n/**\n * Props of {@link Title}.\n * @since 1.0.0\n */\nexport interface TitleProps {\n /**\n * The title text: a string, a number, an array of those, or an accessor returning them. `null`,\n * `undefined` and `false` count as empty text; anything else throws a TypeError.\n * @default undefined (the title is the empty string)\n */\n readonly children?: unknown;\n}\n\n/**\n * Props of {@link Meta}, {@link Link} and {@link Base}: every prop is an attribute, and a function\n * value is read reactively.\n * @since 1.0.0\n */\nexport interface HeadAttributeProps {\n /**\n * One attribute of the tag. A string or number is written as text, `true` as an empty attribute,\n * and `false`, `null` or `undefined` omit it. Any other value throws a TypeError.\n */\n readonly [attribute: string]: unknown;\n}\n\n/**\n * Props of {@link Style}: the CSS text and an optional key that replaces an earlier style with the\n * same key.\n * @since 1.0.0\n */\nexport interface StyleProps {\n /**\n * The CSS text: a string, a number, an array of those, or an accessor returning them.\n * @default undefined (the style has no text)\n */\n readonly children?: unknown;\n /**\n * Identity of the style: a later style with the same key replaces an earlier one. Must be a\n * non-empty string.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: unknown;\n /** One attribute of the `<style>` element, such as `media`, with the same rules as {@link HeadAttributeProps}. */\n readonly [attribute: string]: unknown;\n}\n\n/** Text of a value that may be an accessor. Anything but text or an array of text throws. */\nfunction partText(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n if (value === undefined || value === null || value === false) return \"\";\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: Title children must be text.\" : \"SHADOW_HEAD_TITLE_TEXT\",\n );\n}\n\n/** The text a Title shows. An accessor is called once, so its reads are tracked by the caller. */\nfunction textOf(value: unknown): string {\n const resolved = typeof value === \"function\" ? (value as () => unknown)() : value;\n if (Array.isArray(resolved)) return (resolved as unknown[]).map(partText).join(\"\");\n return partText(resolved);\n}\n\n/** The style key of a prop: absent stays absent, a non-empty string is kept, anything else throws. */\nfunction keyOf(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined;\n if (typeof value === \"string\" && value !== \"\") return value;\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n}\n\n/** One attribute value from a prop: strings, numbers and booleans are kept, the rest is an error. */\nfunction attributeValue(value: unknown): HeadAttributeValue {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return true;\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return value;\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * The attributes of a component's props, reading each prop (so a getter is tracked by the\n * caller). `skip` lists props that are not attributes.\n */\nfunction attributesOf(props: object, skip: readonly string[]): Record<string, HeadAttributeValue> {\n const entries: Array<[string, HeadAttributeValue]> = [];\n for (const key of Object.keys(props)) {\n if (skip.includes(key)) continue;\n entries.push([key, attributeValue(Reflect.get(props, key))]);\n }\n return Object.fromEntries(entries);\n}\n\n/** A tag with attributes and no text, of the given name. */\nfunction attributeTag(tag: HeadTagName, props: object, skip: readonly string[]): HeadTag {\n return { tag, props: attributesOf(props, skip) };\n}\n\n/**\n * Sets the document title. The last registered Title wins; removing it restores the one below, or\n * the original title when none is left.\n *\n * @param props The title text.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_TITLE_TEXT`) when the children are not text.\n * @example\n * import { Title } from \"@shadow-js/web\";\n *\n * function Home() {\n * return <Title>Home | Blog</Title>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Title(props: TitleProps): null {\n useHead((): HeadTag => ({ tag: \"title\", children: textOf(props.children) }));\n return null;\n}\n\n/**\n * Registers a `<meta>`. Identity follows name, property, http-equiv or charset, so the last\n * description wins. Children are ignored: a meta carries no text.\n *\n * @param props Attributes, such as `name` and `content`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Meta } from \"@shadow-js/web\";\n *\n * function About() {\n * return <Meta name=\"description\" content=\"About us\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Meta(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"meta\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<link>`. Icons are keyed by rel, sizes and type; preloads and stylesheets by rel,\n * href and as; other links are append-only.\n *\n * @param props Attributes, such as `rel` and `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean, and for an invalid attribute name or an event attribute\n * (see {@link normalizeTags}).\n * @example\n * import { Link } from \"@shadow-js/web\";\n *\n * function Page() {\n * return <Link rel=\"stylesheet\" href=\"/site.css\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Link(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"link\", props, [\"children\"]));\n return null;\n}\n\n/**\n * Registers a `<style>` with the given CSS text. A `key` makes it replace an earlier style with the\n * same key; without one, every style stays.\n *\n * @param props The CSS as `children`, an optional `key`, and attributes such as `media`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_KEY`) when `key` is not a non-empty string.\n * @example\n * import { Style } from \"@shadow-js/web\";\n *\n * function Theme() {\n * return <Style key=\"theme\">{\"body { margin: 0 }\"}</Style>;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Style(props: StyleProps): null {\n useHead((): HeadTag => {\n const attributes = attributesOf(props, [\"children\", \"key\"]);\n const text = props.children === undefined ? undefined : textOf(props.children);\n const key = keyOf(props.key);\n return {\n tag: \"style\",\n props: attributes,\n ...(text === undefined ? {} : { children: text }),\n ...(key === undefined ? {} : { key }),\n };\n });\n return null;\n}\n\n/**\n * Registers the document `<base>`. There is one; the last registration wins. Base is placed first\n * in the head, as browsers expect.\n *\n * @param props Attributes, such as `href`.\n * @returns Always null: nothing is rendered in place.\n * @throws TypeError (production message `SHADOW_HEAD_ATTRIBUTE_VALUE`) for an attribute value that\n * is not a string, number or boolean.\n * @example\n * import { Base } from \"@shadow-js/web\";\n *\n * function Shell() {\n * return <Base href=\"/app/\" />;\n * }\n * @see useHead\n * @since 1.0.0\n */\nexport function Base(props: HeadAttributeProps): null {\n useHead(() => attributeTag(\"base\", props, [\"children\"]));\n return null;\n}\n"],"mappings":"A,wCAmDA,SAASA,EAAS,EAAwB,CACxC,GAAI,OAAOC,GAAU,SAAU,OAAOA,EACtC,GAAI,OAAOA,GAAU,SAAU,OAAO,OAAOA,CAAK,EAClD,GAAIA,GAAiC,MAAQA,IAAU,GAAO,MAAO,GACrE,MAAU,UACkD,wBAC5D,CACF,CAGA,SAASC,EAAO,EAAwB,CACtC,IAAMC,EAAW,OAAOF,GAAU,WAAcA,EAAwB,EAAIA,EA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S,EAAOT,EAAM,WAAa,IAAA,GAAY,IAAA,GAAYP,EAAOO,EAAM,QAAQ,EACvED,EAAMJ,EAAMK,EAAM,GAAG,EAC3B,MAAO,CACL,IAAK,QACL,MAAOQ,EACP,GAAIC,IAAS,IAAA,GAAY,CAAC,EAAI,CAAE,SAAUA,CAAK,EAC/C,GAAIV,IAAQ,IAAA,GAAY,CAAC,EAAI,CAAE,KAAI,CACrC,CACF,CAAC,EACM,IACT,CAmBA,SAAgBW,EAAK,EAAiC,CAEpD,OADAN,MAAcF,EAAa,OAAQF,EAAO,CAAC,UAAU,CAAC,CAAC,EAChD,IACT,C"}
@@ -0,0 +1,2 @@
1
+ const e=()=>void 0;function t(t){let n=/* @__PURE__ */ new Map,r=0;return{add(i){if(i.length===0)return e;let a=[];for(let e of i){let t=e.identity;t===void 0&&(t=`#${r}`,r+=1);let i=n.get(t);i===void 0&&(i=[],n.set(t,i));let o={slot:t,tag:e};i.push(o),a.push(o)}t();let o=!1;return()=>{if(!o){o=!0;for(let e of a){let t=n.get(e.slot);if(t===void 0)continue;let r=t.indexOf(e);r!==-1&&t.splice(r,1),t.length===0&&n.delete(e.slot)}t()}}},winners(){let e=[];for(let[t,r]of n){let n=r[r.length-1];n!==void 0&&e.push({slot:t,tag:n.tag})}return e}}}export{t as createHeadRegistry};
2
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","names":["noop","createHeadRegistry","stacks","appendOnly","tags","entries","tag","slot","stack","entry","onChange","removed","index","winners","top"],"sources":["../../../src/head/registry.ts"],"sourcesContent":["import type { NormalizedTag } from \"./validate\";\n\n/**\n * One rendered head element: the slot it occupies (its identity, or a unique key for an\n * append-only tag) and the tag that currently wins that slot.\n * @internal\n */\nexport interface HeadWinner {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\n/**\n * The pure head registry: no DOM, no signals. Every registration joins the stack of its identity;\n * the top of each stack is the winner. Removing a registration takes it out of its stack, so the\n * one below it wins again.\n * @internal\n */\nexport interface HeadRegistry {\n /**\n * Registers a group of tags. The returned function removes them again; calling it twice is a\n * no-op.\n */\n add(tags: readonly NormalizedTag[]): () => void;\n /** The winning tag of every slot, in the order each slot first appeared. */\n winners(): HeadWinner[];\n}\n\ninterface Entry {\n readonly slot: string;\n readonly tag: NormalizedTag;\n}\n\nconst noop = (): void => undefined;\n\n/**\n * Creates an empty head registry. `onChange` runs after every effective add or removal, so the\n * owner of the DOM can schedule one update for a whole batch.\n *\n * @param onChange Called after the registry changes.\n * @returns A registry with no winners.\n * @internal\n * @since 1.0.0\n */\nexport function createHeadRegistry(onChange: () => void): HeadRegistry {\n const stacks = new Map<string, Entry[]>();\n let appendOnly = 0;\n return {\n add(tags: readonly NormalizedTag[]): () => void {\n if (tags.length === 0) return noop;\n const entries: Entry[] = [];\n for (const tag of tags) {\n let slot = tag.identity;\n if (slot === undefined) {\n slot = `#${appendOnly}`;\n appendOnly += 1;\n }\n let stack = stacks.get(slot);\n if (stack === undefined) {\n stack = [];\n stacks.set(slot, stack);\n }\n const entry: Entry = { slot, tag };\n stack.push(entry);\n entries.push(entry);\n }\n onChange();\n let removed = false;\n return (): void => {\n if (removed) return;\n removed = true;\n for (const entry of entries) {\n const stack = stacks.get(entry.slot);\n if (stack === undefined) continue;\n const index = stack.indexOf(entry);\n if (index !== -1) stack.splice(index, 1);\n if (stack.length === 0) stacks.delete(entry.slot);\n }\n onChange();\n };\n },\n winners(): HeadWinner[] {\n const winners: HeadWinner[] = [];\n for (const [slot, stack] of stacks) {\n const top = stack[stack.length - 1];\n if (top !== undefined) winners.push({ slot, tag: top.tag });\n }\n return winners;\n },\n };\n}\n"],"mappings":"AAiCA,MAAMA,MAAmB,IAAA,GAWzB,SAAgBC,EAAmB,EAAoC,CACrE,IAAMC,kBAAS,IAAI,IACfC,EAAa,EACjB,MAAO,CACL,IAAI,EAA4C,CAC9C,GAAIC,EAAK,SAAW,EAAG,OAAOJ,EAC9B,IAAMK,EAAmB,CAAC,EAC1B,IAAK,IAAMC,KAAOF,EAAM,CACtB,IAAIG,EAAOD,EAAI,SACXC,IAAS,IAAA,KACX,EAAO,IAAIJ,IACX,GAAc,GAEhB,IAAIK,EAAQN,EAAO,IAAIK,CAAI,EACvBC,IAAU,IAAA,KACZ,EAAQ,CAAC,EACTN,EAAO,IAAIK,EAAMC,CAAK,GAExB,IAAMC,EAAe,CAAE,OAAM,KAAI,EACjCD,EAAM,KAAKC,CAAK,EAChBJ,EAAQ,KAAKI,CAAK,CACpB,CACAC,EAAS,EACT,IAAIC,EAAU,GACd,UAAmB,CACjB,GAAI,GACJ,GAAU,GACV,IAAK,IAAMF,KAASJ,EAAS,CAC3B,IAAMG,EAAQN,EAAO,IAAIO,EAAM,IAAI,EACnC,GAAID,IAAU,IAAA,GAAW,SACzB,IAAMI,EAAQJ,EAAM,QAAQC,CAAK,EAC7BG,IAAU,IAAIJ,EAAM,OAAOI,EAAO,CAAC,EACnCJ,EAAM,SAAW,GAAGN,EAAO,OAAOO,EAAM,IAAI,CAClD,CACAC,EAAS,CARC,CASZ,CACF,EACA,SAAwB,CACtB,IAAMG,EAAwB,CAAC,EAC/B,IAAK,GAAM,CAACN,EAAMC,KAAUN,EAAQ,CAClC,IAAMY,EAAMN,EAAMA,EAAM,OAAS,GAC7BM,IAAQ,IAAA,IAAWD,EAAQ,KAAK,CAAE,OAAM,IAAKC,EAAI,GAAI,CAAC,CAC5D,CACA,OAAOD,CACT,CACF,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import{escapeHtml as e}from"../server/escape.js";import{createHeadRegistry as t}from"./registry.js";import{HEAD_KEY as n,HEAD_MARKER as r}from"./validate.js";import{createContext as i}from"@shadow-js/core";const a=/* @__PURE__ */ new Set([`meta`,`link`,`base`]),o=/* @__PURE__ */ i(null,{name:`ServerHead`});function s(t,i){let o=` ${r}`;t.key!==void 0&&(o+=` ${n}="${e(t.key)}"`);for(let[n,r]of t.attributes)o+=r===``?` ${n}`:` ${n}="${e(r)}"`;if(a.has(t.tag))return`<${t.tag}${o}>`;let s=t.text??``;if(t.tag===`style`){if(/<\/style/i.test(s))throw TypeError(`ShadowJS head: style text may not contain a closing style tag.`);return`<style${i===void 0?o:`${o} nonce="${e(i)}"`}>${s}</style>`}return`<${t.tag}${o}>${e(s)}</${t.tag}>`}function c(){let e=t(()=>void 0);return{add:t=>e.add(t),clear(){e=t(()=>void 0)},html:t=>e.winners().map(e=>s(e.tag,t?.nonce)).join(``),tags:()=>e.winners().map(e=>e.tag)}}function l(e,t){if(e===void 0)return t();let n={};return o({value:e,get children(){return n.value=t(),null}}),n.value}export{o as ServerHeadContext,c as createServerHead,l as runWithServerHead};
2
+ //# sourceMappingURL=server-head.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-head.js","names":["VOID_TAGS","ServerHeadContext","tagHtml","attributes","HEAD_MARKER","tag","HEAD_KEY","escapeHtml","name","value","text","nonce","createServerHead","registry","createHeadRegistry","tags","winner","options","runWithServerHead","head","fn","holder"],"sources":["../../../src/head/server-head.ts"],"sourcesContent":["import { type Context, createContext } from \"@shadow-js/core\";\nimport { escapeHtml } from \"../server/escape\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, type NormalizedTag } from \"./validate\";\n\n/** Elements that never have content or a closing tag. */\nconst VOID_TAGS: ReadonlySet<string> = new Set([\"meta\", \"link\", \"base\"]);\n\n/**\n * The head of one server render: what `useHead`, `<Title>`, `<Meta>`, `<Link>`, `<Style>` and\n * `<Base>` registered while the app rendered. Pass it to a render function through its `head`\n * option, then write {@link ServerHead.html} into the document's `<head>`.\n *\n * Tags follow the same rules as in the browser: the last registration of an identity wins\n * (`title`, `meta` by name, ...), append-only tags all stay. Every tag carries the marker the\n * browser's head sink looks for, so the client adopts the server's elements instead of adding\n * duplicates.\n * @since 1.0.0\n */\nexport interface ServerHead {\n /** Registers tags. Used by `useHead`; the returned function removes them again. */\n add(tags: readonly NormalizedTag[]): () => void;\n /** Forgets every registration. Multi-pass renders call this before each pass. */\n clear(): void;\n /**\n * The markup of the winning tags, in registration order. With a `nonce`, every `<style>` carries\n * it, so the page's Content-Security-Policy (`style-src 'nonce-...'`) accepts the styles. Throws a\n * TypeError when the text of a style contains a closing style tag.\n *\n * @param options `nonce` is added to every `<style>`. Default: no options, so no nonce.\n */\n html(options?: { readonly nonce?: string }): string;\n /** The winning tags, for hosts that build the head themselves. */\n tags(): readonly NormalizedTag[];\n}\n\n/** The collector `useHead` writes to while a render is running; null outside a render with `head`. @internal */\nexport const ServerHeadContext: Context<ServerHead | null> =\n /* @__PURE__ */ createContext<ServerHead | null>(null, { name: \"ServerHead\" });\n\n/** Markup of one tag. Text and attribute values are escaped; `</style` cannot appear in a style. */\nfunction tagHtml(tag: NormalizedTag, nonce: string | undefined): string {\n let attributes = ` ${HEAD_MARKER}`;\n if (tag.key !== undefined) attributes += ` ${HEAD_KEY}=\"${escapeHtml(tag.key)}\"`;\n for (const [name, value] of tag.attributes) {\n attributes += value === \"\" ? ` ${name}` : ` ${name}=\"${escapeHtml(value)}\"`;\n }\n if (VOID_TAGS.has(tag.tag)) return `<${tag.tag}${attributes}>`;\n const text = tag.text ?? \"\";\n if (tag.tag === \"style\") {\n if (/<\\/style/i.test(text)) {\n throw new TypeError(\"ShadowJS head: style text may not contain a closing style tag.\");\n }\n const withNonce =\n nonce === undefined ? attributes : `${attributes} nonce=\"${escapeHtml(nonce)}\"`;\n return `<style${withNonce}>${text}</style>`;\n }\n return `<${tag.tag}${attributes}>${escapeHtml(text)}</${tag.tag}>`;\n}\n\n/**\n * Creates an empty server head collector.\n *\n * @returns A collector to pass as the `head` option of `renderToString`, `renderToStringAsync` or\n * `renderToStream`.\n * @example\n * import { createComponent, Title } from \"@shadow-js/web\";\n * import { createServerHead, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return Title({ children: \"Home\" });\n * }\n *\n * const head = createServerHead();\n * const html = renderToString(() => createComponent(App, {}), { head });\n * const page = `<!doctype html><head>${head.html()}</head><body>${html}</body>`;\n * @see useHead\n * @since 1.0.0\n */\nexport function createServerHead(): ServerHead {\n let registry: HeadRegistry = createHeadRegistry(() => undefined);\n return {\n add: (tags) => registry.add(tags),\n clear() {\n registry = createHeadRegistry(() => undefined);\n },\n html: (options) =>\n registry\n .winners()\n .map((winner) => tagHtml(winner.tag, options?.nonce))\n .join(\"\"),\n tags: () => registry.winners().map((winner) => winner.tag),\n };\n}\n\n/**\n * Runs `fn` with `head` as the collector `useHead` writes to. Server renderers call it around the\n * app; with no collector `fn` runs as is. @internal\n */\nexport function runWithServerHead<T>(head: ServerHead | undefined, fn: () => T): T {\n if (head === undefined) return fn();\n const holder: { value?: T } = {};\n ServerHeadContext({\n value: head,\n get children() {\n holder.value = fn();\n return null;\n },\n });\n return holder.value as T;\n}\n"],"mappings":"A,8MAMA,MAAMA,kBAAiC,IAAI,IAAI,CAAC,OAAQ,OAAQ,MAAM,CAAC,EA+B1DC,EACK,kBAAiC,KAAM,CAAE,KAAM,YAAa,CAAC,EAG/E,SAASC,EAAQ,EAAoB,EAAmC,CACtE,IAAIC,EAAa,IAAIC,IACjBC,EAAI,MAAQ,IAAA,KAAW,GAAc,IAAIC,EAAS,IAAIC,EAAWF,EAAI,GAAG,EAAE,IAC9E,IAAK,GAAM,CAACG,EAAMC,KAAUJ,EAAI,WAC9B,GAAcI,IAAU,GAAK,IAAID,IAAS,IAAIA,EAAK,IAAID,EAAWE,CAAK,EAAE,GAE3E,GAAIT,EAAU,IAAIK,EAAI,GAAG,EAAG,MAAO,IAAIA,EAAI,MAAMF,EAAW,GAC5D,IAAMO,EAAOL,EAAI,MAAQ,GACzB,GAAIA,EAAI,MAAQ,QAAS,CACvB,GAAI,YAAY,KAAKK,CAAI,EACvB,MAAU,UAAU,gEAAgE,EAItF,MAAO,SADLC,IAAU,IAAA,GAAYR,EAAa,GAAGA,EAAW,UAAUI,EAAWI,CAAK,EAAE,GACrD,GAAGD,EAAK,SACpC,CACA,MAAO,IAAIL,EAAI,MAAMF,EAAW,GAAGI,EAAWG,CAAI,EAAE,IAAIL,EAAI,IAAI,EAClE,CAqBA,SAAgBO,GAA+B,CAC7C,IAAIC,EAAyBC,MAAyB,IAAA,EAAS,EAC/D,MAAO,CACL,IAAM,GAASD,EAAS,IAAIE,CAAI,EAChC,OAAQ,CACN,EAAWD,MAAyB,IAAA,EAAS,CAC/C,EACA,KAAO,GACLD,EACG,QAAQ,CAAC,CACT,IAAK,GAAWX,EAAQc,EAAO,IAAKC,GAAS,KAAK,CAAC,CAAC,CACpD,KAAK,EAAE,EACZ,SAAYJ,EAAS,QAAQ,CAAC,CAAC,IAAK,GAAWG,EAAO,GAAG,CAC3D,CACF,CAMA,SAAgBE,EAAqB,EAA8B,EAAgB,CACjF,GAAIC,IAAS,IAAA,GAAW,OAAOC,EAAG,EAClC,IAAMC,EAAwB,CAAC,EAQ/B,OAPApB,EAAkB,CAChB,MAAOkB,EACP,IAAI,UAAW,CAEb,MADA,GAAO,MAAQC,EAAG,EACX,IACT,CACF,CAAC,EACMC,EAAO,KAChB,C"}
@@ -0,0 +1,2 @@
1
+ import{HEAD_KEY as e,HEAD_MARKER as t,identityOfElement as n}from"./validate.js";function r(e,t){let n=t.el;n.parentNode===e&&(n.localName===`title`&&!t.created?t.restoreText!==void 0&&n.textContent!==t.restoreText&&(n.textContent=t.restoreText):n.remove())}function i(e,t,r,i){if(r.identity!==void 0){for(let a of Array.from(e.querySelectorAll(r.tag)))if(!i.has(a)&&n(a)===t&&(a.hasAttribute(`data-shadow-head`)||r.tag===`title`))return a}}function a(n,r,a,o){let s=n.head,c=i(s,r,a,o);if(c!==void 0)return{el:c,created:!1,restoreText:a.tag===`title`?c.textContent:void 0,attributes:[]};let l=n.createElement(a.tag);return l.setAttribute(t,``),a.key!==void 0&&l.setAttribute(e,a.key),a.tag===`base`?s.insertBefore(l,s.firstChild):s.appendChild(l),{el:l,created:!0,restoreText:void 0,attributes:[]}}function o(e,t){let n=e.el,r=new Map(t.attributes);for(let[t]of e.attributes)r.has(t)||n.removeAttribute(t);for(let[e,r]of t.attributes)n.getAttribute(e)!==r&&n.setAttribute(e,r);if(e.attributes=t.attributes,t.tag===`title`||t.tag===`style`){let e=t.text??``;n.textContent!==e&&(n.textContent=e)}}function s(e){let t=/* @__PURE__ */ new Map;return n=>{let i=e.head,s=new Set(n.map(e=>e.slot));for(let[e,n]of t)s.has(e)&&n.el.parentNode===i||(t.delete(e),r(i,n));let c=/* @__PURE__ */ new Set;for(let e of t.values())c.add(e.el);for(let r of n){let n=t.get(r.slot);n===void 0&&(n=a(e,r.slot,r.tag,c),t.set(r.slot,n),c.add(n.el)),o(n,r.tag)}}}export{s as createDomHeadSink};
2
+ //# sourceMappingURL=sink.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sink.js","names":["release","el","record","head","adoptable","tag","candidate","identityOfElement","slot","acquire","doc","existing","claimed","HEAD_MARKER","HEAD_KEY","sync","wanted","name","value","text","createDomHeadSink","owned","winners","winner"],"sources":["../../../src/head/sink.ts"],"sourcesContent":["import type { HeadWinner } from \"./registry\";\nimport { HEAD_KEY, HEAD_MARKER, identityOfElement, type NormalizedTag } from \"./validate\";\n\n/**\n * What the sink knows about one element it writes. `created` elements are removed on release;\n * adopted ones are removed too unless they are titles, where the original text comes back.\n */\ninterface Owned {\n readonly el: Element;\n readonly created: boolean;\n /** Text an adopted title had before the sink took it over. */\n readonly restoreText: string | undefined;\n /** Attributes last written, so the next write can remove the ones that disappeared. */\n attributes: ReadonlyArray<readonly [string, string]>;\n}\n\n/** Removes or restores one element the sink owned. Elements already gone are ignored. */\nfunction release(head: HTMLHeadElement, record: Owned): void {\n const el = record.el;\n if (el.parentNode !== head) return;\n if (el.localName === \"title\" && !record.created) {\n if (record.restoreText !== undefined && el.textContent !== record.restoreText) {\n el.textContent = record.restoreText;\n }\n return;\n }\n el.remove();\n}\n\n/**\n * Finds an element to adopt for a slot, or returns undefined. Only identity-keyed slots adopt. A\n * server-rendered element carries the marker, and a page title or base is adopted even without it,\n * because the browser shows that one, so it must be the one that changes.\n */\nfunction adoptable(\n head: HTMLHeadElement,\n slot: string,\n tag: NormalizedTag,\n claimed: Set<Element>,\n): Element | undefined {\n if (tag.identity === undefined) return undefined;\n for (const candidate of Array.from(head.querySelectorAll(tag.tag))) {\n if (claimed.has(candidate)) continue;\n if (identityOfElement(candidate) !== slot) continue;\n if (candidate.hasAttribute(HEAD_MARKER) || tag.tag === \"title\") return candidate;\n }\n return undefined;\n}\n\n/** Takes over an existing element for a slot, or creates and marks a new one. */\nfunction acquire(doc: Document, slot: string, tag: NormalizedTag, claimed: Set<Element>): Owned {\n const head = doc.head;\n const existing = adoptable(head, slot, tag, claimed);\n if (existing !== undefined) {\n const restoreText = tag.tag === \"title\" ? existing.textContent : undefined;\n return { el: existing, created: false, restoreText, attributes: [] };\n }\n const el = doc.createElement(tag.tag);\n el.setAttribute(HEAD_MARKER, \"\");\n if (tag.key !== undefined) el.setAttribute(HEAD_KEY, tag.key);\n if (tag.tag === \"base\") head.insertBefore(el, head.firstChild);\n else head.appendChild(el);\n return { el, created: true, restoreText: undefined, attributes: [] };\n}\n\n/** Writes the attributes and text of `tag` to its element, touching only what changed. */\nfunction sync(record: Owned, tag: NormalizedTag): void {\n const el = record.el;\n const wanted = new Map<string, string>(tag.attributes);\n for (const [name] of record.attributes) {\n if (!wanted.has(name)) el.removeAttribute(name);\n }\n for (const [name, value] of tag.attributes) {\n if (el.getAttribute(name) !== value) el.setAttribute(name, value);\n }\n record.attributes = tag.attributes;\n if (tag.tag === \"title\" || tag.tag === \"style\") {\n const text = tag.text ?? \"\";\n if (el.textContent !== text) el.textContent = text;\n }\n}\n\n/**\n * Creates the DOM sink for one document. The returned function makes `document.head` show the\n * given winners: it releases elements whose slot is gone, adopts or creates the rest and updates\n * them in place. It is called once per batch of registrations, so one call is one DOM pass.\n *\n * @param doc The document whose head is written.\n * @returns A function that applies a list of winners.\n * @internal\n * @since 1.0.0\n */\nexport function createDomHeadSink(doc: Document): (winners: readonly HeadWinner[]) => void {\n const owned = new Map<string, Owned>();\n return (winners: readonly HeadWinner[]): void => {\n const head = doc.head;\n const wanted = new Set(winners.map((winner) => winner.slot));\n for (const [slot, record] of owned) {\n if (wanted.has(slot) && record.el.parentNode === head) continue;\n owned.delete(slot);\n release(head, record);\n }\n const claimed = new Set<Element>();\n for (const record of owned.values()) claimed.add(record.el);\n for (const winner of winners) {\n let record = owned.get(winner.slot);\n if (record === undefined) {\n record = acquire(doc, winner.slot, winner.tag, claimed);\n owned.set(winner.slot, record);\n claimed.add(record.el);\n }\n sync(record, winner.tag);\n }\n };\n}\n"],"mappings":"A,iFAiBA,SAASA,EAAQ,EAAuB,EAAqB,CAC3D,IAAMC,EAAKC,EAAO,GACdD,EAAG,aAAeE,IAClBF,EAAG,YAAc,SAAW,CAACC,EAAO,QAClCA,EAAO,cAAgB,IAAA,IAAaD,EAAG,cAAgBC,EAAO,cAChE,EAAG,YAAcA,EAAO,aAI5BD,EAAG,OAAO,EACZ,CAOA,SAASG,EACP,EACA,EACA,EACA,EACqB,CACrB,GAAIC,EAAI,WAAa,IAAA,GACrB,KAAK,IAAMC,KAAa,MAAM,KAAKH,EAAK,iBAAiBE,EAAI,GAAG,CAAC,EAC/D,GAAI,GAAQ,IAAIC,CAAS,GACrBC,EAAkBD,CAAS,IAAME,IACjCF,EAAU,aAAA,kBAAwB,GAAKD,EAAI,MAAQ,SAAS,OAAOC,CACzE,CAEF,CAGA,SAASG,EAAQ,EAAe,EAAc,EAAoB,EAA8B,CAC9F,IAAMN,EAAOO,EAAI,KACXC,EAAWP,EAAUD,EAAMK,EAAMH,EAAKO,CAAO,EACnD,GAAID,IAAa,IAAA,GAEf,MAAO,CAAE,GAAIA,EAAU,QAAS,GAAO,YADnBN,EAAI,MAAQ,QAAUM,EAAS,YAAc,IAAA,GACb,WAAY,CAAC,CAAE,EAErE,IAAMV,EAAKS,EAAI,cAAcL,EAAI,GAAG,EAKpC,OAJAJ,EA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rB,IAAW,IAAA,KACb,EAASO,EAAQC,EAAKa,EAAO,KAAMA,EAAO,IAAKX,CAAO,EACtDS,EAAM,IAAIE,EAAO,KAAMrB,CAAM,EAC7BU,EAAQ,IAAIV,EAAO,EAAE,GAEvBa,EAAKb,EAAQqB,EAAO,GAAG,CACzB,CACF,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import{createHeadRegistry as e}from"./registry.js";import{normalizeTags as t}from"./validate.js";import{ServerHeadContext as n}from"./server-head.js";import{createDomHeadSink as r}from"./sink.js";import{createRoot as i,getOwner as a,isServer as o,untrack as s,useContext as c,useEffect as l,useRenderEffect as u,useSignal as d}from"@shadow-js/core";const f=/* @__PURE__ */ new WeakMap;function p(t){return i(()=>{let[n,i]=d(0),a=e(()=>{i(e=>e+1)}),o=r(t);return l(()=>(n(),a.winners()),e=>{o(e)}),a},{detached:!0})}function m(e){let t=f.get(e);if(t!==void 0)return t;let n=p(e);return f.set(e,n),n}function h(e){if(o){let r=a()===null?null:c(n);r!==null&&r.add(t(s(()=>typeof e==`function`?e():e)));return}if(a()===null)return;let r=m(document);u(()=>t(typeof e==`function`?e():e),e=>r.add(e))}export{h as useHead};
2
+ //# sourceMappingURL=use-head.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-head.js","names":["registries","createRegistryFor","createRoot","version","bump","useSignal","registry","createHeadRegistry","count","apply","createDomHeadSink","doc","useEffect","winners","registryFor","known","useHead","isServer","collector","getOwner","useContext","ServerHeadContext","normalizeTags","untrack","input","useRenderEffect","tags"],"sources":["../../../src/head/use-head.ts"],"sourcesContent":["import {\n createRoot,\n getOwner,\n isServer,\n untrack,\n useContext,\n useEffect,\n useRenderEffect,\n useSignal,\n} from \"@shadow-js/core\";\nimport { createHeadRegistry, type HeadRegistry } from \"./registry\";\nimport { ServerHeadContext } from \"./server-head\";\nimport { createDomHeadSink } from \"./sink\";\nimport { type HeadInput, normalizeTags } from \"./validate\";\n\n/** One registry per document, shared by every `useHead` call on it. */\nconst registries = new WeakMap<Document, HeadRegistry>();\n\n/**\n * Creates the registry for a document and the deferred effect that writes it to the head. The\n * effect is detached: it lives as long as the document, not as long as the first caller. It runs\n * in the user-effect queue, so every registration made in one flush produces one DOM pass.\n */\nfunction createRegistryFor(doc: Document): HeadRegistry {\n return createRoot(\n (): HeadRegistry => {\n const [version, bump] = useSignal(0);\n const registry = createHeadRegistry(() => {\n bump((count) => count + 1);\n });\n const apply = createDomHeadSink(doc);\n useEffect(\n () => {\n version();\n return registry.winners();\n },\n (winners) => {\n apply(winners);\n },\n );\n return registry;\n },\n { detached: true },\n );\n}\n\n/** The registry of a document, created on first use. */\nfunction registryFor(doc: Document): HeadRegistry {\n const known = registries.get(doc);\n if (known !== undefined) return known;\n const registry = createRegistryFor(doc);\n registries.set(doc, registry);\n return registry;\n}\n\n/**\n * Registers head tags for the lifetime of the current owner. Each registration joins the stack of\n * its identity: `title` and `base` are singletons, `meta` is keyed by its name, property,\n * http-equiv or charset (and media), icons by rel, sizes and type, resource links by rel, href and\n * as, and styles by key. The last registration of an identity wins; disposing it restores the one\n * below. Append-only tags (no identity) all stay. Passing a function re-registers when its\n * dependencies change. On the client the registrations are written to `document.head` after the\n * render phase of a flush, in one pass per flush. On the server the tags go to the render's `head`\n * collector (see `createServerHead`), read once; without one, or outside an owner, nothing is\n * registered.\n *\n * @param input One tag, several tags, or a function returning them. `null`, `undefined` and `false`\n * register nothing.\n * @throws TypeError for an invalid tag description (see {@link normalizeTags}); on the client the\n * error is raised in the registration's render effect and goes to the owner's error handler.\n * In development builds, calling it on the client with no owner does not throw: it warns\n * `HEAD_OUTSIDE_OWNER` and registers nothing.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { useHead } from \"@shadow-js/web\";\n *\n * function Post() {\n * const [post] = useSignal({ title: \"Hello\" });\n * useHead(() => ({ tag: \"title\", children: `${post().title} | Blog` }));\n * return null;\n * }\n * @see Title\n * @see Meta\n * @since 1.0.0\n */\nexport function useHead(input: HeadInput | (() => HeadInput)): void {\n if (isServer) {\n const collector = getOwner() === null ? null : useContext(ServerHeadContext);\n if (collector !== null) {\n collector.add(normalizeTags(untrack(() => (typeof input === \"function\" ? input() : input))));\n }\n return;\n }\n if (getOwner() === null) {\n if (__DEV__) {\n console.warn(\"[shadow HEAD_OUTSIDE_OWNER] useHead() needs an owner; nothing was registered.\");\n }\n return;\n }\n const registry = registryFor(document);\n useRenderEffect(\n () => normalizeTags(typeof input === \"function\" ? input() : input),\n (tags) => registry.add(tags),\n );\n}\n"],"mappings":"A,6VAgBA,MAAMA,kBAAa,IAAI,QAOvB,SAASC,EAAkB,EAA6B,CACtD,OAAOC,MACe,CAClB,GAAM,CAACC,EAASC,GAAQC,EAAU,CAAC,EAC7BC,EAAWC,MAAyB,CACxCH,EAAM,GAAUI,EAAQ,CAAC,CAC3B,CAAC,EACKC,EAAQC,EAAkBC,CAAG,EAUnC,OATAC,OAEIT,EAAQ,EACDG,EAAS,QAAQ,GAEzB,GAAY,CACXG,EAAMI,CAAO,CACf,CACF,EACOP,CACT,EACA,CAAE,SAAU,EAAK,CACnB,CACF,CAGA,SAASQ,EAAY,EAA6B,CAChD,IAAMC,EAAQf,EAAW,IAAIW,CAAG,EAChC,GAAII,IAAU,IAAA,GAAW,OAAOA,EAChC,IAAMT,EAAWL,EAAkBU,CAAG,EAEtC,OADAX,EAAW,IAAIW,EAAKL,CAAQ,EACrBA,CACT,CAgCA,SAAgBU,EAAQ,EAA4C,CAClE,GAAIC,EAAU,CACZ,IAAMC,EAAYC,EAAS,IAAM,KAAO,KAAOC,EAAWC,CAAiB,EACvEH,IAAc,MAChBA,EAAU,IAAII,EAAcC,MAAe,OAAOC,GAAU,WAAaA,EAAM,EAAIA,CAAM,CAAC,CAAC,EAE7F,MACF,CACA,GAAIL,EAAS,IAAM,KAIjB,OAEF,IAAMb,EAAWQ,EAAY,QAAQ,EACrCW,MACQH,EAAc,OAAOE,GAAU,WAAaA,EAAM,EAAIA,CAAK,EAChE,GAASlB,EAAS,IAAIoB,CAAI,CAC7B,CACF,C"}
@@ -0,0 +1,2 @@
1
+ import"../internal/diagnostics.js";import{isUnsafeUrlAttribute as e}from"../attributes.js";const t=`data-shadow-head`,n=`data-shadow-key`,r=/* @__PURE__ */ new Set([`title`,`meta`,`link`,`style`,`base`]),i=/^[a-zA-Z_][a-zA-Z0-9_:.-]*$/,a=/* @__PURE__ */ new Set([t,n]),o=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),s=[`name`,`property`,`http-equiv`,`charset`],c=/* @__PURE__ */ new Set([`og:image`,`og:video`,`og:audio`,`og:locale:alternate`,`og:email`,`og:phone_number`,`og:fax_number`,`article:tag`,`article:author`,`book:author`,`book:tag`,`music:album`,`music:song`,`music:musician`,`music:creator`,`video:actor`,`video:director`,`video:writer`,`video:tag`,`fb:admins`,`twitter:image`]),l=/* @__PURE__ */ new Set([`alternate`,`author`,`archives`,`assets`,`bookmarks`,`me`,`apple-touch-startup-image`]),u=/* @__PURE__ */ new Set([`preload`,`modulepreload`,`prefetch`,`preconnect`,`dns-prefetch`,`stylesheet`]);function d(e){return r.has(e)}function f(e){return e.map(e=>`${e.length}:${e}`).join(``)}function p(e){if(e!=null&&e!==!1){if(e===!0)return``;if(typeof e==`string`)return e;if(typeof e==`number`)return String(e);throw TypeError(`SHADOW_HEAD_ATTRIBUTE_VALUE`)}}function m(t,n){if(n==null)return/* @__PURE__ */ new Map;if(typeof n!=`object`||Array.isArray(n))throw TypeError(`SHADOW_HEAD_PROPS`);let r=/* @__PURE__ */ new Map;for(let s of Object.keys(n)){if(!i.test(s))throw TypeError(`SHADOW_HEAD_ATTRIBUTE_NAME`);let c=s.toLowerCase();if(c.startsWith(`on`))throw TypeError(`SHADOW_HEAD_EVENT_ATTRIBUTE`);if(a.has(c))throw TypeError(`SHADOW_HEAD_RESERVED`);if(o.has(c))continue;let l=p(Reflect.get(n,s));l!==void 0&&(e(c,l)?`${c}${t}`:r.set(c,l))}return r}function h(e,t){if(t!=null){if(e!==`title`&&e!==`style`)throw TypeError(`SHADOW_HEAD_NO_CHILDREN`);if(typeof t!=`string`)throw TypeError(`SHADOW_HEAD_TEXT`);return t}}function g(e,t){if(t!=null){if(e!==`style`)throw TypeError(`SHADOW_HEAD_STYLE_KEY`);if(typeof t!=`string`||t===``)throw TypeError(`SHADOW_HEAD_KEY`);return t}}function _(e){if(e===void 0)return;let t=e.toLowerCase().split(/\s+/).filter(e=>e!==``);if(t.length!==0)return t.sort().join(` `)}function v(e){let t=e.get(`media`)??``;for(let n of s){let r=e.get(n);if(r!==void 0)return n===`charset`?f([`meta`,n]):c.has(r)?f([`meta`,n,r,t,e.get(`content`)??``]):f([`meta`,n,r,t])}}function y(e){let t=_(e.get(`rel`));if(t!==void 0){if(t.split(` `).some(e=>e===`icon`||e.endsWith(`-icon`)))return f([`link`,`icon`,t,e.get(`sizes`)??``,e.get(`type`)??``]);if(t===`canonical`)return f([`link`,`canonical`]);if(u.has(t))return f([`link`,`resource`,t,e.get(`href`)??``,e.get(`as`)??``]);if(l.has(t))return f([`link`,`multi`,t,e.get(`href`)??``,e.get(`hreflang`)??``,e.get(`media`)??``,e.get(`type`)??``])}}function b(e,t,n){return e===`title`?f([`title`]):e===`base`?f([`base`]):e===`style`?n===void 0?void 0:f([`style`,n]):e===`meta`?v(t):y(t)}function x(e){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`SHADOW_HEAD_TAG`);let t=Reflect.get(e,`tag`);if(typeof t!=`string`||!d(t))throw TypeError(`SHADOW_HEAD_TAG_NAME`);let n=m(t,Reflect.get(e,`props`)),r=h(t,Reflect.get(e,`children`)),i=g(t,Reflect.get(e,`key`));return{tag:t,attributes:[...n],text:r,key:i,identity:b(t,n,i)}}function S(e){return e==null||e===!1?[]:Array.isArray(e)?e.map(e=>x(e)):[x(e)]}function C(e){let t=e.localName;if(!d(t))return;let n=/* @__PURE__ */ new Map;for(let t of Array.from(e.attributes))t.name!==`data-shadow-head`&&t.name!==`data-shadow-key`&&n.set(t.name.toLowerCase(),t.value);return b(t,n,e.getAttribute(`data-shadow-key`)??void 0)}export{n as HEAD_KEY,t as HEAD_MARKER,b as identityOf,C as identityOfElement,d as isHeadTagName,x as normalizeTag,S as normalizeTags};
2
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","names":["HEAD_MARKER","HEAD_KEY","TAG_NAMES","ATTRIBUTE_NAME","RESERVED_ATTRIBUTES","FORBIDDEN_NAMES","META_IDENTITY_FIELDS","MULTI_VALUED_META","MULTI_LINK_RELS","RESOURCE_RELS","isHeadTagName","value","frame","parts","part","attributeText","attributesFrom","props","values","key","name","text","isUnsafeUrlAttribute","tag","textFrom","children","keyFrom","normalizeRel","raw","tokens","token","metaIdentity","media","lookup","field","linkIdentity","rel","identityOf","normalizeTag","input","normalizeTags","item","identityOfElement","element","attribute"],"sources":["../../../src/head/validate.ts"],"sourcesContent":["import { isUnsafeUrlAttribute, warnOnce } from \"../extend\";\n\n/**\n * Head elements the registry manages. `script` and `noscript` are refused: a head-registered\n * script would bypass CSP nonces and Trusted Types, so scripts come only from the asset pipeline.\n * @since 1.0.0\n */\nexport type HeadTagName = \"title\" | \"meta\" | \"link\" | \"style\" | \"base\";\n\n/**\n * One attribute value: a string is written as is, `true` as an empty attribute, `false` and\n * `undefined` omit it, and a number is written as text.\n * @since 1.0.0\n */\nexport type HeadAttributeValue = string | number | boolean | undefined;\n\n/**\n * Describes one head element. `key` identifies a `style` for replacement; other tags use their\n * own identity (see {@link useHead}).\n *\n * @example\n * import type { HeadTag } from \"@shadow-js/web\";\n *\n * const description: HeadTag = { tag: \"meta\", props: { name: \"description\", content: \"Docs\" } };\n * @since 1.0.0\n */\nexport interface HeadTag {\n /** The element to register: `title`, `meta`, `link`, `style` or `base`. Any other name throws. */\n readonly tag: HeadTagName;\n /**\n * The attributes of the element. Names are case-insensitive, must be valid attribute names, and\n * may not start with `on`.\n * @default undefined (the element has no attributes)\n */\n readonly props?: Readonly<Record<string, HeadAttributeValue>>;\n /**\n * The text of a `title` or `style`. Other tags take no text and throw when it is given.\n * @default undefined (no text)\n */\n readonly children?: string;\n /**\n * Identity of a `style`: a later style with the same key replaces an earlier one. Only `style`\n * takes a key.\n * @default undefined (the style has no identity and always stays)\n */\n readonly key?: string;\n}\n\n/**\n * What {@link useHead} accepts: one tag, several tags, or nothing (which registers nothing).\n * @since 1.0.0\n */\nexport type HeadInput = HeadTag | readonly HeadTag[] | null | undefined | false;\n\n/**\n * A validated tag: lower-case attribute names, the text it carries, and its identity. Produced\n * only by {@link normalizeTag}, so the registry and the DOM sink never see unchecked input.\n * @internal\n */\nexport interface NormalizedTag {\n readonly tag: HeadTagName;\n readonly attributes: ReadonlyArray<readonly [string, string]>;\n readonly text: string | undefined;\n readonly key: string | undefined;\n /** Identity that replaces earlier registrations; undefined for append-only tags. */\n readonly identity: string | undefined;\n}\n\n/** Marks every element the sink created or adopted. Callers may not supply it. @internal */\nexport const HEAD_MARKER = \"data-shadow-head\";\n/** Carries a style's key so a server-rendered style can be adopted. @internal */\nexport const HEAD_KEY = \"data-shadow-key\";\n\nconst TAG_NAMES: ReadonlySet<string> = new Set([\"title\", \"meta\", \"link\", \"style\", \"base\"]);\nconst ATTRIBUTE_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;\nconst RESERVED_ATTRIBUTES: ReadonlySet<string> = new Set([HEAD_MARKER, HEAD_KEY]);\n/** Names skipped silently, as spread does: they would reach a prototype if written as keys. */\nconst FORBIDDEN_NAMES: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\nconst META_IDENTITY_FIELDS = [\"name\", \"property\", \"http-equiv\", \"charset\"] as const;\n/**\n * Properties that repeat by design (one tag per image, per tag, per locale). Their identity includes the content,\n * so every value stays; the others are last-wins. Sub-properties of an image (`og:image:width`) are single.\n * @since 1.0.0\n */\nconst MULTI_VALUED_META: ReadonlySet<string> = new Set([\n \"og:image\",\n \"og:video\",\n \"og:audio\",\n \"og:locale:alternate\",\n \"og:email\",\n \"og:phone_number\",\n \"og:fax_number\",\n \"article:tag\",\n \"article:author\",\n \"book:author\",\n \"book:tag\",\n \"music:album\",\n \"music:song\",\n \"music:musician\",\n \"music:creator\",\n \"video:actor\",\n \"video:director\",\n \"video:writer\",\n \"video:tag\",\n \"fb:admins\",\n \"twitter:image\",\n]);\n/** Links that repeat (alternates per language, authors, archives): their identity is every attribute. */\nconst MULTI_LINK_RELS: ReadonlySet<string> = new Set([\n \"alternate\",\n \"author\",\n \"archives\",\n \"assets\",\n \"bookmarks\",\n \"me\",\n \"apple-touch-startup-image\",\n]);\nconst RESOURCE_RELS: ReadonlySet<string> = new Set([\n \"preload\",\n \"modulepreload\",\n \"prefetch\",\n \"preconnect\",\n \"dns-prefetch\",\n \"stylesheet\",\n]);\n\n/** True for the tag names the registry manages. @internal */\nexport function isHeadTagName(value: string): value is HeadTagName {\n return TAG_NAMES.has(value);\n}\n\n/**\n * Length-prefixed identity: `[\"a|b\"]` and `[\"a\", \"b\"]` can never collide because every part\n * carries its own length.\n */\nfunction frame(parts: readonly string[]): string {\n return parts.map((part) => `${part.length}:${part}`).join(\"\");\n}\n\n/** Text of an attribute value, or undefined when the attribute is omitted. */\nfunction attributeText(value: unknown): string | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (value === true) return \"\";\n if (typeof value === \"string\") return value;\n if (typeof value === \"number\") return String(value);\n throw new TypeError(\n __DEV__\n ? \"ShadowJS head: attribute values must be strings, numbers or booleans.\"\n : \"SHADOW_HEAD_ATTRIBUTE_VALUE\",\n );\n}\n\n/**\n * Validates the props of one tag and returns its lower-case, de-duplicated attributes, in order. The\n * map is the lookup that the identity is built from, so it is built once per tag.\n */\nfunction attributesFrom(tag: HeadTagName, props: unknown): ReadonlyMap<string, string> {\n if (props === undefined || props === null) return new Map();\n if (typeof props !== \"object\" || Array.isArray(props)) {\n throw new TypeError(__DEV__ ? \"ShadowJS head: props must be an object.\" : \"SHADOW_HEAD_PROPS\");\n }\n const values = new Map<string, string>();\n for (const key of Object.keys(props)) {\n if (!ATTRIBUTE_NAME.test(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: \"${key}\" is not a valid attribute name.`\n : \"SHADOW_HEAD_ATTRIBUTE_NAME\",\n );\n }\n const name = key.toLowerCase();\n if (name.startsWith(\"on\")) {\n throw new TypeError(\n __DEV__\n ? `ShadowJS head: event attribute \"${key}\" is not allowed.`\n : \"SHADOW_HEAD_EVENT_ATTRIBUTE\",\n );\n }\n if (RESERVED_ATTRIBUTES.has(name)) {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: \"${key}\" is reserved for the runtime.` : \"SHADOW_HEAD_RESERVED\",\n );\n }\n if (FORBIDDEN_NAMES.has(name)) continue;\n const text = attributeText(Reflect.get(props, key));\n if (text === undefined) continue;\n if (isUnsafeUrlAttribute(name, text)) {\n warnOnce(\"UNSAFE_URL_BLOCKED\", `Dropped the unsafe \"${name}\" value of a <${tag}> head tag.`);\n continue;\n }\n values.set(name, text);\n }\n return values;\n}\n\n/** Children text: title and style only, and only as a string. */\nfunction textFrom(tag: HeadTagName, children: unknown): string | undefined {\n if (children === undefined || children === null) return undefined;\n if (tag !== \"title\" && tag !== \"style\") {\n throw new TypeError(\n __DEV__ ? `ShadowJS head: <${tag}> takes no children.` : \"SHADOW_HEAD_NO_CHILDREN\",\n );\n }\n if (typeof children !== \"string\")\n throw new TypeError(__DEV__ ? \"ShadowJS head: children must be text.\" : \"SHADOW_HEAD_TEXT\");\n return children;\n}\n\n/** The key of a style. Only style takes one. */\nfunction keyFrom(tag: HeadTagName, key: unknown): string | undefined {\n if (key === undefined || key === null) return undefined;\n if (tag !== \"style\")\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: only <style> takes a key.\" : \"SHADOW_HEAD_STYLE_KEY\",\n );\n if (typeof key !== \"string\" || key === \"\") {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a key must be a non-empty string.\" : \"SHADOW_HEAD_KEY\",\n );\n }\n return key;\n}\n\n/** Rel tokens, lower-cased and sorted, so `\"ICON apple\"` and `\"apple icon\"` compare equal. */\nfunction normalizeRel(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const tokens = raw\n .toLowerCase()\n .split(/\\s+/)\n .filter((token) => token !== \"\");\n if (tokens.length === 0) return undefined;\n return tokens.sort().join(\" \");\n}\n\n/** Identity of a meta: its first identifying field and the media query. */\nfunction metaIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const media = lookup.get(\"media\") ?? \"\";\n for (const field of META_IDENTITY_FIELDS) {\n const value = lookup.get(field);\n if (value === undefined) continue;\n // A document has one charset, whatever its value: that meta is a singleton.\n if (field === \"charset\") return frame([\"meta\", field]);\n if (MULTI_VALUED_META.has(value))\n return frame([\"meta\", field, value, media, lookup.get(\"content\") ?? \"\"]);\n return frame([\"meta\", field, value, media]);\n }\n return undefined;\n}\n\n/** Identity of a link: icons by rel, sizes and type; preloads and stylesheets by rel, href and as. */\nfunction linkIdentity(lookup: ReadonlyMap<string, string>): string | undefined {\n const rel = normalizeRel(lookup.get(\"rel\"));\n if (rel === undefined) return undefined;\n const isIcon = rel.split(\" \").some((token) => token === \"icon\" || token.endsWith(\"-icon\"));\n if (isIcon) {\n return frame([\"link\", \"icon\", rel, lookup.get(\"sizes\") ?? \"\", lookup.get(\"type\") ?? \"\"]);\n }\n // A document has one canonical URL: a singleton, so a new value replaces the old element (and a server's\n // copy is adopted) instead of a second `<link rel=\"canonical\">` being appended.\n if (rel === \"canonical\") return frame([\"link\", \"canonical\"]);\n if (RESOURCE_RELS.has(rel)) {\n return frame([\"link\", \"resource\", rel, lookup.get(\"href\") ?? \"\", lookup.get(\"as\") ?? \"\"]);\n }\n if (MULTI_LINK_RELS.has(rel)) {\n return frame([\n \"link\",\n \"multi\",\n rel,\n lookup.get(\"href\") ?? \"\",\n lookup.get(\"hreflang\") ?? \"\",\n lookup.get(\"media\") ?? \"\",\n lookup.get(\"type\") ?? \"\",\n ]);\n }\n return undefined;\n}\n\n/** Identity of a validated tag, or undefined when the tag is append-only. @internal */\nexport function identityOf(\n tag: HeadTagName,\n lookup: ReadonlyMap<string, string>,\n key: string | undefined,\n): string | undefined {\n if (tag === \"title\") return frame([\"title\"]);\n if (tag === \"base\") return frame([\"base\"]);\n if (tag === \"style\") return key === undefined ? undefined : frame([\"style\", key]);\n return tag === \"meta\" ? metaIdentity(lookup) : linkIdentity(lookup);\n}\n\n/**\n * Validates one head tag description and computes its identity. Hostile input throws a\n * TypeError: an unknown tag (including `script`), a bad attribute name, an event attribute, a\n * reserved marker, children on a void tag, or a key on anything but a style. An unsafe URL\n * attribute is dropped with a dev warning, the same way `setAttribute` treats it.\n *\n * @param input The description, usually a {@link HeadTag}; any value is checked.\n * @returns The normalized tag.\n * @throws TypeError for every invalid input listed above.\n * @internal\n * @since 1.0.0\n */\nexport function normalizeTag(input: unknown): NormalizedTag {\n if (input === null || typeof input !== \"object\" || Array.isArray(input)) {\n throw new TypeError(\n __DEV__ ? \"ShadowJS head: a head tag must be an object.\" : \"SHADOW_HEAD_TAG\",\n );\n }\n const name = Reflect.get(input, \"tag\");\n if (typeof name !== \"string\" || !isHeadTagName(name)) {\n const shown = typeof name === \"string\" ? name : typeof name;\n throw new TypeError(\n __DEV__ ? `ShadowJS head: unsupported tag \"${shown}\".` : \"SHADOW_HEAD_TAG_NAME\",\n );\n }\n const lookup = attributesFrom(name, Reflect.get(input, \"props\"));\n const text = textFrom(name, Reflect.get(input, \"children\"));\n const key = keyFrom(name, Reflect.get(input, \"key\"));\n return {\n tag: name,\n attributes: [...lookup],\n text,\n key,\n identity: identityOf(name, lookup, key),\n };\n}\n\n/**\n * Normalizes what {@link useHead} receives: one description, a list, or nothing.\n *\n * @param input A description, a list of them, or null, undefined or false for none.\n * @returns The normalized tags, in order.\n * @throws TypeError when any description is invalid: an unknown tag (including `script`), an\n * attribute name that is not valid or starts with `on`, a reserved marker attribute, an attribute\n * value that is not a string, number or boolean, children on a tag other than `title` and `style`,\n * or a key on anything but a `style`. The production messages start with `SHADOW_HEAD_`.\n * @example\n * import { normalizeTags } from \"@shadow-js/web/server\";\n *\n * const tags = normalizeTags([\n * { tag: \"title\", children: \"A\" },\n * { tag: \"base\", props: { href: \"/\" } },\n * ]);\n * console.log(tags.length); // 2\n * @see useHead\n * @since 1.0.0\n */\nexport function normalizeTags(input: unknown): NormalizedTag[] {\n if (input === null || input === undefined || input === false) return [];\n if (Array.isArray(input)) return input.map((item: unknown) => normalizeTag(item));\n return [normalizeTag(input)];\n}\n\n/**\n * The identity of an element already in the document, computed the same way as for a\n * registration, so the sink can adopt a server-rendered element. Undefined for elements that are\n * not head tags or that are append-only.\n * @internal\n */\nexport function identityOfElement(element: Element): string | undefined {\n const name = element.localName;\n if (!isHeadTagName(name)) return undefined;\n const lookup = new Map<string, string>();\n for (const attribute of Array.from(element.attributes)) {\n if (attribute.name === HEAD_MARKER || attribute.name === HEAD_KEY) continue;\n lookup.set(attribute.name.toLowerCase(), attribute.value);\n }\n const key = element.getAttribute(HEAD_KEY) ?? undefined;\n return identityOf(name, lookup, key);\n}\n"],"mappings":"A,2FAqEA,MAAaA,EAAc,mBAEdC,EAAW,kBAElBC,kBAAiC,IAAI,IAAI,CAAC,QAAS,OAAQ,OAAQ,QAAS,MAAM,CAAC,EACnFC,EAAiB,8BACjBC,kBAA2C,IAAI,IAAI,CAACJ,EAAaC,CAAQ,CAAC,EAE1EI,kBAAuC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EACxFC,EAAuB,CAAC,OAAQ,WAAY,aAAc,SAAS,EAMnEC,kBAAyC,IAAI,IAAI,CACrD,WACA,WACA,WACA,sBACA,WACA,kBACA,gBACA,cACA,iBACA,cACA,WACA,cACA,aACA,iBACA,gBACA,cACA,iBACA,eACA,YACA,YACA,eACF,CAAC,EAEKC,kBAAuC,IAAI,IAAI,CACnD,YACA,SACA,WACA,SACA,YACA,KACA,2BACF,CAAC,EACKC,kBAAqC,IAAI,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L,WAAY,CAAC,GAAGa,CAAM,EACtB,OACA,MACA,SAAUI,EAAWjB,EAAMa,EAAQd,CAAG,CACxC,CACF,CAsBA,SAAgBqB,EAAc,EAAiC,CAG7D,OAFID,GAAU,MAA+BA,IAAU,GAAc,CAAC,EAClE,MAAM,QAAQA,CAAK,EAAUA,EAAM,IAAK,GAAkBD,EAAaG,CAAI,CAAC,EACzE,CAACH,EAAaC,CAAK,CAAC,CAC7B,CAQA,SAAgBG,EAAkB,EAAsC,CACtE,IAAMtB,EAAOuB,EAAQ,UACrB,GAAI,CAACjC,EAAcU,CAAI,EAAG,OAC1B,IAAMa,kBAAS,IAAI,IACnB,IAAK,IAAMW,KAAa,MAAM,KAAKD,EAAQ,UAAU,EAC/CC,EAAU,OAAA,oBAAwBA,EAAU,OAAA,mBAChDX,EAAO,IAAIW,EAAU,KAAK,YAAY,EAAGA,EAAU,KAAK,EAG1D,OAAOP,EAAWjB,EAAMa,EADZU,EAAQ,aAAA,iBAAqB,GAAK,IAAA,EACX,CACrC,C"}
@@ -0,0 +1,2 @@
1
+ import{createRootScope as e,resourceKey as t,withScope as n}from"./internal/hydration-scope.js";import{beginClaiming as r,claimElement as i,claimPortal as a,endClaiming as o,isClaiming as s,liftedRegions as c,releaseUnclaimedPortals as l,takeRegion as u,withoutClaiming as d}from"./internal/claim.js";import{claims as f}from"./internal/hydration-hooks.js";import{bindRegion as p,createRegion as m,removeRegion as h}from"./insert.js";import{attachRootErrors as g}from"./control-flow/root-errors.js";import{replayEarlyEvents as _}from"./internal/early-events.js";import{ResourceCacheContext as v,batch as y,createRoot as b,flushSync as x,runWithOwner as S,untrack as C}from"@shadow-js/core";import{withHydration as w}from"@shadow-js/core/extend";function T(e){let n=/* @__PURE__ */ new Set;return{key:t,read(t){if(!n.has(t)&&Object.hasOwn(e,t))return n.add(t),{value:e[t]}},track(){}}}function E(e){let t=e instanceof Document?e:e.ownerDocument;if(t===null)return;t.body!==null&&l(t.body);let n=t.createTreeWalker(e,NodeFilter.SHOW_COMMENT),r=[];for(;n.nextNode();){let e=n.currentNode;(e.data===`[`||e.data===`]`)&&r.push(e)}for(let e of r)e.remove()}function D(t,l,D={}){if(s())throw Error(`SHADOW_HYDRATE_RUNNING`);let O=/* @__PURE__ */ new Map,k=l instanceof Element?[l]:[];for(let e of[...k,...Array.from(l.querySelectorAll(`[data-hk]`))]){let t=e.getAttribute(`data-hk`);t!==null&&O.set(t,e)}r(O,D.onRecoverableError);let A={claimElement:i,takeRegion:u,liftedRegions:c,claimPortal:a,isClaiming:s,withoutClaiming:d},j=f.current;f.current=A;let M=T(D.data??{}),N=m(l,null,Array.from(l.childNodes)),P;try{P=w(()=>y(()=>n(e(D.renderId),()=>S(D.owner??null,()=>b(e=>(g(D),v({value:M,get children(){return p(N,C(t)),null}}),e)))))),x()}finally{o(),f.current=j}_(),E(l);let F=!1;return()=>{F||(F=!0,P(),h(N))}}export{D as hydrate};
2
+ //# sourceMappingURL=hydration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration.js","names":["dataCache","used","resourceKey","key","data","stripLeftovers","doc","container","releaseUnclaimedPortals","walker","stale","comment","hydrate","isClaiming","registry","roots","element","beginClaiming","options","passClaims","previousClaims","claims","cache","region","createRegion","stop","withHydration","batch","withScope","createRootScope","runWithOwner","createRoot","attachRootErrors","ResourceCacheContext","bindRegion","untrack","code","dispose","flushSync","endClaiming","replayEarlyEvents","disposed","removeRegion"],"sources":["../../src/hydration.ts"],"sourcesContent":["import {\n batch,\n createRoot,\n flushSync,\n type Owner,\n type ResourceCache,\n ResourceCacheContext,\n runWithOwner,\n untrack,\n} from \"@shadow-js/core\";\nimport { withHydration } from \"@shadow-js/core/extend\";\nimport { attachRootErrors, type RootErrorOptions } from \"./control-flow/root-errors\";\nimport { bindRegion, createRegion, removeRegion } from \"./insert\";\nimport {\n beginClaiming,\n claimElement,\n claimPortal,\n endClaiming,\n isClaiming,\n liftedRegions,\n releaseUnclaimedPortals,\n takeRegion,\n withoutClaiming,\n} from \"./internal/claim\";\nimport { replayEarlyEvents } from \"./internal/early-events\";\nimport { type Claims, claims } from \"./internal/hydration-hooks\";\nimport { createRootScope, resourceKey, withScope } from \"./internal/hydration-scope\";\n\n/**\n * Options of {@link hydrate}: the server render it continues, the root's owner, and the error\n * reporters it inherits from `RootErrorOptions` (`onUncaughtError`, `onCaughtError`,\n * `onRecoverableError`).\n * @since 1.0.0\n */\nexport interface HydrateOptions extends RootErrorOptions {\n /**\n * The id the server render used, so the client numbers its elements with the same keys. Must\n * equal the `renderId` given to the server render.\n * @default \"0\"\n */\n renderId?: string;\n /**\n * The resource values the server fetched: the `data` of `renderToStringAsync`. A resource whose\n * key is found here starts with that value instead of fetching it again. Each value is used once.\n * @default {} (no resource value is preloaded; resources fetch on the client)\n */\n data?: Record<string, unknown>;\n /**\n * The owner the hydrated root is created under, so its context (providers) is visible to the app.\n * @default null (the root has no parent owner)\n */\n owner?: Owner;\n}\n\nfunction dataCache(data: Record<string, unknown>): ResourceCache {\n const used = new Set<string>();\n return {\n key: resourceKey,\n read(key) {\n if (used.has(key) || !Object.hasOwn(data, key)) return undefined;\n used.add(key);\n return { value: data[key] };\n },\n track() {\n // Client fetches are not tracked: nothing waits for them.\n },\n };\n}\n\n/**\n * Removes marker comments the pass did not claim, so the live DOM never keeps any, and the server\n * blocks of portals the client did not render (they would show content the client does not have).\n */\nfunction stripLeftovers(container: Node): void {\n const doc = container instanceof Document ? container : container.ownerDocument;\n if (doc === null) return;\n if (doc.body !== null) releaseUnclaimedPortals(doc.body);\n const walker = doc.createTreeWalker(container, NodeFilter.SHOW_COMMENT);\n const stale: Comment[] = [];\n while (walker.nextNode()) {\n const comment = walker.currentNode as Comment;\n if (comment.data === \"[\" || comment.data === \"]\") stale.push(comment);\n }\n for (const comment of stale) comment.remove();\n}\n\n/**\n * Attaches the application to HTML the server already rendered into `container`. Elements are\n * claimed by their `data-hk` keys instead of created, so the DOM is not rebuilt and nodes keep\n * their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the\n * server and client disagree on are repaired by reconciliation, never left half hydrated.\n *\n * @param code Runs once, untracked, and builds the same component tree the server rendered.\n * @param container Element or Document that holds the server markup.\n * @param options `renderId` (must match the server), the server's resource `data`, an `owner`, and\n * the error reporters. Undefined uses the defaults.\n * @returns A dispose function that stops the hydrated root and removes its nodes. Safe to call more\n * than once.\n * @throws Error (production message `SHADOW_HYDRATE_RUNNING`) when called while another hydration\n * pass is in progress.\n * @example\n * import { createComponent, hydrate } from \"@shadow-js/web\";\n *\n * function App() {\n * return \"Hello\";\n * }\n *\n * const container = document.getElementById(\"app\") as Element;\n * const data = JSON.parse(document.getElementById(\"data\")?.textContent ?? \"{}\") as Record<\n * string,\n * unknown\n * >;\n * const dispose = hydrate(() => createComponent(App, {}), container, { data });\n * @see render\n * @since 1.0.0\n */\nexport function hydrate(\n code: () => unknown,\n container: Element | Document,\n options: HydrateOptions = {},\n): () => void {\n if (isClaiming())\n throw new Error(\n __DEV__ ? \"hydrate(): a hydration pass is already running.\" : \"SHADOW_HYDRATE_RUNNING\",\n );\n const registry = new Map<string, Element>();\n const roots: Element[] = container instanceof Element ? [container] : [];\n for (const element of [...roots, ...Array.from(container.querySelectorAll(\"[data-hk]\"))]) {\n const key = element.getAttribute(\"data-hk\");\n if (key !== null) registry.set(key, element);\n }\n beginClaiming(registry, options.onRecoverableError);\n // The renderer reaches the claiming code only through this hook, installed for this pass alone.\n const passClaims: Claims = {\n claimElement,\n takeRegion,\n liftedRegions,\n claimPortal,\n isClaiming,\n withoutClaiming,\n };\n const previousClaims = claims.current;\n claims.current = passClaims;\n const cache = dataCache(options.data ?? {});\n const region = createRegion(container, null, Array.from(container.childNodes));\n let stop: () => void;\n try {\n // The batch wraps the scope, not the other way round: its exit flushes the queued effects\n // (onMount, and the re-renders they cause) after the scope is restored. The scope numbers only\n // the templates the server rendered; an effect that builds new DOM must not draw keys from it\n // (that shifts the keys of later siblings and misses the ones the server never sent). Boundaries\n // rebuild from their own captured scope, so a reset inside the pass still claims its elements.\n stop = withHydration(() =>\n batch(() =>\n withScope(createRootScope(options.renderId), () =>\n runWithOwner(options.owner ?? null, () =>\n createRoot((dispose) => {\n attachRootErrors(options);\n ResourceCacheContext({\n value: cache,\n get children() {\n bindRegion(region, untrack(code));\n return null;\n },\n });\n return dispose;\n }),\n ),\n ),\n ),\n );\n flushSync();\n } finally {\n endClaiming();\n claims.current = previousClaims;\n }\n replayEarlyEvents();\n stripLeftovers(container);\n let disposed = false;\n return () => {\n if (disposed) return;\n disposed = true;\n stop();\n removeRegion(region);\n };\n}\n"],"mappings":"A,wuBAsDA,SAASA,EAAU,EAA8C,CAC/D,IAAMC,kBAAO,IAAI,IACjB,MAAO,CACL,IAAKC,EACL,KAAK,EAAK,CACR,GAAI,GAAK,IAAIC,CAAG,GAAM,OAAO,OAAOC,EAAMD,CAAG,EAE7C,OADAF,EAAK,IAAIE,CAAG,EACL,CAAE,MAAOC,EAAKD,EAAK,CAC5B,EACA,OAAQ,CAER,CACF,CACF,CAMA,SAASE,EAAe,EAAuB,CAC7C,IAAMC,EAAMC,aAAqB,SAAWA,EAAYA,EAAU,cAClE,GAAID,IAAQ,KAAM,OACdA,EAAI,OAAS,MAAME,EAAwBF,EAAI,IAAI,EACvD,IAAMG,EAASH,EAAI,iBAAiBC,EAAW,WAAW,YAAY,EAChEG,EAAmB,CAAC,EAC1B,KAAOD,EAAO,SAAS,GAAG,CACxB,IAAME,EAAUF,EAAO,aACnBE,EAAQ,OAAS,KAAOA,EAAQ,OAAS,MAAKD,EAAM,KAAKC,CAAO,CACtE,CACA,IAAK,IAAMA,KAAWD,EAAOC,EAAQ,OAAO,CAC9C,CAgCA,SAAgBC,EACd,EACA,EACA,EAA0B,CAAC,EACf,CACZ,GAAIC,EAAW,EACb,MAAU,MACsD,wBAChE,EACF,IAAMC,kBAAW,IAAI,IACfC,EAAmBR,aAAqB,QAAU,CAACA,CAAS,EAAI,CAAC,EACvE,IAAK,IAAMS,IAAW,CAAC,GAAGD,EAAO,GAAG,MAAM,KAAKR,EAAU,iBAAiB,WAAW,CAAC,CAAC,EAAG,CACxF,IAAMJ,EAAMa,EAAQ,aAAa,SAAS,EACtCb,IAAQ,MAAMW,EAAS,IAAIX,EAAKa,CAAO,CAC7C,CACAC,EAAcH,EAAUI,EAAQ,kBAAkB,EAElD,IAAMC,EAAqB,CACzB,eACA,aACA,gBACA,cACA,aACA,iBACF,EACMC,EAAiBC,EAAO,QAC9B,EAAO,QAAUF,EACjB,IAAMG,EAAQtB,EAAUkB,EAAQ,MAAQ,CAAC,CAAC,EACpCK,EAASC,EAAajB,EAAW,KAAM,MAAM,KAAKA,EAAU,UAAU,CAAC,EACzEkB,EACJ,GAAI,CAMF,EAAOC,MACLC,MACEC,EAAUC,EAAgBX,EAAQ,QAAQ,MACxCY,EAAaZ,EAAQ,OAAS,SAC5Ba,EAAY,IACVC,EAAiBd,CAAO,EACxBe,EAAqB,CACnB,MAAOX,EACP,IAAI,UAAW,CAEb,OADAY,EAAWX,EAAQY,EAAQC,CAAI,CAAC,EACzB,IACT,CACF,CAAC,EACMC,EACR,CACH,CACF,CACF,CACF,EACAC,EAAU,CACZ,QAAU,CACRC,EAAY,EACZ,EAAO,QAAUnB,CACnB,CACAoB,EAAkB,EAClBnC,EAAeE,CAAS,EACxB,IAAIkC,EAAW,GACf,UAAa,CACPA,IACJ,EAAW,GACXhB,EAAK,EACLiB,EAAanB,CAAM,EACrB,CACF,C"}
@@ -0,0 +1 @@
1
+ import{setAttribute as e,setAttributeNS as t,setBoolAttribute as n}from"./attributes.js";import{autoFocus as r}from"./autofocus.js";import{classList as i,className as a,setStyleProperty as o,style as s}from"./class-style.js";import{createComponent as c}from"./component.js";import{Activity as l}from"./control-flow/activity.js";import{Show as u}from"./control-flow/show.js";import{ClientOnly as d}from"./control-flow/client-only.js";import{anchor as f,insert as p}from"./insert.js";import{element as m}from"./element.js";import{addEventListener as h,chainEvents as g,clearDelegatedEvents as _,delegateEvents as v}from"./events.js";import{setSelectValue as y}from"./select-value.js";import{spread as b}from"./spread.js";import{Dynamic as x,createDynamic as S}from"./control-flow/dynamic.js";import{ErrorBoundary as C}from"./control-flow/error-boundary.js";import{For as w}from"./control-flow/for.js";import{Fragment as T}from"./control-flow/fragment.js";import{Index as E}from"./control-flow/index-list.js";import{lazy as D}from"./control-flow/lazy.js";import{NoHydration as O}from"./control-flow/no-hydration.js";import{Portal as k}from"./control-flow/portal.js";import{SuspenseList as A}from"./control-flow/suspense-list.js";import{Suspense as j}from"./control-flow/suspense.js";import{Match as M,Switch as N}from"./control-flow/switch.js";import{derived as P}from"./derived.js";import{useHead as F}from"./head/use-head.js";import{Base as I,Link as L,Meta as R,Style as z,Title as B}from"./head/components.js";import{hydrate as V}from"./hydration.js";import{effect as H,memo as U,refTo as W,use as G}from"./reactive.js";import{render as K}from"./render.js";import{preconnect as q,prefetchDNS as J,preinit as Y,preinitModule as X,preload as Z,preloadModule as Q}from"./resource-hints.js";import{template as $}from"./template.js";import{ViewTransition as ee,startViewTransition as te}from"./view-transition.js";import{isDev as ne,isServer as re,mergeProps as ie}from"@shadow-js/core";export{l as Activity,I as Base,d as ClientOnly,x as Dynamic,C as ErrorBoundary,w as For,T as Fragment,E as Index,L as Link,M as Match,R as Meta,O as NoHydration,k as Portal,u as Show,z as Style,j as Suspense,A as SuspenseList,N as Switch,B as Title,ee as ViewTransition,h as addEventListener,f as anchor,r as autoFocus,g as chainEvents,i as classList,a as className,_ as clearDelegatedEvents,c as createComponent,S as createDynamic,v as delegateEvents,P as derived,H as effect,m as element,V as hydrate,p as insert,ne as isDev,re as isServer,D as lazy,U as memo,ie as mergeProps,q as preconnect,J as prefetchDNS,Y as preinit,X as preinitModule,Z as preload,Q as preloadModule,W as refTo,K as render,e as setAttribute,t as setAttributeNS,n as setBoolAttribute,y as setSelectValue,o as setStyleProperty,b as spread,te as startViewTransition,s as style,$ as template,G as use,F as useHead};
@@ -0,0 +1,2 @@
1
+ import{claims as e}from"./internal/hydration-hooks.js";import{reconcileNodes as t}from"./internal/reconcile.js";import{useRenderEffect as n}from"@shadow-js/core";import{createComputation as r,currentOwner as i,disposeOwner as a,readComputation as o}from"@shadow-js/core/extend";function s(e){return e instanceof Document?e:e.ownerDocument??document}function c(e,t){let n=e.texts;return n===t||n instanceof Set&&n.has(t)}function l(e,t){let n=e.texts;n===null?e.texts=t:n instanceof Set?n.add(t):n!==t&&(e.texts=/* @__PURE__ */ new Set([n,t]))}function u(e,t){let n=e.texts;if(n!==null){if(n instanceof Set){let e=new Set(t);for(let t of n)e.has(t)||n.delete(t)}else t.includes(n)||(e.texts=null)}}function d(e,t=e=>e()){let n=[],r=[[e]],i=[0],a=/* @__PURE__ */ new Set;for(;r.length>0;){let e=r.length-1,o=r[e],s=i[e]??0;if(o===void 0||s>=o.length){let e=r.pop();e!==void 0&&a.delete(e),i.pop();continue}i[e]=s+1;let c=o[s];for(let e=0;typeof c==`function`;e+=1){if(e>=1e4)throw TypeError(`SHADOW_INSERT_DEPTH`);c=t(c)}if(c!=null&&typeof c!=`boolean`){if(typeof c==`string`)n.push(c);else if(typeof c==`number`)n.push(String(c));else if(c instanceof DocumentFragment)for(let e of c.childNodes)n.push(e);else if(c instanceof Node)n.push(c);else if(Array.isArray(c)){if(a.has(c))throw TypeError(`SHADOW_INSERT_CYCLE`);a.add(c),r.push(c),i.push(0)}else n.push(String(c))}}return n}function f(e){let t=/* @__PURE__ */ new Map;for(let n of e.nodes){if(!(n instanceof Text)||!c(e,n))continue;let r=t.get(n.data);r===void 0?t.set(n.data,[n]):r.push(n)}return t}function p(e,t){let n=t.length===1?t[0]:void 0;if(typeof n==`string`){let t=e.nodes.length===1?e.nodes[0]:void 0;if(t instanceof Text&&c(e,t))return t.data!==n&&(t.data=n),[t]}let r=Array(t.length),i=0,a=/* @__PURE__ */ new Set,o;for(let n of t)if(typeof n==`string`){o??=f(e);let t=o.get(n)?.pop();t===void 0&&(t=s(e.parent).createTextNode(n),l(e,t)),a.add(t),r[i]=t,i+=1}else a.has(n)||(a.add(n),r[i]=n,i+=1);return r.length=i,r}function m(e,t){if(e.anchor!==null)return e.anchor;let n=t.at(-1);if(n!==void 0)return n.nextSibling;let r=e.marker;return r===null?e.parent.firstChild:r.parentNode===e.parent?r.nextSibling:null}function h(e,n){let r=e.parent,i=e.nodes.filter(e=>e.parentNode===r),a=m(e,i),o=i[0];n.length===0&&o!==void 0&&(e.marker=o.previousSibling),t(r,i,n,a),e.nodes=n,u(e,n)}function g(e,t){h(e,p(e,t))}function _(e,t){if(typeof t==`string`||typeof t==`number`){let n=e.nodes,r=typeof t==`string`?t:String(t);if(n.length===1){let t=n[0];if(t instanceof Text&&t.parentNode===e.parent&&c(e,t)){t.data!==r&&(t.data=r);return}}else if(n.length===0){let t=s(e.parent).createTextNode(r);l(e,t),e.parent.insertBefore(t,m(e,n)),e.nodes=[t];return}}g(e,d(t))}function v(e,t){let n=[],r=/* @__PURE__ */ new Set;for(let i of d(t))typeof i==`string`||r.has(i)||i.parentNode!==e||(r.add(i),n.push(i));return n}function y(e,t,n){let r=n===void 0?[]:v(e,n),i={parent:e,anchor:t,marker:r.length>0?r[0]?.previousSibling??null:e.lastChild,nodes:r,texts:null};for(let e of r)e instanceof Text&&l(i,e);return i}function b(e){if(typeof e==`function`)return!0;if(!Array.isArray(e))return!1;let t=[e],n=/* @__PURE__ */ new Set([e]);for(;t.length>0;){let e=t.pop()??[];for(let r of e){if(typeof r==`function`)return!0;Array.isArray(r)&&!n.has(r)&&(n.add(r),t.push(r))}}return!1}function x(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Set;return{begin(){n=/* @__PURE__ */ new Set},call(i){n.add(i);let a=t.get(i);return a===void 0&&(a=r({kind:`memo`,fn:()=>i(),allowWrites:!0,owner:e}),t.set(i,a)),o(a)},prune(){for(let[e,r]of t)n.has(e)||(t.delete(e),a(r))}}}function S(e,t){if(!b(t))return _(e,t),t instanceof DocumentFragment?[...e.nodes]:t;let r;return n(typeof t==`function`?t:()=>t,t=>{if(r=t,b(t)){let r=x(i());n(()=>{r.begin();let e=d(t,r.call);return r.prune(),e},t=>{g(e,t)})}else _(e,t)}),r}function C(e){for(let t of e.nodes)t.parentNode===e.parent&&e.parent.removeChild(t);e.nodes=[],e.texts=null}function w(e,t){let n=s(e).createTextNode(``);return e.insertBefore(n,t),n}function T(t,n,r,i){let a=r??null;return S(y(t,a,i===void 0?e.current.takeRegion(t,a):i),n)}export{w as anchor,S as bindRegion,y as createRegion,T as insert,C as removeRegion};
2
+ //# sourceMappingURL=insert.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"insert.js","names":["documentOf","node","ownsText","texts","region","addText","text","pruneTexts","kept","keep","flatten","fn","parts","frames","root","cursors","active","top","frame","cursor","done","item","depth","call","child","reusablePool","pool","list","materialize","only","current","nodes","count","seen","part","endOf","last","attached","marker","reconcileRegion","parent","end","first","next","reconcileNodes","commit","commitValue","raw","created","adoptInitial","adopted","initial","createRegion","anchorNode","containsFunction","stack","createCallCache","memos","touched","createComputation","readComputation","disposeOwner","bindRegion","value","latest","useRenderEffect","cache","currentOwner","removeRegion","anchor","before","insert","resolvedAnchor","claims"],"sources":["../../src/insert.ts"],"sourcesContent":["import { useRenderEffect } from \"@shadow-js/core\";\nimport {\n type ComputationNode,\n createComputation,\n currentOwner,\n disposeOwner,\n readComputation,\n} from \"@shadow-js/core/extend\";\nimport { checkClaimedText } from \"./internal/claim\";\nimport { claims } from \"./internal/hydration-hooks\";\nimport { reconcileNodes } from \"./internal/reconcile\";\n\n/** One piece of a value after flattening: a DOM node, or text to be turned into a Text node. */\ntype Part = Node | string;\n\n/** Longest chain of accessors a single value may hold (a function returning a function ...). */\nconst MAX_ACCESSOR_DEPTH = 10_000;\n\n/**\n * State of one dynamic child region. `nodes` are the DOM nodes the region owns, in order. When\n * `anchor` is set, content goes before it. Without one, an empty region is placed after `marker`\n * (the node that preceded it), so it keeps its position while it is empty.\n * @internal\n */\nexport interface Region {\n readonly parent: Node;\n readonly anchor: Node | null;\n marker: Node | null;\n nodes: Node[];\n /**\n * Text nodes this region created or adopted; only these may be reused by string updates. Null for none, the node\n * itself for one (the usual region: a single dynamic text), a Set for more, so most regions allocate no Set.\n */\n texts: Text | Set<Text> | null;\n /**\n * Development only: the server nodes a hydration pass handed this region, kept until its first\n * commit compares their text with the value (`checkClaimedText`).\n */\n claimed?: readonly Node[] | undefined;\n}\n\n/** The document a node belongs to (a Document is its own document). */\nfunction documentOf(node: Node): Document {\n return node instanceof Document ? node : (node.ownerDocument ?? document);\n}\n\n/** True when the region created or adopted `node`. */\nfunction ownsText(region: Region, node: Node): boolean {\n const texts = region.texts;\n return texts === node || (texts instanceof Set && texts.has(node as Text));\n}\n\n/** Records that the region owns `text`. */\nfunction addText(region: Region, text: Text): void {\n const texts = region.texts;\n if (texts === null) region.texts = text;\n else if (texts instanceof Set) texts.add(text);\n else if (texts !== text) region.texts = new Set([texts, text]);\n}\n\n/** Forgets the Text nodes of the region that are not in `keep`. */\nfunction pruneTexts(region: Region, keep: readonly Node[]): void {\n const texts = region.texts;\n if (texts === null) return;\n if (texts instanceof Set) {\n const kept = new Set<Node>(keep);\n for (const text of texts) {\n if (!kept.has(text)) texts.delete(text);\n }\n } else if (!keep.includes(texts)) region.texts = null;\n}\n\n/**\n * Flattens a value into parts without recursion. Functions are called (and their results unwrapped)\n * through `call`, which runs inside the render effect that owns the value, so reads are tracked.\n */\nfunction flatten(root: unknown, call: (fn: () => unknown) => unknown = (fn) => fn()): Part[] {\n const parts: Part[] = [];\n const frames: unknown[][] = [[root]];\n const cursors: number[] = [0];\n const active = new Set<unknown[]>();\n while (frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined || cursor >= frame.length) {\n const done = frames.pop();\n if (done !== undefined) active.delete(done);\n cursors.pop();\n continue;\n }\n cursors[top] = cursor + 1;\n let item: unknown = frame[cursor];\n for (let depth = 0; typeof item === \"function\"; depth += 1) {\n if (depth >= MAX_ACCESSOR_DEPTH)\n throw new TypeError(\n __DEV__ ? \"insert(): accessor chain is too deep.\" : \"SHADOW_INSERT_DEPTH\",\n );\n item = call(item as () => unknown);\n }\n if (item === null || item === undefined || typeof item === \"boolean\") continue;\n if (typeof item === \"string\") parts.push(item);\n else if (typeof item === \"number\") parts.push(String(item));\n else if (item instanceof DocumentFragment) {\n for (const child of item.childNodes) parts.push(child);\n } else if (item instanceof Node) parts.push(item);\n else if (Array.isArray(item)) {\n if (active.has(item))\n throw new TypeError(__DEV__ ? \"insert(): a value contains itself.\" : \"SHADOW_INSERT_CYCLE\");\n active.add(item);\n frames.push(item);\n cursors.push(0);\n } else parts.push(String(item));\n }\n return parts;\n}\n\n/** Text nodes the region currently owns, keyed by their data, for reuse by equal strings. */\nfunction reusablePool(region: Region): Map<string, Text[]> {\n const pool = new Map<string, Text[]>();\n for (const node of region.nodes) {\n if (!(node instanceof Text) || !ownsText(region, node)) continue;\n const list = pool.get(node.data);\n if (list === undefined) pool.set(node.data, [node]);\n else list.push(node);\n }\n return pool;\n}\n\n/** Turns parts into the nodes the region should hold, reusing its own Text nodes where possible. */\nfunction materialize(region: Region, parts: readonly Part[]): Node[] {\n const only = parts.length === 1 ? parts[0] : undefined;\n if (typeof only === \"string\") {\n const current = region.nodes.length === 1 ? region.nodes[0] : undefined;\n if (current instanceof Text && ownsText(region, current)) {\n if (current.data !== only) current.data = only;\n return [current];\n }\n }\n // Sized to the parts: `[]` and `push` would reserve room for sixteen nodes in every dynamic child (a row has two).\n const nodes: Node[] = new Array<Node>(parts.length);\n let count = 0;\n const seen = new Set<Node>();\n let pool: Map<string, Text[]> | undefined;\n for (const part of parts) {\n if (typeof part === \"string\") {\n pool ??= reusablePool(region);\n const reused = pool.get(part)?.pop();\n let text = reused;\n if (text === undefined) {\n text = documentOf(region.parent).createTextNode(part);\n addText(region, text);\n }\n seen.add(text);\n nodes[count] = text;\n count += 1;\n } else if (!seen.has(part)) {\n seen.add(part);\n nodes[count] = part;\n count += 1;\n }\n }\n nodes.length = count;\n return nodes;\n}\n\n/** The node after the region: its anchor, or the node after its last attached child, or its marker. */\nfunction endOf(region: Region, attached: readonly Node[]): Node | null {\n if (region.anchor !== null) return region.anchor;\n const last = attached.at(-1);\n if (last !== undefined) return last.nextSibling;\n const marker = region.marker;\n if (marker === null) return region.parent.firstChild;\n if (marker.parentNode !== region.parent) return null;\n return marker.nextSibling;\n}\n\n/** Makes the DOM show `next` for this region. */\nfunction reconcileRegion(region: Region, next: Node[]): void {\n const parent = region.parent;\n const attached = region.nodes.filter((node) => node.parentNode === parent);\n const end = endOf(region, attached);\n const first = attached[0];\n if (next.length === 0 && first !== undefined) region.marker = first.previousSibling;\n reconcileNodes(parent, attached, next, end);\n region.nodes = next;\n pruneTexts(region, next);\n}\n\n/** Applies a flattened value to a region. */\nfunction commit(region: Region, parts: readonly Part[]): void {\n if (__DEV__ && region.claimed !== undefined) {\n // Only the first commit of a claimed region is compared; later changes are ordinary updates.\n checkClaimedText(region.claimed, parts);\n region.claimed = undefined;\n }\n reconcileRegion(region, materialize(region, parts));\n}\n\n/**\n * Applies a resolved value to a region. A string or number is the common case (a dynamic text): when the region\n * already shows its own Text node only the data is rewritten, and an empty region gets one new Text node, with none of\n * the flattening and reconciling a general value needs.\n */\nfunction commitValue(region: Region, raw: unknown): void {\n if ((typeof raw === \"string\" || typeof raw === \"number\") && !(__DEV__ && region.claimed)) {\n const nodes = region.nodes;\n const text = typeof raw === \"string\" ? raw : String(raw);\n if (nodes.length === 1) {\n const current = nodes[0];\n if (\n current instanceof Text &&\n current.parentNode === region.parent &&\n ownsText(region, current)\n ) {\n if (current.data !== text) current.data = text;\n return;\n }\n } else if (nodes.length === 0) {\n const created = documentOf(region.parent).createTextNode(text);\n addText(region, created);\n region.parent.insertBefore(created, endOf(region, nodes));\n region.nodes = [created];\n return;\n }\n }\n commit(region, flatten(raw));\n}\n\n/** Nodes of `initial` (already in the parent) that the region adopts as its current content. */\nfunction adoptInitial(parent: Node, initial: unknown): Node[] {\n const adopted: Node[] = [];\n const seen = new Set<Node>();\n for (const part of flatten(initial)) {\n if (typeof part === \"string\" || seen.has(part) || part.parentNode !== parent) continue;\n seen.add(part);\n adopted.push(part);\n }\n return adopted;\n}\n\n/**\n * Creates the state of a region in `parent`. `anchorNode` (null to append) and `initial` (nodes\n * already in the DOM, from hydration or splitText) are both optional.\n * @internal\n */\nexport function createRegion(parent: Node, anchorNode: Node | null, initial: unknown): Region {\n const nodes = initial === undefined ? [] : adoptInitial(parent, initial);\n const marker = nodes.length > 0 ? (nodes[0]?.previousSibling ?? null) : parent.lastChild;\n const region: Region = { parent, anchor: anchorNode, marker, nodes, texts: null };\n for (const node of nodes) if (node instanceof Text) addText(region, node);\n // A region that adopts server nodes during a hydration pass is checked against its first commit.\n if (__DEV__ && initial !== undefined && claims.current.isClaiming()) region.claimed = nodes;\n return region;\n}\n\n/**\n * True when a function appears anywhere in `root`, at any array depth. Scans without calling\n * anything; `seen` stops it from looping on cyclic arrays (flatten reports those).\n */\nfunction containsFunction(root: unknown): boolean {\n if (typeof root === \"function\") return true;\n if (!Array.isArray(root)) return false;\n const stack: unknown[][] = [root];\n const seen = new Set<unknown[]>([root]);\n while (stack.length > 0) {\n const frame = stack.pop() ?? [];\n for (const item of frame) {\n if (typeof item === \"function\") return true;\n if (Array.isArray(item) && !seen.has(item)) {\n seen.add(item);\n stack.push(item);\n }\n }\n }\n return false;\n}\n\n/**\n * One memo per accessor function, owned by `owner` (the effect that evaluates the region's expression,\n * so a new result drops them all; the effect that resolves the result runs many times and must not\n * own them). `prune` disposes the memos of accessors the last\n * run did not meet, which bounds the cache by what the region currently shows.\n */\nfunction createCallCache(owner: ReturnType<typeof currentOwner>): {\n begin(): void;\n call(fn: () => unknown): unknown;\n prune(): void;\n} {\n const memos = new Map<() => unknown, ComputationNode>();\n let touched = new Set<() => unknown>();\n return {\n begin(): void {\n touched = new Set();\n },\n call(fn: () => unknown): unknown {\n touched.add(fn);\n let node = memos.get(fn);\n if (node === undefined) {\n // Component setup runs inside these memos, which may write the state it owns.\n node = createComputation({ kind: \"memo\", fn: () => fn(), allowWrites: true, owner });\n memos.set(fn, node);\n }\n return readComputation(node);\n },\n prune(): void {\n for (const [fn, node] of memos) {\n if (touched.has(fn)) continue;\n memos.delete(fn);\n disposeOwner(node);\n }\n },\n };\n}\n\n/**\n * Keeps a region in sync with `value`. A value that is or contains a function (an accessor, or an\n * array with accessor members) runs inside a render effect, so its reads are tracked. Anything\n * else is inserted once.\n * @internal\n */\nexport function bindRegion(region: Region, value: unknown): unknown {\n if (!containsFunction(value)) {\n commitValue(region, value);\n return value instanceof DocumentFragment ? [...region.nodes] : value;\n }\n let latest: unknown;\n const accessor = typeof value === \"function\" ? (value as () => unknown) : () => value;\n // Every accessor met while resolving the result is evaluated by a memo of its own, kept between\n // runs. An accessor that builds components (`() => show() ? <Late /> : null`) then runs again\n // only when what it reads changes, not whenever something it returned (the component's own\n // accessor, reading its own data) does.\n // Two stages. The outer effect runs the expression and tracks only what the expression itself\n // reads. When the result holds accessors (a component returned one, or `props.children` did),\n // a nested effect resolves them, so a change inside the result re-renders the result but never\n // re-runs the expression: re-running `() => props.children` would build the child components\n // again, discarding their state.\n useRenderEffect(accessor, (raw) => {\n latest = raw;\n if (containsFunction(raw)) {\n const cache = createCallCache(currentOwner());\n useRenderEffect(\n () => {\n cache.begin();\n const parts = flatten(raw, cache.call);\n cache.prune();\n return parts;\n },\n (parts) => {\n commit(region, parts);\n },\n );\n } else {\n commitValue(region, raw);\n }\n });\n return latest;\n}\n\n/**\n * Removes a region's nodes from its parent. Anchors and nodes that were moved elsewhere are not\n * touched.\n * @internal\n */\nexport function removeRegion(region: Region): void {\n for (const node of region.nodes) {\n if (node.parentNode === region.parent) region.parent.removeChild(node);\n }\n region.nodes = [];\n region.texts = null;\n}\n\n/**\n * Creates a text anchor: an empty Text node placed before `before` (appended when null). Use it as\n * the stable insertion point between two dynamic regions; it is never removed by the runtime.\n *\n * @param parent Node that receives the anchor.\n * @param before Node the anchor goes before, or null to append.\n * @returns The new empty Text node.\n * @example\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const slot = anchor(list, null);\n * insert(list, \"first\", slot); // goes before the anchor\n * @see insert\n * @since 1.0.0\n */\nexport function anchor(parent: Node, before: Node | null): Text {\n const text = documentOf(parent).createTextNode(\"\");\n parent.insertBefore(text, before);\n return text;\n}\n\n/**\n * Reactive child insertion: keeps the content of a region in sync with `value`.\n *\n * - A function is an accessor, wrapped in a render effect; it re-runs when its dependencies change.\n * - `null`, `undefined`, booleans render nothing. Strings and numbers become one Text node, reused\n * when the region already holds one. A Node is inserted itself. A DocumentFragment inserts a\n * snapshot of its children. Arrays are flattened, nested arrays included.\n * - Content goes before `anchorNode`, or at the end when it is null or omitted.\n * - Arrays are reconciled in place: nodes that remain are never removed and re-added.\n * - `initial` lists nodes already in the DOM (from hydration or splitText) so nothing is recreated.\n * - During `hydrate()`, a region that adopted server text is compared with its first commit: in\n * development, different text warns `HYDRATION_TEXT_MISMATCH` (on the console and in devtools) and\n * the region shows the value computed by the client.\n *\n * @param parent Node that holds the region.\n * @param value The value or an accessor returning it.\n * @param anchorNode Node the content goes before; null or omitted appends.\n * @param initial Nodes already in place for this region. Undefined adopts the server's nodes while\n * hydrating and starts empty otherwise.\n * @returns The value as accepted (a fragment yields the array of its nodes).\n * @throws TypeError (production message `SHADOW_INSERT_CYCLE`) when an array contains itself, and\n * (`SHADOW_INSERT_DEPTH`) when an accessor returns accessors more than 10,000 levels deep. When the\n * value is reactive, the error is raised inside its render effect and goes to the owner's error\n * handler, like any effect error.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { anchor, insert } from \"@shadow-js/web\";\n *\n * const list = document.createElement(\"ul\");\n * const end = anchor(list, null);\n * const [items] = useSignal([\"a\", \"b\"]);\n * insert(list, () => items().map((name) => document.createTextNode(name)), end);\n * @see anchor\n * @since 1.0.0\n */\nexport function insert(\n parent: Node,\n value: unknown,\n anchorNode?: Node | null,\n initial?: unknown,\n): unknown {\n const resolvedAnchor = anchorNode ?? null;\n const adopted =\n initial === undefined ? claims.current.takeRegion(parent, resolvedAnchor) : initial;\n const region = createRegion(parent, resolvedAnchor, adopted);\n return bindRegion(region, value);\n}\n"],"mappings":"A,sRA0CA,SAASA,EAAW,EAAsB,CACxC,OAAOC,aAAgB,SAAWA,EAAQA,EAAK,eAAiB,QAClE,CAGA,SAASC,EAAS,EAAgB,EAAqB,CACrD,IAAMC,EAAQC,EAAO,MACrB,OAAOD,IAAUF,GAASE,aAAiB,KAAOA,EAAM,IAAIF,CAAY,CAC1E,CAGA,SAASI,EAAQ,EAAgB,EAAkB,CACjD,IAAMF,EAAQC,EAAO,MACjBD,IAAU,KAAM,EAAO,MAAQG,EAC1BH,aAAiB,IAAKA,EAAM,IAAIG,CAAI,EACpCH,IAAUG,IAAM,EAAO,sBAAQ,IAAI,IAAI,CAACH,EAAOG,CAAI,CAAC,EAC/D,CAGA,SAASC,EAAW,EAAgB,EAA6B,CAC/D,IAAMJ,EAAQC,EAAO,MACrB,GAAID,IAAU,KACd,IAAIA,aAAiB,IAAK,CACxB,IAAMK,EAAO,IAAI,IAAUC,CAAI,EAC/B,IAAK,IAAMH,KAAQH,EACZK,EAAK,IAAIF,CAAI,GAAGH,EAAM,OAAOG,CAAI,CAE1C,MAAYG,EAAK,SAASN,CAAK,IAAG,EAAO,MAAQ,KAAA,CACnD,CAMA,SAASO,EAAQ,EAAe,EAAwC,GAAOC,EAAG,EAAW,CAC3F,IAAMC,EAAgB,CAAC,EACjBC,EAAsB,CAAC,CAACC,CAAI,CAAC,EAC7BC,EAAoB,CAAC,CAAC,EACtBC,kBAAS,IAAI,IACnB,KAAOH,EAAO,OAAS,GAAG,CACxB,IAAMI,EAAMJ,EAAO,OAAS,EACtBK,EAAQL,EAAOI,GACfE,EAASJ,EAAQE,IAAQ,EAC/B,GAAIC,IAAU,IAAA,IAAaC,GAAUD,EAAM,OAAQ,C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 @@
1
+ import"@shadow-js/core/extend";let e=null;function t(t,n){e={registry:t,recoverable:n,pending:/* @__PURE__ */ new WeakMap,lifted:[]}}function n(){e=null}function r(){return e!==null}function i(e,t){if(e.nodeType!==8)return!1;let n=e.data;return n===t||t===`[`&&n.startsWith(`[b:`)}function a(e,t,n){let r=[e];for(;r.length>0;){let e=r.pop();if(e===void 0)break;let a=e.firstChild;for(;a!==null;){let o=a.nextSibling;if(i(a,`[`)){let r=[],o=1,s=a.nextSibling;for(;s!==null;){if(i(s,`[`))o+=1;else if(i(s,`]`)&&(--o,o===0))break;r.push(s),s=s.nextSibling}let c=s===null?null:s.nextSibling;n.push(r);for(let t of r)e.removeChild(t);e.removeChild(a),s!==null&&e.removeChild(s);let l=t.get(e);l===void 0?t.set(e,[r]):l.push(r),a=c}else a.nodeType===1&&r.push(a),a=o}}e.normalize()}function o(t){let n=e;if(n===null||t===void 0)return null;let r=n.registry.get(t);return r===void 0?(n.recoverable?.(/* @__PURE__ */ Error(`SHADOW_HYDRATION_KEY_MISS`)),null):(n.registry.delete(t),r.removeAttribute(`data-hk`),a(r,n.pending,n.lifted),r)}function s(t,n){let r=e;if(r===null)return;let i=r.pending.get(t)?.shift();if(i!==void 0){for(let e of i)t.insertBefore(e,n);return i}}function c(){return e?.lifted}function l(t){let n=e;e=null;try{return t()}finally{e=n}}const u=`portal:`,d=`/portal:`;function f(t){let n=e;if(n===null||t===void 0||typeof document>`u`)return;let r=document.body;if(r===null)return;let i=Array.from(r.childNodes),a=i.findIndex(e=>m(e,u+t));if(a===-1)return;let o=i.findIndex((e,n)=>n>a&&m(e,d+t));if(o===-1)return;let s=[];for(let e of i.slice(a+1,o))e.nodeType===8&&h(e)?r.removeChild(e):s.push(e);for(let e of[i[a],i[o]])e!==void 0&&r.removeChild(e);for(let e of s){if(e.nodeType!==1)continue;let t=e,r=t.getAttribute(`data-hk`);r!==null&&n.registry.set(r,t);for(let e of Array.from(t.querySelectorAll(`[data-hk]`))){let t=e.getAttribute(`data-hk`);t!==null&&n.registry.set(t,e)}}return s}function p(e){let t=Array.from(e.childNodes);for(let n=0;n<t.length;n+=1){let r=t[n];if(r===void 0||r.nodeType!==8)continue;let i=r.data;if(!i.startsWith(u))continue;let a=t.findIndex((e,t)=>t>n&&m(e,d+i.slice(7))),o=a===-1?n:a;for(let r of t.slice(n,o+1))r.parentNode===e&&e.removeChild(r);n=o}}function m(e,t){return e.nodeType===8&&e.data===t}function h(e){return e.data===`[`||e.data===`]`}export{t as beginClaiming,o as claimElement,f as claimPortal,n as endClaiming,r as isClaiming,c as liftedRegions,p as releaseUnclaimedPortals,s as takeRegion,l as withoutClaiming};
2
+ //# sourceMappingURL=claim.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claim.js","names":["state","beginClaiming","endClaiming","isClaiming","isMarker","node","text","data","prepare","stack","root","parent","child","following","content","depth","cursor","after","lifted","queue","pending","claimElement","current","key","element","takeRegion","anchorNode","liftedRegions","withoutClaiming","saved","fn","PORTAL_OPEN","PORTAL_CLOSE","claimPortal","body","nodes","open","isComment","close","index","isRegionMarker","own","keyed","hk","releaseUnclaimedPortals","opening","last","comment"],"sources":["../../../src/internal/claim.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n\n/** What a hydration pass in progress knows. Exists only while `hydrate()` runs its synchronous pass. */\ninterface HydrationState {\n /** Server elements by `data-hk` key; entries are consumed when claimed. */\n readonly registry: Map<string, Element>;\n /** Told about each mismatch the pass repaired (the `onRecoverableError` option). */\n readonly recoverable: ((error: unknown) => void) | undefined;\n /** Region contents taken out of each claimed parent, in document order. */\n readonly pending: WeakMap<Node, Node[][]>;\n /** The content of every region lifted out of a claimed element, in document order (read by `NoHydration`). */\n readonly lifted: Node[][];\n}\n\nlet state: HydrationState | null = null;\n\n/** Starts a claiming pass over the given server elements. @internal */\nexport function beginClaiming(\n registry: Map<string, Element>,\n recoverable?: (error: unknown) => void,\n): void {\n state = { registry, recoverable, pending: new WeakMap(), lifted: [] };\n}\n\n/** Ends the claiming pass. @internal */\nexport function endClaiming(): void {\n state = null;\n}\n\n/**\n * Reports whether a `hydrate()` pass is claiming server DOM right now: a custom renderer reads it to\n * decide between adopting server nodes and building fresh ones. The pass is synchronous, so this is\n * `false` again once `hydrate()` returns, and in every later update.\n *\n * @returns `true` during the synchronous pass of `hydrate()` (outside {@link withoutClaiming}),\n * `false` otherwise.\n * @example\n * import { isClaiming } from \"@shadow-js/web/extend\";\n *\n * function describe(): string {\n * return isClaiming() ? \"adopting server markup\" : \"building fresh DOM\";\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function isClaiming(): boolean {\n return state !== null;\n}\n\nfunction isMarker(node: Node, data: string): boolean {\n if (node.nodeType !== 8) return false;\n const text = (node as Comment).data;\n // `[b:ID` opens a Suspense boundary region (streaming); it hydrates like a plain region.\n return text === data || (data === \"[\" && text.startsWith(\"[b:\"));\n}\n\n/**\n * Turns server markup for one template into the shape a freshly cloned template has: region\n * contents are lifted out (to be re-inserted by `insert`), marker comments are removed and text\n * nodes are merged again. Iterative; static elements below the root are walked, regions are not\n * (their contents belong to other templates, claimed later through the registry).\n */\nfunction prepare(root: Element, pending: WeakMap<Node, Node[][]>, lifted: Node[][]): void {\n const stack: Element[] = [root];\n while (stack.length > 0) {\n const parent = stack.pop();\n if (parent === undefined) break;\n let child: ChildNode | null = parent.firstChild;\n while (child !== null) {\n const following: ChildNode | null = child.nextSibling;\n if (isMarker(child, \"[\")) {\n const content: Node[] = [];\n let depth = 1;\n let cursor: ChildNode | null = child.nextSibling;\n while (cursor !== null) {\n if (isMarker(cursor, \"[\")) depth += 1;\n else if (isMarker(cursor, \"]\")) {\n depth -= 1;\n if (depth === 0) break;\n }\n content.push(cursor);\n cursor = cursor.nextSibling;\n }\n const after: ChildNode | null = cursor === null ? null : cursor.nextSibling;\n lifted.push(content);\n for (const node of content) parent.removeChild(node);\n parent.removeChild(child);\n if (cursor !== null) parent.removeChild(cursor);\n const queue = pending.get(parent);\n if (queue === undefined) pending.set(parent, [content]);\n else queue.push(content);\n child = after;\n continue;\n }\n if (child.nodeType === 1) stack.push(child as Element);\n child = following;\n }\n }\n root.normalize();\n}\n\n/**\n * Adopts the server's element for a hydration key while `hydrate()` runs: the step that lets a custom\n * template reuse server markup instead of creating new nodes. The element loses its `data-hk`\n * attribute, and the content of its regions is lifted out, to be adopted by {@link takeRegion} when\n * the regions bind. Prefer `claims.current.claimElement`, which links this code only into apps that\n * call `hydrate()`.\n *\n * @param key The key from `nextKey()`, drawn where the server drew it. Undefined claims nothing.\n * @returns The server element; `null` when no hydration pass is running, when `key` is undefined, or\n * when the server sent no element for the key (the caller then creates the node itself). A missing\n * key is a recoverable mismatch: development builds warn `HYDRATION_KEY_MISS`, and the pass's\n * `onRecoverableError` receives an `Error`.\n * @example\n * import { claimElement, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createPanel(): Element {\n * // During hydrate(): the server's <section>. Otherwise: a new one.\n * return claimElement(nextKey()) ?? document.createElement(\"section\");\n * }\n * @see claims\n * @since 1.0.0\n */\nexport function claimElement(key: string | undefined): Element | null {\n const current = state;\n if (current === null || key === undefined) return null;\n const element = current.registry.get(key);\n if (element === undefined) {\n // Production keeps only the code (the same split as core's messages): the text stays out of the bundle.\n if (__DEV__) {\n const message = `No server element for key \"${key}\".`;\n console.warn(`[shadow HYDRATION_KEY_MISS] ${message}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, message, key, undefined);\n }\n current.recoverable?.(\n new Error(__DEV__ ? `No server element for key \"${key}\".` : \"SHADOW_HYDRATION_KEY_MISS\"),\n );\n return null;\n }\n current.registry.delete(key);\n element.removeAttribute(\"data-hk\");\n prepare(element, current.pending, current.lifted);\n return element;\n}\n\n/** Characters that stay readable as escapes in a diagnostic snippet: markup, quotes and ampersands. */\nconst SNIPPET_ESCAPES: ReadonlyMap<string, string> = new Map([\n [\"<\", \"\\\\u003c\"],\n [\">\", \"\\\\u003e\"],\n [\"&\", \"\\\\u0026\"],\n ['\"', \"\\\\u0022\"],\n [\"'\", \"\\\\u0027\"],\n]);\n\n/**\n * Escapes text for a diagnostic snippet and cuts it to `limit` output characters, with `...` when cut.\n * Escapes are never split, so the output is at most `limit + 3` characters.\n * @internal\n */\nfunction snippet(text: string, limit: number): string {\n let out = \"\";\n for (const char of text) {\n const code = char.codePointAt(0) ?? 0;\n const controlled = code < 0x20 || (code >= 0x7f && code <= 0x9f);\n const escaped =\n SNIPPET_ESCAPES.get(char) ?? (controlled ? `\\\\u${code.toString(16).padStart(4, \"0\")}` : char);\n if (out.length + escaped.length > limit) return `${out}...`;\n out += escaped;\n }\n return out;\n}\n\n/** The opening tag of a server element as the server wrote it (attribute values as they are). */\nfunction openingMarkup(element: Element): string {\n let markup = `<${element.localName}`;\n for (const attr of Array.from(element.attributes)) markup += ` ${attr.name}=\"${attr.value}\"`;\n return `${markup}>`;\n}\n\n/**\n * Development check of a claimed element against the tag its template or `element()` call expects.\n * A different tag warns `HYDRATION_MISMATCH` on the console and in devtools, with an escaped snippet of\n * the server element (its opening tag and the start of its text, bounded). Recovery is unchanged: the\n * element is still adopted, nothing is thrown or replaced, and the caller gets the same value.\n *\n * Call it under `if (__DEV__)`. Text is not compared here: the expected text is inserted later, by\n * `insert`, and {@link checkClaimedText} compares it with the server text at that point.\n *\n * @param element The server element `claimElement` returned.\n * @param expectedTag The tag the client expects (any case).\n * @internal\n */\nexport function checkClaimedTag(element: Element, expectedTag: string): void {\n if (!__DEV__) return;\n const expected = expectedTag.toLowerCase();\n const actual = element.localName.toLowerCase();\n if (actual === expected) return;\n const text = element.textContent ?? \"\";\n let detail = `expected <${expected}> but the server sent <${snippet(actual, 80)}>; server markup: \"${snippet(openingMarkup(element), 80)}\"`;\n if (text !== \"\") detail += `; text: \"${snippet(text, 40)}\"`;\n console.warn(`[shadow HYDRATION_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Development check of the first commit of a region that claimed server text. The server text is the\n * DOM text of the claimed nodes (already decoded, so an escaped `&lt;` compares as `<`); the expected\n * text is the strings of the first commit, joined (a number is already its string, `null` and booleans\n * render nothing, so they expect `\"\"`). Equal text is silent. Different text warns\n * `HYDRATION_TEXT_MISMATCH` on the console and in devtools, with both texts escaped and bounded to 40\n * characters. Recovery is unchanged: the region shows the value the client computed.\n *\n * Not compared, so silent: a region that claimed no nodes (an empty server region has no server text),\n * a region whose server nodes are not all text (an element, or the markers of a nested region), and a\n * commit that holds a node (an element is shown in place of the server's content, as before).\n *\n * Call it under `if (__DEV__)`, once per claimed region, at its first commit.\n *\n * @param claimed The server nodes the region adopted, in document order.\n * @param parts What the first commit shows: strings, or nodes.\n * @internal\n * @since 1.0.0\n */\nexport function checkClaimedText(\n claimed: readonly Node[],\n parts: readonly (Node | string)[],\n): void {\n if (!__DEV__) return;\n if (claimed.length === 0) return;\n let server = \"\";\n for (const node of claimed) {\n if (node.nodeType !== 3) return;\n server += node.textContent ?? \"\";\n }\n let expected = \"\";\n for (const part of parts) {\n if (typeof part !== \"string\") return;\n expected += part;\n }\n if (expected === server) return;\n const detail = `expected text \"${snippet(expected, 40)}\" but the server sent text \"${snippet(server, 40)}\"`;\n console.warn(`[shadow HYDRATION_TEXT_MISMATCH] ${detail}`);\n devtoolsReport(DEVTOOLS_EVENT.HYDRATION_MISMATCH, detail, undefined, undefined);\n}\n\n/**\n * Adopts the server content of the next region of a claimed parent while `hydrate()` runs: the nodes\n * that sat between the region's markers are put back before `anchorNode` and returned, so a custom\n * region can bind to them instead of inserting new nodes. Regions are taken in document order.\n *\n * @param parent An element returned by {@link claimElement} (or one of its descendants).\n * @param anchorNode The node the content goes before; `null` appends it at the end of `parent`.\n * @returns The adopted nodes; undefined when no hydration pass is running or `parent` has no region\n * left to adopt (the caller then inserts fresh nodes).\n * @example\n * import { takeRegion } from \"@shadow-js/web/extend\";\n *\n * function fillRegion(parent: Element): Node[] {\n * const adopted = takeRegion(parent, null);\n * if (adopted !== undefined) return adopted;\n * const text = document.createTextNode(\"fresh\");\n * parent.append(text);\n * return [text];\n * }\n * @see claimElement\n * @since 1.0.0\n */\nexport function takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined {\n const current = state;\n if (current === null) return undefined;\n const content = current.pending.get(parent)?.shift();\n if (content === undefined) return undefined;\n for (const node of content) parent.insertBefore(node, anchorNode);\n return content;\n}\n\n/**\n * The content of every region the pass lifted out of the server elements it claimed, in document order. `NoHydration` finds\n * its own markers in them. Undefined outside a hydration pass.\n * @internal\n */\nexport function liftedRegions(): readonly (readonly Node[])[] | undefined {\n return state?.lifted;\n}\n\n/**\n * Runs `fn` with claiming switched off, so the templates it builds are created fresh instead of\n * claimed from the server markup. Use it for content the server did not render (a portal the server\n * sent nothing for), so its keys are not reported as missing. The previous state is restored when\n * `fn` returns or throws.\n *\n * @param fn The code to run. It runs synchronously, once.\n * @returns What `fn` returns. An error `fn` throws propagates.\n * @example\n * import { template } from \"@shadow-js/web\";\n * import { withoutClaiming } from \"@shadow-js/web/extend\";\n *\n * const makeTip = template(`<div class=\"tip\"></div>`);\n * const tip = withoutClaiming(() => makeTip()); // a fresh clone, even during hydrate()\n * @see claims\n * @since 1.0.0\n */\nexport function withoutClaiming<T>(fn: () => T): T {\n const saved = state;\n state = null;\n try {\n return fn();\n } finally {\n state = saved;\n }\n}\n\n/** Comment that opens the server block of a portal (`<!--portal:KEY-->`). */\nconst PORTAL_OPEN = \"portal:\";\n/** Comment that closes it (`<!--/portal:KEY-->`). */\nconst PORTAL_CLOSE = \"/portal:\";\n\n/**\n * Adopts the server block of a portal while `hydrate()` runs. The server writes each portal's markup\n * at the end of `<body>` between `<!--portal:KEY-->` and `<!--/portal:KEY-->` comments (see\n * `createServerPortals`); this removes the comments, leaves the content in place, and registers its\n * keyed elements so the portal's templates claim them.\n *\n * @param key The portal's key from `nextKey()`. Undefined claims nothing.\n * @returns The nodes of the block, in place in the body; undefined when no hydration pass is running,\n * `key` is undefined, there is no document body, or the server sent no complete block for the key.\n * @example\n * import { claimPortal, nextKey } from \"@shadow-js/web/extend\";\n *\n * function mountOverlay(build: () => Node): Node[] {\n * const adopted = claimPortal(nextKey());\n * if (adopted !== undefined) return adopted;\n * const node = build();\n * document.body.append(node);\n * return [node];\n * }\n * @since 1.0.0\n */\nexport function claimPortal(key: string | undefined): Node[] | undefined {\n const current = state;\n if (current === null || key === undefined || typeof document === \"undefined\") return undefined;\n const body = document.body;\n if (body === null) return undefined;\n const nodes = Array.from(body.childNodes);\n const open = nodes.findIndex((node) => isComment(node, PORTAL_OPEN + key));\n if (open === -1) return undefined;\n const close = nodes.findIndex(\n (node, index) => index > open && isComment(node, PORTAL_CLOSE + key),\n );\n if (close === -1) return undefined;\n // The content stays where the server put it (the region adopts it in place); only the markers go.\n const content: Node[] = [];\n for (const node of nodes.slice(open + 1, close)) {\n if (node.nodeType === 8 && isRegionMarker(node as Comment)) body.removeChild(node);\n else content.push(node);\n }\n for (const node of [nodes[open], nodes[close]]) {\n if (node !== undefined) body.removeChild(node);\n }\n for (const node of content) {\n if (node.nodeType !== 1) continue;\n const element = node as Element;\n const own = element.getAttribute(\"data-hk\");\n if (own !== null) current.registry.set(own, element);\n for (const keyed of Array.from(element.querySelectorAll(\"[data-hk]\"))) {\n const hk = keyed.getAttribute(\"data-hk\");\n if (hk !== null) current.registry.set(hk, keyed);\n }\n }\n return content;\n}\n\n/**\n * Removes the server blocks of portals that were not claimed during the pass: the client did not render\n * those portals, so their markup must not stay in the page. Each block goes with its comments. A block\n * without its closing comment loses only its opening one.\n * @internal\n */\nexport function releaseUnclaimedPortals(body: Node): void {\n const nodes = Array.from(body.childNodes);\n for (let open = 0; open < nodes.length; open += 1) {\n const opening = nodes[open];\n if (opening === undefined || opening.nodeType !== 8) continue;\n const data = (opening as Comment).data;\n if (!data.startsWith(PORTAL_OPEN)) continue;\n const close = nodes.findIndex(\n (node, index) =>\n index > open && isComment(node, PORTAL_CLOSE + data.slice(PORTAL_OPEN.length)),\n );\n const last = close === -1 ? open : close;\n for (const node of nodes.slice(open, last + 1)) {\n if (node.parentNode === body) body.removeChild(node);\n }\n open = last;\n }\n}\n\nfunction isComment(node: Node, data: string): boolean {\n return node.nodeType === 8 && (node as Comment).data === data;\n}\n\nfunction isRegionMarker(comment: Comment): boolean {\n return comment.data === \"[\" || comment.data === \"]\";\n}\n"],"mappings":"A,+BAcA,IAAIA,EAA+B,KAGnC,SAAgBC,EACd,EACA,EACM,CACN,EAAQ,CAAE,WAAU,cAAa,wBAAS,IAAI,QAAW,OAAQ,CAAC,CAAE,CACtE,CAGA,SAAgBC,GAAoB,CAClC,EAAQ,IACV,CAkBA,SAAgBC,GAAsB,CACpC,OAAOH,IAAU,IACnB,CAEA,SAASI,EAAS,EAAY,EAAuB,CACnD,GAAIC,EAAK,WAAa,EAAG,MAAO,GAChC,IAAMC,EAAQD,EAAiB,KAE/B,OAAOC,IAASC,GAASA,IAAS,KAAOD,EAAK,WAAW,KAAK,CAChE,CAQA,SAASE,EAAQ,EAAe,EAAkC,EAAwB,CACxF,IAAMC,EAAmB,CAACC,CAAI,EAC9B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAASF,EAAM,IAAI,EACzB,GAAIE,IAAW,IAAA,GAAW,MAC1B,IAAIC,EAA0BD,EAAO,WACrC,KAAOC,IAAU,MAAM,CACrB,IAAMC,EAA8BD,EAAM,YAC1C,GAAIR,EAASQ,EAAO,GAAG,EAAG,CACxB,IAAME,EAAkB,CAAC,EACrBC,EAAQ,EACRC,EAA2BJ,EAAM,YACrC,KAAOI,IAAW,MAAM,CACtB,GAAIZ,EAASY,EAAQ,GAAG,EAAG,GAAS,OAC/B,GAAIZ,EAASY,EAAQ,GAAG,IAC3B,IACID,IAAU,GAAG,MAEnBD,EAAQ,KAAKE,CAAM,EACnB,EAASA,EAAO,WAClB,CACA,IAAMC,EAA0BD,IAAW,KAAO,KAAOA,EAAO,YAChEE,EAAO,KAAKJ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AAUV,EAAMC,GACtB,GAAIS,IAAY,IAAA,IAAaA,EAAQ,WAAa,EAAG,SACrD,IAAMtC,EAAQsC,EAAoB,KAClC,GAAI,CAACtC,EAAK,WAAWwB,CAAW,EAAG,SACnC,IAAMO,EAAQH,EAAM,WACjB,EAAM,IACLI,EAAQH,GAAQC,EAAUhC,EAAM2B,EAAezB,EAAK,MAAM,CAAkB,CAAC,CACjF,EACMuC,EAAOR,IAAU,GAAKF,EAAOE,EACnC,IAAK,IAAMjC,KAAQ8B,EAAM,MAAMC,EAAMU,EAAO,CAAC,EACvCzC,EAAK,aAAe6B,GAAMA,EAAK,YAAY7B,CAAI,EAErD,EAAOyC,CACT,CACF,CAEA,SAAST,EAAU,EAAY,EAAuB,CACpD,OAAOhC,EAAK,WAAa,GAAMA,EAAiB,OAASE,CAC3D,CAEA,SAASiC,EAAe,EAA2B,CACjD,OAAOO,EAAQ,OAAS,KAAOA,EAAQ,OAAS,GAClD,C"}
@@ -0,0 +1,2 @@
1
+ const e=new Set(`animation-iteration-count aspect-ratio border-image-outset border-image-slice border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit stroke-opacity stroke-width`.split(` `));function t(t,n){if(typeof n!=`number`||n===0||t.startsWith(`--`))return String(n);let r=t.replace(/^-(?:webkit|moz|ms|o)-/,``);return e.has(r)?String(n):`${n}px`}export{t as cssValueText};
2
+ //# sourceMappingURL=css-units.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"css-units.js","names":["UNITLESS","cssValueText","value","property","bare"],"sources":["../../../src/internal/css-units.ts"],"sourcesContent":["/**\n * React's unitless style properties. A number given to any other property is in pixels (`0` stays\n * `0`); these properties take the bare number. Vendor prefixes do not change the answer.\n *\n * The compiler never needs this table for static values, and `class-style.ts` and the server\n * stylesheet writer are the only importers, so it is linked only where a style is written.\n * @internal\n */\nconst UNITLESS: ReadonlySet<string> = new Set(\n (\n \"animation-iteration-count aspect-ratio border-image-outset border-image-slice \" +\n \"border-image-width box-flex box-flex-group box-ordinal-group column-count columns flex \" +\n \"flex-grow flex-positive flex-shrink flex-negative flex-order grid-area grid-row grid-row-end \" +\n \"grid-row-span grid-row-start grid-column grid-column-end grid-column-span grid-column-start \" +\n \"font-weight line-clamp line-height opacity order orphans scale tab-size widows z-index zoom \" +\n \"fill-opacity flood-opacity stop-opacity stroke-dasharray stroke-dashoffset stroke-miterlimit \" +\n \"stroke-opacity stroke-width\"\n ).split(\" \"),\n);\n\n/**\n * The CSS text of one style value. A finite or non-finite number gets `px` unless it is zero, a\n * custom property (`--x`) or unitless; every other value is `String(value)`.\n * @param property The CSS property in kebab-case (`toCssProperty` output).\n * @param value The style value.\n * @internal\n */\nexport function cssValueText(property: string, value: unknown): string {\n if (typeof value !== \"number\" || value === 0 || property.startsWith(\"--\")) return String(value);\n const bare = property.replace(/^-(?:webkit|moz|ms|o)-/, \"\");\n return UNITLESS.has(bare) ? String(value) : `${value}px`;\n}\n"],"mappings":"AAQA,MAAMA,EAAgC,IAAI,IAEtC,qjBAOA,MAAM,GAAG,CACb,EASA,SAAgBC,EAAa,EAAkB,EAAwB,CACrE,GAAI,OAAOC,GAAU,UAAYA,IAAU,GAAKC,EAAS,WAAW,IAAI,EAAG,OAAO,OAAOD,CAAK,EAC9F,IAAME,EAAOD,EAAS,QAAQ,yBAA0B,EAAE,EAC1D,OAAOH,EAAS,IAAII,CAAI,EAAI,OAAOF,CAAK,EAAI,GAAGA,EAAM,GACvD,C"}
@@ -0,0 +1,2 @@
1
+ function e(e,t){}function t(e){return/* @__PURE__ */ TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: "${e}"`)}export{t as invalidAttributeName,e as warnOnce};
2
+ //# sourceMappingURL=diagnostics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diagnostics.js","names":["warnOnce","invalidAttributeName","name"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["/**\n * The diagnostic codes of the DOM runtime: `UNSAFE_URL_BLOCKED` (a URL attribute that would run\n * script was not written), `INVALID_ATTRIBUTE_NAME` (a name that cannot appear in markup) and\n * `DUPLICATE_CLASS_ATTRIBUTE` (one element carries `class` and `className`, so the parser drops one).\n * @since 1.0.0\n */\nexport type WebWarningCode =\n | \"UNSAFE_URL_BLOCKED\"\n | \"INVALID_ATTRIBUTE_NAME\"\n | \"DUPLICATE_CLASS_ATTRIBUTE\";\n\nconst seen = new Set<WebWarningCode>();\n\n/**\n * Prints a development warning as `[shadow CODE] detail`, at most once per code for the life of the\n * page or process (the same pattern as core's `warn`): for a custom renderer that refuses a value the\n * way the built-in ones do. Production builds print nothing.\n *\n * @param code The diagnostic code. A code that was already reported is ignored, whatever the detail.\n * @param detail The text after the code.\n * @example\n * import { isUnsafeUrlAttribute, warnOnce } from \"@shadow-js/web/extend\";\n *\n * function setLink(el: Element, url: string): void {\n * if (isUnsafeUrlAttribute(\"href\", url)) {\n * warnOnce(\"UNSAFE_URL_BLOCKED\", `Blocked a script URL: ${url}`);\n * return;\n * }\n * el.setAttribute(\"href\", url);\n * }\n * @since 1.0.0\n */\nexport function warnOnce(code: WebWarningCode, detail: string): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n console.warn(`[shadow ${code}] ${detail}`);\n}\n\n/** Forgets which codes were already reported. Used by tests; not part of the public surface. @internal */\nexport function resetWebWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Error thrown for attribute names that cannot appear in markup. Dev builds carry the full text;\n * production keeps the code and the name (the same split as core's messages).\n * @internal\n */\nexport function invalidAttributeName(name: string): TypeError {\n if (!__DEV__) return new TypeError(`SHADOW_INVALID_ATTRIBUTE_NAME: \"${name}\"`);\n return new TypeError(`[shadow INVALID_ATTRIBUTE_NAME] \"${name}\" is not a valid attribute name.`);\n}\n"],"mappings":"AAgCA,SAAgBA,EAAS,EAAsB,EAAsB,CAKrE,CAYA,SAAgBC,EAAqB,EAAyB,CAC9C,MAAO,gBAAI,UAAU,mCAAmCC,EAAK,EAAE,CAE/E,C"}
@@ -0,0 +1,2 @@
1
+ const e=[`click`,`input`],t=`__SHADOWJS_EARLY__`,n=/^[a-z]+$/;function r(e){return`(function(){var d=document,n=`+JSON.stringify(e.filter(e=>n.test(e)))+`,q=[];function c(e){q.push(e)}for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);window.${t}={queue:q,names:n,listener:c};})();`}function i(){let e=Reflect.get(globalThis,t);if(typeof e!=`object`||!e)return;let n=Reflect.get(e,`queue`),r=Reflect.get(e,`names`),i=Reflect.get(e,`listener`);if(Array.isArray(n)&&Array.isArray(r)&&typeof i==`function`)return{queue:n.filter(e=>e instanceof Event),names:r.filter(e=>typeof e==`string`),listener:i}}function a(e){let t={bubbles:!0,cancelable:e.cancelable,composed:!0};return e instanceof MouseEvent?new MouseEvent(e.type,{...t,clientX:e.clientX,clientY:e.clientY,button:e.button,buttons:e.buttons,altKey:e.altKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey,shiftKey:e.shiftKey}):new Event(e.type,t)}function o(){let e=i();if(e!==void 0){Reflect.deleteProperty(globalThis,t);for(let t of e.names)document.removeEventListener(t,e.listener,!0);for(let t of e.queue){let e=t.target;e instanceof Node&&e.dispatchEvent(a(t))}}}export{e as DEFAULT_EARLY_EVENTS,t as EARLY_CAPTURE_KEY,r as captureScriptBody,o as replayEarlyEvents};
2
+ //# sourceMappingURL=early-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"early-events.js","names":["DEFAULT_EARLY_EVENTS","EARLY_CAPTURE_KEY","EVENT_NAME","captureScriptBody","names","name","readCapture","value","queue","listener","item","reissue","init","event","replayEarlyEvents","capture","target"],"sources":["../../../src/internal/early-events.ts"],"sourcesContent":["/**\n * Early event capture (ADR-016): a tiny inline script, placed before the bundle, records the events a\n * user makes before the application has hydrated. `hydrate()` then replays them once its handlers are\n * attached, so a click made while the page was still loading is not lost. The script is generated by\n * `generateHydrationScript` on the server; the replay is the client half, and it does nothing when the\n * page has no captured events.\n */\n\n/** The event types recorded when a page does not name its own. @internal */\nexport const DEFAULT_EARLY_EVENTS: readonly string[] = [\"click\", \"input\"];\n\n/** The window property the capture script writes. Its shape is checked before use. @internal */\nexport const EARLY_CAPTURE_KEY = \"__SHADOWJS_EARLY__\";\n\n/** Event names are plain lower-case words: anything else would end up inside the script text. */\nconst EVENT_NAME = /^[a-z]+$/;\n\n/**\n * The inline script body. A capture listener on the document (capture phase, so it sees events even\n * when a page stops their propagation) queues each event; the queue and the listener are kept on\n * `window` for the replay.\n * @internal\n */\nexport function captureScriptBody(names: readonly string[]): string {\n const list = JSON.stringify(names.filter((name) => EVENT_NAME.test(name)));\n return (\n \"(function(){var d=document,n=\" +\n list +\n \",q=[];function c(e){q.push(e)}\" +\n \"for(var i=0;i<n.length;i++)d.addEventListener(n[i],c,true);\" +\n `window.${EARLY_CAPTURE_KEY}={queue:q,names:n,listener:c};})();`\n );\n}\n\ninterface Capture {\n readonly queue: Event[];\n readonly names: string[];\n readonly listener: (event: Event) => void;\n}\n\n/** The capture the script left on the window, validated, or undefined. */\nfunction readCapture(): Capture | undefined {\n const value: unknown = Reflect.get(globalThis, EARLY_CAPTURE_KEY);\n if (typeof value !== \"object\" || value === null) return undefined;\n const queue: unknown = Reflect.get(value, \"queue\");\n const names: unknown = Reflect.get(value, \"names\");\n const listener: unknown = Reflect.get(value, \"listener\");\n if (!Array.isArray(queue) || !Array.isArray(names) || typeof listener !== \"function\") {\n return undefined;\n }\n const events = queue.filter((item): item is Event => item instanceof Event);\n const kinds = names.filter((name): name is string => typeof name === \"string\");\n return { queue: events, names: kinds, listener: listener as (event: Event) => void };\n}\n\n/** A new event of the same type that bubbles like the original and carries its pointer position. */\nfunction reissue(event: Event): Event {\n const init: EventInit = { bubbles: true, cancelable: event.cancelable, composed: true };\n if (event instanceof MouseEvent) {\n return new MouseEvent(event.type, {\n ...init,\n clientX: event.clientX,\n clientY: event.clientY,\n button: event.button,\n buttons: event.buttons,\n altKey: event.altKey,\n ctrlKey: event.ctrlKey,\n metaKey: event.metaKey,\n shiftKey: event.shiftKey,\n });\n }\n return new Event(event.type, init);\n}\n\n/**\n * Stops the capture and replays what it recorded, in order, on the elements they were made on. Called\n * by `hydrate()` after the handlers are attached. Does nothing when no capture ran.\n * @internal\n */\nexport function replayEarlyEvents(): void {\n const capture = readCapture();\n if (capture === undefined) return;\n Reflect.deleteProperty(globalThis, EARLY_CAPTURE_KEY);\n for (const name of capture.names) document.removeEventListener(name, capture.listener, true);\n for (const event of capture.queue) {\n const target = event.target;\n if (target instanceof Node) target.dispatchEvent(reissue(event));\n }\n}\n"],"mappings":"AASA,MAAaA,EAA0C,CAAC,QAAS,OAAO,EAG3DC,EAAoB,qBAG3BC,EAAa,WAQnB,SAAgBC,EAAkB,EAAkC,CAElE,MACE,gCAFW,KAAK,UAAUC,EAAM,OAAQ,GAASF,EAAW,KAAKG,CAAI,CAAC,CAGnE,EACH,mGAEUJ,EAAkB,oCAEhC,CASA,SAASK,GAAmC,CAC1C,IAAMC,EAAiB,QAAQ,IAAI,WAAYN,CAAiB,EAChE,GAAI,OAAOM,GAAU,WAAYA,EAAgB,OACjD,IAAMC,EAAiB,QAAQ,IAAID,EAAO,OAAO,EAC3CH,EAAiB,QAAQ,IAAIG,EAAO,OAAO,EAC3CE,EAAoB,QAAQ,IAAIF,EAAO,UAAU,EACvD,GAAK,MAAM,QAAQC,CAAK,GAAM,MAAM,QAAQJ,CAAK,GAAK,OAAOK,GAAa,WAK1E,MAAO,CAAE,MAFMD,EAAM,OAAQ,GAAwBE,aAAgB,KAEhD,EAAG,MADVN,EAAM,OAAQ,GAAyB,OAAOC,GAAS,QAClC,EAAa,UAAmC,CACrF,CAGA,SAASM,EAAQ,EAAqB,CACpC,IAAMC,EAAkB,CAAE,QAAS,GAAM,WAAYC,EAAM,WAAY,SAAU,EAAK,EActF,OAbIA,aAAiB,WACZ,IAAI,WAAWA,EAAM,KAAM,CAChC,GAAGD,EACH,QAASC,EAAM,QACf,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,OAAQA,EAAM,OACd,QAASA,EAAM,QACf,QAASA,EAAM,QACf,SAAUA,EAAM,QAClB,CAAC,EAEI,IAAI,MAAMA,EAAM,KAAMD,CAAI,CACnC,CAOA,SAAgBE,GAA0B,CACxC,IAAMC,EAAUT,EAAY,EAC5B,GAAIS,IAAY,IAAA,GAChB,SAAQ,eAAe,WAAYd,CAAiB,EACpD,IAAK,IAAMI,KAAQU,EAAQ,MAAO,SAAS,oBAAoBV,EAAMU,EAAQ,SAAU,EAAI,EAC3F,IAAK,IAAMF,KAASE,EAAQ,MAAO,CACjC,IAAMC,EAASH,EAAM,OACjBG,aAAkB,MAAMA,EAAO,cAAcL,EAAQE,CAAK,CAAC,CACjE,CALoD,CAMtD,C"}
@@ -0,0 +1,2 @@
1
+ const e={current:{claimElement:()=>null,takeRegion:()=>void 0,liftedRegions:()=>void 0,claimPortal:()=>void 0,isClaiming:()=>!1,withoutClaiming:e=>e()}};export{e as claims};
2
+ //# sourceMappingURL=hydration-hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-hooks.js","names":["claims","fn"],"sources":["../../../src/internal/hydration-hooks.ts"],"sourcesContent":["/**\n * The claiming half of hydration, as a hook. `hydrate()` installs the real implementation for the\n * length of its pass; outside a pass the hooks are idle: nothing is claimed, and the renderer builds\n * the same DOM it builds on a fresh page. Templates, regions, `Dynamic`, `Portal` and `NoHydration`\n * call through {@link claims}, so only code that reaches `hydrate()` carries the claiming code (the\n * registry, the server-block lifting and the portal scan). A custom renderer reads the same hook.\n * @since 1.0.0\n */\nexport interface Claims {\n /** Claims the server element for `key` (see `claimElement`). */\n claimElement(key: string | undefined): Element | null;\n /** Adopts the next server region of `parent` (see `takeRegion`). */\n takeRegion(parent: Node, anchorNode: Node | null): Node[] | undefined;\n /** The content of every region lifted out of a claimed element (see `liftedRegions`). */\n liftedRegions(): readonly (readonly Node[])[] | undefined;\n /** Adopts the server block of a portal (see `claimPortal`). */\n claimPortal(key: string | undefined): Node[] | undefined;\n /** True while a hydration pass claims server DOM (see `isClaiming`). */\n isClaiming(): boolean;\n /** Runs `fn` with claiming off (see `withoutClaiming`). */\n withoutClaiming<T>(fn: () => T): T;\n}\n\nconst idle: Claims = {\n claimElement: () => null,\n takeRegion: () => undefined,\n liftedRegions: () => undefined,\n claimPortal: () => undefined,\n isClaiming: () => false,\n withoutClaiming: (fn) => fn(),\n};\n\n/**\n * The claims in effect. Read at each call (never captured), so a region that is updated after its\n * hydration pass ended builds fresh DOM. Only `hydrate()` replaces it, and restores it in `finally`.\n * Outside a hydration pass every method is a no-op.\n *\n * @example\n * import { claims, nextKey } from \"@shadow-js/web/extend\";\n *\n * function createCard(): Element {\n * // Adopts the server's element during hydrate(); builds a new one otherwise.\n * return claims.current.claimElement(nextKey()) ?? document.createElement(\"article\");\n * }\n * @see Claims\n * @since 1.0.0\n */\nexport const claims: { current: Claims } = { current: idle };\n"],"mappings":"AA+CA,MAAaA,EAA8B,CAAE,QAAS,CAvBpD,iBAAoB,KACpB,eAAkB,IAAA,GAClB,kBAAqB,IAAA,GACrB,gBAAmB,IAAA,GACnB,eAAkB,GAClB,gBAAkB,GAAOC,EAAG,CAkBwB,CAAK,E"}
@@ -0,0 +1,2 @@
1
+ let e=null;function t(e=`0`){return{id:`${e}-`,count:0,resources:0}}function n(){return e}function r(t,n){let r=e;e=t;try{return n()}finally{e=r}}function i(t){let n=e;return n===null?t():r({id:`${n.id}${n.count++}-`,count:0,resources:0},t)}function a(){let t=e;if(t!==null)return`${t.id}${t.count++}`}function o(t){if(t!==void 0)return`k:${t}`;let n=e;return n===null?`r`:`${n.id}r${n.resources++}`}function s(e){return e===void 0?null:{id:`${e}-`,count:0,resources:0}}export{s as childScope,t as createRootScope,n as currentScope,i as enterComponent,a as nextKey,o as resourceKey,r as withScope};
2
+ //# sourceMappingURL=hydration-scope.js.map