@shadow-js/web 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (281) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/dev/attributes.d.ts +10 -3
  3. package/dist/dev/attributes.js +27 -49
  4. package/dist/dev/attributes.js.map +1 -1
  5. package/dist/dev/class-style.d.ts +15 -6
  6. package/dist/dev/class-style.js +64 -47
  7. package/dist/dev/class-style.js.map +1 -1
  8. package/dist/dev/control-flow/dynamic.d.ts +11 -2
  9. package/dist/dev/control-flow/dynamic.js +57 -40
  10. package/dist/dev/control-flow/dynamic.js.map +1 -1
  11. package/dist/dev/control-flow/error-boundary.js +2 -2
  12. package/dist/dev/control-flow/error-boundary.js.map +1 -1
  13. package/dist/dev/control-flow/portal.d.ts +2 -2
  14. package/dist/dev/control-flow/portal.js +17 -13
  15. package/dist/dev/control-flow/portal.js.map +1 -1
  16. package/dist/dev/control-flow/suspense-list.js +2 -2
  17. package/dist/dev/control-flow/suspense-list.js.map +1 -1
  18. package/dist/dev/control-flow/suspense.js +2 -2
  19. package/dist/dev/control-flow/suspense.js.map +1 -1
  20. package/dist/dev/element.js +6 -3
  21. package/dist/dev/element.js.map +1 -1
  22. package/dist/dev/events.js +15 -44
  23. package/dist/dev/events.js.map +1 -1
  24. package/dist/dev/extend.d.ts +2 -2
  25. package/dist/dev/extend.js +2 -2
  26. package/dist/dev/insert.d.ts +26 -5
  27. package/dist/dev/insert.js +84 -45
  28. package/dist/dev/insert.js.map +1 -1
  29. package/dist/dev/internal/accessor.js +56 -0
  30. package/dist/dev/internal/accessor.js.map +1 -0
  31. package/dist/dev/internal/claim.d.ts +2 -1
  32. package/dist/dev/internal/claim.js +18 -3
  33. package/dist/dev/internal/claim.js.map +1 -1
  34. package/dist/dev/internal/css-units.js +2 -2
  35. package/dist/dev/internal/css-units.js.map +1 -1
  36. package/dist/dev/internal/diagnostics.d.ts +7 -3
  37. package/dist/dev/internal/diagnostics.js +14 -4
  38. package/dist/dev/internal/diagnostics.js.map +1 -1
  39. package/dist/dev/internal/early-events.js +20 -2
  40. package/dist/dev/internal/early-events.js.map +1 -1
  41. package/dist/dev/internal/portal-context.d.ts +9 -0
  42. package/dist/dev/internal/portal-context.js.map +1 -1
  43. package/dist/dev/internal/react-names.js +45 -71
  44. package/dist/dev/internal/react-names.js.map +1 -1
  45. package/dist/dev/internal/reconcile.js +7 -12
  46. package/dist/dev/internal/reconcile.js.map +1 -1
  47. package/dist/dev/jsx/global.d.ts +5 -2
  48. package/dist/dev/jsx/html.d.ts +1 -0
  49. package/dist/dev/resource-hints.js +4 -2
  50. package/dist/dev/resource-hints.js.map +1 -1
  51. package/dist/dev/select-value.js +5 -15
  52. package/dist/dev/select-value.js.map +1 -1
  53. package/dist/dev/server/attributes.d.ts +3 -0
  54. package/dist/dev/server/attributes.js +6 -32
  55. package/dist/dev/server/attributes.js.map +1 -1
  56. package/dist/dev/server/element.js +10 -7
  57. package/dist/dev/server/element.js.map +1 -1
  58. package/dist/dev/server/errors.js +7 -1
  59. package/dist/dev/server/errors.js.map +1 -1
  60. package/dist/dev/server/escape.js +14 -6
  61. package/dist/dev/server/escape.js.map +1 -1
  62. package/dist/dev/server/form-controls.js +5 -2
  63. package/dist/dev/server/form-controls.js.map +1 -1
  64. package/dist/dev/server/index.d.ts +2 -1
  65. package/dist/dev/server/index.js +3 -2
  66. package/dist/dev/server/portals.js +3 -0
  67. package/dist/dev/server/portals.js.map +1 -1
  68. package/dist/dev/server/raw-text.d.ts +28 -0
  69. package/dist/dev/server/raw-text.js +66 -0
  70. package/dist/dev/server/raw-text.js.map +1 -0
  71. package/dist/dev/server/render.d.ts +2 -1
  72. package/dist/dev/server/render.js +3 -3
  73. package/dist/dev/server/render.js.map +1 -1
  74. package/dist/dev/server/stream.d.ts +1 -1
  75. package/dist/dev/server/stream.js +3 -3
  76. package/dist/dev/server/stream.js.map +1 -1
  77. package/dist/dev/server.d.ts +2 -1
  78. package/dist/dev/server.js +3 -2
  79. package/dist/dev/spread.js +56 -81
  80. package/dist/dev/spread.js.map +1 -1
  81. package/dist/dev/template.js +1 -3
  82. package/dist/dev/template.js.map +1 -1
  83. package/dist/dev/view-transition.js +12 -4
  84. package/dist/dev/view-transition.js.map +1 -1
  85. package/dist/prod/attributes.js +1 -1
  86. package/dist/prod/attributes.js.map +1 -1
  87. package/dist/prod/class-style.js +1 -1
  88. package/dist/prod/class-style.js.map +1 -1
  89. package/dist/prod/control-flow/dynamic.js +1 -1
  90. package/dist/prod/control-flow/dynamic.js.map +1 -1
  91. package/dist/prod/control-flow/error-boundary.js +1 -1
  92. package/dist/prod/control-flow/error-boundary.js.map +1 -1
  93. package/dist/prod/control-flow/portal.js +1 -1
  94. package/dist/prod/control-flow/portal.js.map +1 -1
  95. package/dist/prod/control-flow/suspense-list.js +1 -1
  96. package/dist/prod/control-flow/suspense-list.js.map +1 -1
  97. package/dist/prod/control-flow/suspense.js +1 -1
  98. package/dist/prod/control-flow/suspense.js.map +1 -1
  99. package/dist/prod/element.js +1 -1
  100. package/dist/prod/element.js.map +1 -1
  101. package/dist/prod/events.js +1 -1
  102. package/dist/prod/events.js.map +1 -1
  103. package/dist/prod/extend.js +1 -1
  104. package/dist/prod/insert.js +1 -1
  105. package/dist/prod/insert.js.map +1 -1
  106. package/dist/prod/internal/accessor.js +2 -0
  107. package/dist/prod/internal/accessor.js.map +1 -0
  108. package/dist/prod/internal/claim.js +1 -1
  109. package/dist/prod/internal/claim.js.map +1 -1
  110. package/dist/prod/internal/css-units.js +1 -1
  111. package/dist/prod/internal/css-units.js.map +1 -1
  112. package/dist/prod/internal/diagnostics.js +1 -1
  113. package/dist/prod/internal/diagnostics.js.map +1 -1
  114. package/dist/prod/internal/early-events.js +1 -1
  115. package/dist/prod/internal/early-events.js.map +1 -1
  116. package/dist/prod/internal/portal-context.js.map +1 -1
  117. package/dist/prod/internal/react-names.js +1 -1
  118. package/dist/prod/internal/react-names.js.map +1 -1
  119. package/dist/prod/internal/reconcile.js +1 -1
  120. package/dist/prod/internal/reconcile.js.map +1 -1
  121. package/dist/prod/resource-hints.js +1 -1
  122. package/dist/prod/resource-hints.js.map +1 -1
  123. package/dist/prod/select-value.js +1 -1
  124. package/dist/prod/select-value.js.map +1 -1
  125. package/dist/prod/server/attributes.js +1 -1
  126. package/dist/prod/server/attributes.js.map +1 -1
  127. package/dist/prod/server/element.js +1 -1
  128. package/dist/prod/server/element.js.map +1 -1
  129. package/dist/prod/server/errors.js +1 -1
  130. package/dist/prod/server/errors.js.map +1 -1
  131. package/dist/prod/server/escape.js +1 -1
  132. package/dist/prod/server/escape.js.map +1 -1
  133. package/dist/prod/server/form-controls.js +2 -2
  134. package/dist/prod/server/form-controls.js.map +1 -1
  135. package/dist/prod/server/index.js +1 -1
  136. package/dist/prod/server/portals.js +1 -1
  137. package/dist/prod/server/portals.js.map +1 -1
  138. package/dist/prod/server/raw-text.js +2 -0
  139. package/dist/prod/server/raw-text.js.map +1 -0
  140. package/dist/prod/server/render.js +1 -1
  141. package/dist/prod/server/render.js.map +1 -1
  142. package/dist/prod/server/stream.js +1 -1
  143. package/dist/prod/server/stream.js.map +1 -1
  144. package/dist/prod/server.js +1 -1
  145. package/dist/prod/spread.js +1 -1
  146. package/dist/prod/spread.js.map +1 -1
  147. package/dist/prod/template.js +1 -1
  148. package/dist/prod/template.js.map +1 -1
  149. package/dist/prod/view-transition.js +1 -1
  150. package/dist/prod/view-transition.js.map +1 -1
  151. package/dist/server/attributes.js +1 -1
  152. package/dist/server/attributes.js.map +1 -1
  153. package/dist/server/class-style.js +1 -1
  154. package/dist/server/class-style.js.map +1 -1
  155. package/dist/server/control-flow/dynamic.js +1 -1
  156. package/dist/server/control-flow/dynamic.js.map +1 -1
  157. package/dist/server/control-flow/error-boundary.js +1 -1
  158. package/dist/server/control-flow/error-boundary.js.map +1 -1
  159. package/dist/server/control-flow/portal.js +1 -1
  160. package/dist/server/control-flow/portal.js.map +1 -1
  161. package/dist/server/control-flow/suspense-list.js +1 -1
  162. package/dist/server/control-flow/suspense-list.js.map +1 -1
  163. package/dist/server/control-flow/suspense.js +1 -1
  164. package/dist/server/control-flow/suspense.js.map +1 -1
  165. package/dist/server/element.js +1 -1
  166. package/dist/server/element.js.map +1 -1
  167. package/dist/server/events.js +1 -1
  168. package/dist/server/events.js.map +1 -1
  169. package/dist/server/extend.js +1 -1
  170. package/dist/server/insert.js +1 -1
  171. package/dist/server/insert.js.map +1 -1
  172. package/dist/server/internal/accessor.js +2 -0
  173. package/dist/server/internal/accessor.js.map +1 -0
  174. package/dist/server/internal/claim.js +1 -1
  175. package/dist/server/internal/claim.js.map +1 -1
  176. package/dist/server/internal/css-units.js +1 -1
  177. package/dist/server/internal/css-units.js.map +1 -1
  178. package/dist/server/internal/diagnostics.js +1 -1
  179. package/dist/server/internal/diagnostics.js.map +1 -1
  180. package/dist/server/internal/early-events.js +1 -1
  181. package/dist/server/internal/early-events.js.map +1 -1
  182. package/dist/server/internal/portal-context.js.map +1 -1
  183. package/dist/server/internal/react-names.js +1 -1
  184. package/dist/server/internal/react-names.js.map +1 -1
  185. package/dist/server/internal/reconcile.js +1 -1
  186. package/dist/server/internal/reconcile.js.map +1 -1
  187. package/dist/server/resource-hints.js +1 -1
  188. package/dist/server/resource-hints.js.map +1 -1
  189. package/dist/server/select-value.js +1 -1
  190. package/dist/server/select-value.js.map +1 -1
  191. package/dist/server/server/attributes.js +1 -1
  192. package/dist/server/server/attributes.js.map +1 -1
  193. package/dist/server/server/element.js +1 -1
  194. package/dist/server/server/element.js.map +1 -1
  195. package/dist/server/server/errors.js +1 -1
  196. package/dist/server/server/errors.js.map +1 -1
  197. package/dist/server/server/escape.js +1 -1
  198. package/dist/server/server/escape.js.map +1 -1
  199. package/dist/server/server/form-controls.js +2 -2
  200. package/dist/server/server/form-controls.js.map +1 -1
  201. package/dist/server/server/index.js +1 -1
  202. package/dist/server/server/portals.js +1 -1
  203. package/dist/server/server/portals.js.map +1 -1
  204. package/dist/server/server/raw-text.js +2 -0
  205. package/dist/server/server/raw-text.js.map +1 -0
  206. package/dist/server/server/render.js +1 -1
  207. package/dist/server/server/render.js.map +1 -1
  208. package/dist/server/server/stream.js +1 -1
  209. package/dist/server/server/stream.js.map +1 -1
  210. package/dist/server/server.js +1 -1
  211. package/dist/server/spread.js +1 -1
  212. package/dist/server/spread.js.map +1 -1
  213. package/dist/server/template.js +1 -1
  214. package/dist/server/template.js.map +1 -1
  215. package/dist/server/view-transition.js.map +1 -1
  216. package/dist/server-dev/attributes.js +27 -49
  217. package/dist/server-dev/attributes.js.map +1 -1
  218. package/dist/server-dev/class-style.js +64 -47
  219. package/dist/server-dev/class-style.js.map +1 -1
  220. package/dist/server-dev/control-flow/dynamic.js +22 -10
  221. package/dist/server-dev/control-flow/dynamic.js.map +1 -1
  222. package/dist/server-dev/control-flow/error-boundary.js +2 -2
  223. package/dist/server-dev/control-flow/error-boundary.js.map +1 -1
  224. package/dist/server-dev/control-flow/portal.js +17 -13
  225. package/dist/server-dev/control-flow/portal.js.map +1 -1
  226. package/dist/server-dev/control-flow/suspense-list.js +2 -2
  227. package/dist/server-dev/control-flow/suspense-list.js.map +1 -1
  228. package/dist/server-dev/control-flow/suspense.js +2 -2
  229. package/dist/server-dev/control-flow/suspense.js.map +1 -1
  230. package/dist/server-dev/element.js +3 -1
  231. package/dist/server-dev/element.js.map +1 -1
  232. package/dist/server-dev/events.js +15 -44
  233. package/dist/server-dev/events.js.map +1 -1
  234. package/dist/server-dev/extend.js +2 -2
  235. package/dist/server-dev/insert.js +84 -45
  236. package/dist/server-dev/insert.js.map +1 -1
  237. package/dist/server-dev/internal/accessor.js +56 -0
  238. package/dist/server-dev/internal/accessor.js.map +1 -0
  239. package/dist/server-dev/internal/claim.js +18 -3
  240. package/dist/server-dev/internal/claim.js.map +1 -1
  241. package/dist/server-dev/internal/css-units.js +2 -2
  242. package/dist/server-dev/internal/css-units.js.map +1 -1
  243. package/dist/server-dev/internal/diagnostics.js +14 -4
  244. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  245. package/dist/server-dev/internal/early-events.js +20 -2
  246. package/dist/server-dev/internal/early-events.js.map +1 -1
  247. package/dist/server-dev/internal/portal-context.js.map +1 -1
  248. package/dist/server-dev/internal/react-names.js +45 -71
  249. package/dist/server-dev/internal/react-names.js.map +1 -1
  250. package/dist/server-dev/internal/reconcile.js +7 -12
  251. package/dist/server-dev/internal/reconcile.js.map +1 -1
  252. package/dist/server-dev/resource-hints.js +4 -2
  253. package/dist/server-dev/resource-hints.js.map +1 -1
  254. package/dist/server-dev/select-value.js +5 -15
  255. package/dist/server-dev/select-value.js.map +1 -1
  256. package/dist/server-dev/server/attributes.js +6 -32
  257. package/dist/server-dev/server/attributes.js.map +1 -1
  258. package/dist/server-dev/server/element.js +10 -7
  259. package/dist/server-dev/server/element.js.map +1 -1
  260. package/dist/server-dev/server/errors.js +7 -1
  261. package/dist/server-dev/server/errors.js.map +1 -1
  262. package/dist/server-dev/server/escape.js +14 -6
  263. package/dist/server-dev/server/escape.js.map +1 -1
  264. package/dist/server-dev/server/form-controls.js +5 -2
  265. package/dist/server-dev/server/form-controls.js.map +1 -1
  266. package/dist/server-dev/server/index.js +3 -2
  267. package/dist/server-dev/server/portals.js +3 -0
  268. package/dist/server-dev/server/portals.js.map +1 -1
  269. package/dist/server-dev/server/raw-text.js +86 -0
  270. package/dist/server-dev/server/raw-text.js.map +1 -0
  271. package/dist/server-dev/server/render.js +3 -3
  272. package/dist/server-dev/server/render.js.map +1 -1
  273. package/dist/server-dev/server/stream.js +3 -3
  274. package/dist/server-dev/server/stream.js.map +1 -1
  275. package/dist/server-dev/server.js +3 -2
  276. package/dist/server-dev/spread.js +42 -80
  277. package/dist/server-dev/spread.js.map +1 -1
  278. package/dist/server-dev/template.js +1 -3
  279. package/dist/server-dev/template.js.map +1 -1
  280. package/dist/server-dev/view-transition.js.map +1 -1
  281. package/package.json +4 -3
@@ -1 +1 @@
1
- {"version":3,"file":"form-controls.js","names":[],"sources":["../../../src/server/form-controls.ts"],"sourcesContent":["import { invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n const html = escapeHtml(valueText(resolveValue(value)));\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves &lt;b&gt;tags&lt;/b&gt;</textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and `&nbsp;` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSelectedOptions(value: unknown, html: string):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invalid } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape, escapeHtml, resolveValue } from \"./escape\";\nimport { SsrNode } from \"./node\";\n\n/**\n * Server markup for the controls whose state is not an attribute. A browser ignores `value` on a\n * `<textarea>` and on a `<select>`: the textarea's text is its content, and the select's value is\n * the `selected` flag of its options. These helpers write that markup, so the server HTML shows the\n * same state the client sets and a form posted without JavaScript sends it.\n */\n\n/** Text of a value for a textarea: null and undefined are empty, everything else is its string. */\nfunction valueText(value: unknown): string {\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be a form control value.\");\n }\n return value === null || value === undefined ? \"\" : String(value);\n}\n\n/**\n * Markup of a textarea's content. The HTML parser drops one newline directly after `<textarea>`,\n * so a value that starts with a line break gets one more; its content is then exactly the value.\n * @internal\n */\nexport function textareaContent(value: unknown): string {\n return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));\n}\n\n/** Content markup of a textarea with the line break its parser would drop kept. @internal */\nexport function keepLeadingNewline(html: string): string {\n const first = html.charAt(0);\n return first === \"\\n\" || first === \"\\r\" ? `\\n${html}` : html;\n}\n\n/**\n * Renders the content of a `<textarea>` from its value: the helper compiled server output calls for\n * `<textarea value={...}>` and `defaultValue`, since a browser ignores a `value` attribute on a\n * textarea. The text is escaped, and a value that starts with a line break gets one more, because\n * the HTML parser drops the first one.\n *\n * @param value The value, or an accessor of it. `null` and `undefined` give an empty textarea;\n * anything else is written as `String(value)`.\n * @returns The escaped content as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol.\n * @example\n * import { renderToString, ssr, ssrTextArea } from \"@shadow-js/web/server\";\n *\n * const bio = \"Loves <b>tags</b>\";\n * const html = renderToString(() => ssr([\"<textarea>\", \"</textarea>\"], ssrTextArea(bio)));\n * // \"<textarea>Loves &lt;b&gt;tags&lt;/b&gt;</textarea>\"\n * @see ssrSelectValue\n * @since 1.0.0\n */\nexport function ssrTextArea(value: unknown): SsrNode {\n return new SsrNode(textareaContent(value));\n}\n\n/** The values a select value stands for: an array lists them (`multiple`), anything else is one. */\nfunction wantedValues(value: unknown): { values: Set<string>; many: boolean } {\n const resolved = resolveValue(value);\n if (!Array.isArray(resolved)) return { values: new Set([valueText(resolved)]), many: false };\n const values = new Set<string>();\n for (const item of resolved) {\n const one = resolveValue(item);\n if (one !== null && one !== undefined) values.add(valueText(one));\n }\n return { values, many: true };\n}\n\n/** Characters of the HTML spec's \"ASCII whitespace\". */\nconst WHITESPACE = /[ \\t\\n\\f\\r]+/g;\n/** Entities our own escaping writes, plus numeric references and `&nbsp;` from trusted raw markup. */\nconst ENTITY = /&(?:#(\\d+)|#x([0-9a-f]+)|(amp|lt|gt|quot|apos|nbsp));/gi;\nconst NAMED_ENTITIES: Readonly<Record<string, string>> = {\n amp: \"&\",\n lt: \"<\",\n gt: \">\",\n quot: '\"',\n apos: \"'\",\n nbsp: \" \",\n};\n/** Comments and tags inside an option's text (the region markers the compiler writes). */\nconst TAGS = /<!--[\\s\\S]*?-->|<[^>]*>/g;\n/**\n * The next option or optgroup tag, start or end: where an option's text ends. Sources of global\n * expressions, built per call so no `lastIndex` outlives it.\n */\nconst OPTION_BOUNDARY = \"<\\\\/?(?:option|optgroup)(?=[\\\\s/>])\";\n/** One attribute of a start tag: name, then an optional quoted or bare value. */\nconst ATTRIBUTE = \"\\\\s+([^\\\\s\\\"'<>/=]+)(?:\\\\s*=\\\\s*(?:\\\"([^\\\"]*)\\\"|'([^']*)'|([^\\\\s\\\"'=<>`]+)))?\";\n\nfunction decodeEntities(text: string): string {\n return text.replace(ENTITY, (whole, decimal?: string, hex?: string, named?: string) => {\n if (named !== undefined) return NAMED_ENTITIES[named.toLowerCase()] ?? whole;\n const code = decimal !== undefined ? Number(decimal) : Number.parseInt(hex ?? \"\", 16);\n return Number.isInteger(code) &&\n code >= 0 &&\n code <= 0x10ffff &&\n !(code >= 0xd800 && code <= 0xdfff)\n ? String.fromCodePoint(code)\n : whole;\n });\n}\n\n/** Index of the `>` that ends the start tag whose attributes begin at `from`, or -1. Quotes are skipped. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let index = from; index < html.length; index += 1) {\n const char = html.charAt(index);\n if (quote !== \"\") {\n if (char === quote) quote = \"\";\n } else if (char === '\"' || char === \"'\") {\n quote = char;\n } else if (char === \">\") {\n return index;\n }\n }\n return -1;\n}\n\n/** The text an option without a `value` attribute stands for: its text content, whitespace collapsed. */\nfunction optionText(html: string, from: number, boundaries: RegExp): string {\n boundaries.lastIndex = from;\n const boundary = boundaries.exec(html);\n const raw = html.slice(from, boundary === null ? html.length : boundary.index);\n return decodeEntities(raw.replace(TAGS, \"\")).replace(WHITESPACE, \" \").trim();\n}\n\n/**\n * Rewrites the option start tags of `html` so that exactly the wanted ones carry `selected`. The\n * input is markup this runtime produced (text and attribute values are escaped, so `<option` is\n * always a tag); only the `selected` attribute is added or removed, and nothing from the wanted\n * values is ever written.\n */\nfunction markOptions(html: string, wanted: { values: Set<string>; many: boolean }): string {\n let out = \"\";\n let copied = 0;\n let at = 0;\n let found = false;\n const attribute = new RegExp(ATTRIBUTE, \"g\");\n const boundaries = new RegExp(OPTION_BOUNDARY, \"gi\");\n for (;;) {\n const start = html.indexOf(\"<option\", at);\n if (start === -1) break;\n const attributesFrom = start + 7;\n at = attributesFrom;\n if (!/[\\s/>]/.test(html.charAt(attributesFrom))) continue;\n const end = tagEnd(html, attributesFrom);\n if (end === -1) break;\n const source = html.slice(attributesFrom, end);\n let value: string | undefined;\n let selectedAt = -1;\n let selectedEnd = -1;\n attribute.lastIndex = 0;\n for (let match = attribute.exec(source); match !== null; match = attribute.exec(source)) {\n const name = (match[1] ?? \"\").toLowerCase();\n if (name === \"selected\") {\n selectedAt = match.index;\n selectedEnd = match.index + match[0].length;\n } else if (name === \"value\" && value === undefined) {\n value = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n }\n // A scalar behaves like `select.value = x`: the first option with that value wins.\n const matches =\n (wanted.many || !found) && wanted.values.has(value ?? optionText(html, end + 1, boundaries));\n if (matches) found = true;\n if (matches && selectedAt === -1) {\n const slash = source.endsWith(\"/\") ? source.length - 1 : source.length;\n out += `${html.slice(copied, attributesFrom + slash)} selected`;\n copied = attributesFrom + slash;\n } else if (!matches && selectedAt !== -1) {\n out += html.slice(copied, attributesFrom + selectedAt);\n copied = attributesFrom + selectedEnd;\n }\n at = end;\n }\n return copied === 0 ? html : out + html.slice(copied);\n}\n\n/**\n * The options of a `<select>` with the ones its value stands for marked `selected`. A browser\n * ignores a `value` attribute on `<select>`, so the server flags the options instead: the option\n * whose `value` attribute equals the value (or, with no such attribute, whose text does) is\n * selected, and every other option loses `selected`. An array selects every listed option, for\n * `<select multiple>`; a single value selects the first match, like `select.value = x`. `null`\n * and `undefined` stand for the empty string. Options inside `<optgroup>`, control flow and\n * components are found because the search runs on the serialized children. Values are compared,\n * never written, so they cannot add markup.\n *\n * @param value The select's `value`, or an accessor of it. Entries of an array are compared as\n * strings; `null` and `undefined` entries are skipped.\n * @param children The select's children (an `SsrNode`, or anything `escape` accepts).\n * @returns The children with the `selected` flags set, as a trusted `SsrNode`.\n * @throws TypeError `UNRECOGNIZED_INSERT_VALUE` when the value is a symbol, and the errors of\n * {@link escape} for the children.\n * @example\n * import { renderToString, ssr, ssrRaw, ssrSelectValue } from \"@shadow-js/web/server\";\n *\n * const options = ssrRaw(`<option value=\"red\">Red</option><option value=\"blue\">Blue</option>`);\n * const html = renderToString(() => ssr([\"<select>\", \"</select>\"], ssrSelectValue(\"blue\", options)));\n * // '<select><option value=\"red\">Red</option><option value=\"blue\" selected>Blue</option></select>'\n * @see setSelectValue\n * @since 1.0.0\n */\nexport function ssrSelectValue(value: unknown, children: unknown): SsrNode {\n return new SsrNode(markSelectedOptions(value, escape(children)));\n}\n\n/** {@link ssrSelectValue} on markup that is already escaped. @internal */\nexport function markSel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2,15 +2,16 @@ import { escape } from "./escape.js";
2
2
  import { ssrAttribute } from "./attributes.js";
3
3
  import { ssrClass, ssrStyle } from "./class-style.js";
4
4
  import { ssrSelectValue, ssrTextArea } from "./form-controls.js";
5
+ import { ssrRawText } from "./raw-text.js";
5
6
  import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./element.js";
6
- import { createServerPortals } from "./portals.js";
7
7
  import { normalizeTags } from "../head/validate.js";
8
8
  import { createServerHead } from "../head/server-head.js";
9
9
  import { createComponent, memo } from "./component.js";
10
10
  import { derived } from "./derived.js";
11
11
  import { HydrationScript, generateHydrationScript } from "./hydration-script.js";
12
+ import { createServerPortals } from "./portals.js";
12
13
  import { renderToString, renderToStringAsync } from "./render.js";
13
14
  import { deserialize, serialize } from "./serialize.js";
14
15
  import { renderToStream } from "./stream.js";
15
16
  import { mergeProps as mergeProps$1 } from "@shadow-js/core";
16
- export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
17
+ export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps$1 as mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };
@@ -13,6 +13,9 @@ var PortalCollector = class {
13
13
  clear() {
14
14
  this.entries.clear();
15
15
  }
16
+ render(key, children) {
17
+ renderServerPortal(key, children, this);
18
+ }
16
19
  html() {
17
20
  let out = "";
18
21
  for (const [key, html] of this.entries) out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;
@@ -1 +1 @@
1
- {"version":3,"file":"portals.js","names":[],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CACjD,0BAA2B,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IAAI,CAAC,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAA,KACzC,MAAM,IAAI,SACR,oBACA,kFACF;EAEF,KAAK,QAAQ,IAAI,KAAK,IAAI;CAC5B;;CAGA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;CAEA,OAAe;EACb,IAAI,MAAM;EACV,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAC7B,OAAO,cAAc,IAAI,KAAK,KAAK,cAAc,IAAI;EAEvD,OAAO;CACT;AACF;AAEA,MAAM,6BAAa,IAAI,QAAwC;;;;;;;;;;;;;;;;;;AAmB/D,SAAgB,sBAAqC;CACnD,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,UAAyB,EAAE,YAAY,UAAU,KAAK,EAAE;CAC9D,WAAW,IAAI,SAAS,SAAS;CACjC,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,SAAyC;CACnE,MAAM,YAAY,WAAW,IAAI,OAAO;CACxC,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,UAAU,qDAAqD;CAE3E,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,mBACd,KACA,UACA,MACM;CACN,IAAI,SAAS,QAAQ,QAAQ,KAAA,GAAW;CACxC,MAAM,OAAO,UAAU,WAAW,GAAG,SAAS,OAAO,SAAS,CAAC,CAAC;CAChE,KAAK,IAAI,KAAK,IAAI;AACpB;;;;;;AAOA,SAAgB,eAAkB,MAAyB,OAAmB;CAO5E,OANa,cAAc;EACzB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CACW,CAAC,CAAa;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,SAA4D;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,YAAY,YAAY,OAAO;CACrC,UAAU,MAAM;CAChB,OAAO;AACT"}
1
+ {"version":3,"file":"portals.js","names":[],"sources":["../../../src/server/portals.ts"],"sourcesContent":["import { childScope, withScope } from \"../internal/hydration-scope\";\nimport { PortalContext, type PortalSink } from \"../internal/portal-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\n\n/**\n * The most portals one render may produce. A page with more open overlays than this is a bug, and the\n * collector refuses to grow without a bound.\n * @internal\n */\nexport const MAX_SERVER_PORTALS = 256;\n\n/**\n * The markup of the portals a server render produced (see {@link createServerPortals}). Pass it to\n * the render as its `portals` option, then emit `html()` at the end of `<body>`, after the app markup.\n * The client adopts each block when it hydrates the portal that wrote it.\n *\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<!doctype html><html><body><div id=\"app\">${app}</div>${portals.html()}</body></html>`;\n * @since 1.0.0\n */\nexport interface ServerPortals {\n /**\n * The collected blocks, in the order the render produced them: each is `<!--portal:KEY-->` markup\n * `<!--/portal:KEY-->`. Emit it once, at the end of `<body>`.\n * @returns The markup; empty when no portal was rendered.\n */\n html(): string;\n}\n\n/** The collector behind a {@link ServerPortals}: what a renderer writes into while it renders. @internal */\nexport class PortalCollector implements PortalSink {\n private readonly entries = new Map<string, string>();\n\n add(key: string, html: string): void {\n if (!this.entries.has(key) && this.entries.size >= MAX_SERVER_PORTALS) {\n throw new SsrError(\n \"SSR_PORTAL_LIMIT\",\n `A render produced more than ${MAX_SERVER_PORTALS} portals; close some overlays or raise the limit.`,\n );\n }\n this.entries.set(key, html);\n }\n\n /** Forgets what an earlier pass of the same render wrote. */\n clear(): void {\n this.entries.clear();\n }\n\n render(key: string | undefined, children: () => unknown): void {\n renderServerPortal(key, children, this);\n }\n\n html(): string {\n let out = \"\";\n for (const [key, html] of this.entries) {\n out += `<!--portal:${key}-->${html}<!--/portal:${key}-->`;\n }\n return out;\n }\n}\n\nconst collectors = new WeakMap<ServerPortals, PortalCollector>();\n\n/**\n * Creates the collector a server render writes its portals into. Without one, a `Portal` renders\n * nothing on the server. Create one per request: a render clears it before it starts, and one render\n * may produce at most 256 portals (more throw an `SsrError` whose `code` is `SSR_PORTAL_LIMIT`).\n *\n * @returns A new, empty {@link ServerPortals}.\n * @example\n * import { createComponent, createServerPortals, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <main>Hello</main>;\n * }\n * const portals = createServerPortals();\n * const app = renderToString(() => createComponent(App, {}), { portals });\n * const page = `<body><div id=\"app\">${app}</div>${portals.html()}</body>`;\n * @since 1.0.0\n */\nexport function createServerPortals(): ServerPortals {\n const collector = new PortalCollector();\n const portals: ServerPortals = { html: () => collector.html() };\n collectors.set(portals, collector);\n return portals;\n}\n\n/**\n * The collector behind a `portals` option.\n * @throws TypeError when the value did not come from {@link createServerPortals}.\n * @internal\n */\nexport function collectorOf(portals: ServerPortals): PortalCollector {\n const collector = collectors.get(portals);\n if (collector === undefined) {\n throw new TypeError(\"portals must be created with createServerPortals().\");\n }\n return collector;\n}\n\n/**\n * The server half of a `Portal`: renders its content into the render's collector. The content gets its\n * own hydration scope, so the keys of the siblings do not depend on whether the portal rendered. Writes\n * nothing when the render has no collector or the portal has no key (no render scope).\n *\n * @param key The portal's key, from `nextKey()` at the call site.\n * @param children Reads the portal's content. A thunk, because reading a JSX child builds it, and the\n * content must be built inside its own scope.\n * @param sink The collector the portal context provides (null for a render without one).\n * @internal\n */\nexport function renderServerPortal(\n key: string | undefined,\n children: () => unknown,\n sink: PortalSink | null,\n): void {\n if (sink === null || key === undefined) return;\n const html = withScope(childScope(key), () => escape(children()));\n sink.add(key, html);\n}\n\n/**\n * Runs `build` with the portal sink provided, and returns what `build` returns (the render's accessor).\n * A null sink provides nothing, so the portals of that render write nothing.\n * @internal\n */\nexport function withPortalSink<T>(sink: PortalSink | null, build: () => T): T {\n const view = PortalContext({\n value: sink,\n get children() {\n return build();\n },\n });\n return (view as () => T)();\n}\n\n/**\n * The collector a renderer writes into for one call: null without a `portals` option, else the cleared\n * collector.\n * @internal\n */\nexport function portalCollectorFor(portals: ServerPortals | undefined): PortalCollector | null {\n if (portals === undefined) return null;\n const collector = collectorOf(portals);\n collector.clear();\n return collector;\n}\n"],"mappings":";;;;;AAuCA,IAAa,kBAAb,MAAmD;CACjD,0BAA2B,IAAI,IAAoB;CAEnD,IAAI,KAAa,MAAoB;EACnC,IAAI,CAAC,KAAK,QAAQ,IAAI,GAAG,KAAK,KAAK,QAAQ,QAAA,KACzC,MAAM,IAAI,SACR,oBACA,kFACF;EAEF,KAAK,QAAQ,IAAI,KAAK,IAAI;CAC5B;;CAGA,QAAc;EACZ,KAAK,QAAQ,MAAM;CACrB;CAEA,OAAO,KAAyB,UAA+B;EAC7D,mBAAmB,KAAK,UAAU,IAAI;CACxC;CAEA,OAAe;EACb,IAAI,MAAM;EACV,KAAK,MAAM,CAAC,KAAK,SAAS,KAAK,SAC7B,OAAO,cAAc,IAAI,KAAK,KAAK,cAAc,IAAI;EAEvD,OAAO;CACT;AACF;AAEA,MAAM,6BAAa,IAAI,QAAwC;;;;;;;;;;;;;;;;;;AAmB/D,SAAgB,sBAAqC;CACnD,MAAM,YAAY,IAAI,gBAAgB;CACtC,MAAM,UAAyB,EAAE,YAAY,UAAU,KAAK,EAAE;CAC9D,WAAW,IAAI,SAAS,SAAS;CACjC,OAAO;AACT;;;;;;AAOA,SAAgB,YAAY,SAAyC;CACnE,MAAM,YAAY,WAAW,IAAI,OAAO;CACxC,IAAI,cAAc,KAAA,GAChB,MAAM,IAAI,UAAU,qDAAqD;CAE3E,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,mBACd,KACA,UACA,MACM;CACN,IAAI,SAAS,QAAQ,QAAQ,KAAA,GAAW;CACxC,MAAM,OAAO,UAAU,WAAW,GAAG,SAAS,OAAO,SAAS,CAAC,CAAC;CAChE,KAAK,IAAI,KAAK,IAAI;AACpB;;;;;;AAOA,SAAgB,eAAkB,MAAyB,OAAmB;CAO5E,OANa,cAAc;EACzB,OAAO;EACP,IAAI,WAAW;GACb,OAAO,MAAM;EACf;CACF,CACW,CAAC,CAAa;AAC3B;;;;;;AAOA,SAAgB,mBAAmB,SAA4D;CAC7F,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,MAAM,YAAY,YAAY,OAAO;CACrC,UAAU,MAAM;CAChB,OAAO;AACT"}
@@ -0,0 +1,86 @@
1
+ import { invalid } from "./errors.js";
2
+ import { SsrNode, isSsrNode } from "./node.js";
3
+ import { render, resolveValue } from "./escape.js";
4
+ // src/server/raw-text.ts
5
+ /**
6
+ * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no
7
+ * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers
8
+ * that delimit a dynamic child elsewhere would show up as literal text inside them.
9
+ */
10
+ const TEXT_ONLY_ELEMENTS = /* @__PURE__ */ new Set([
11
+ "script",
12
+ "style",
13
+ "title",
14
+ "textarea"
15
+ ]);
16
+ /**
17
+ * True for an HTML element whose content is text only, so its children are written without region markers
18
+ * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names
19
+ * are ordinary elements and are not text only.
20
+ * @internal
21
+ */
22
+ function isTextOnlyElement(tag) {
23
+ return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());
24
+ }
25
+ /** The elements whose text the parser reads raw. */
26
+ const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
27
+ /** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */
28
+ const CLOSING_TAG = {
29
+ script: /<\/(script)|<!--/gi,
30
+ style: /<\/(style)/gi
31
+ };
32
+ /**
33
+ * Keeps raw text from ending its element or the script data state. `<\/script` and `</style` get a backslash that
34
+ * CSS, JavaScript and JSON all read as the character itself (`<\/style` is `</style` in a string, a comment or a
35
+ * selector escape), and `<!--` in a script becomes `<\u0021--`: `\!` is no JSON escape, and a script that holds
36
+ * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does
37
+ * not see a tag. Entities would instead change the text: raw text has none.
38
+ */
39
+ function neutralize(tag, text) {
40
+ return text.replace(CLOSING_TAG[tag], (match) => match === "<!--" ? "<\\u0021--" : `<\\/${match.slice(2)}`);
41
+ }
42
+ /** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */
43
+ function rawTextContent(tag, value) {
44
+ return neutralize(tag.toLowerCase() === "script" ? "script" : "style", render(value, (text) => text));
45
+ }
46
+ /**
47
+ * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)
48
+ * is the application's own markup and is left as it is; any other value is raw text and is checked.
49
+ * @internal
50
+ */
51
+ function rawElementContent(tag, value) {
52
+ const resolved = resolveValue(value);
53
+ return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);
54
+ }
55
+ /**
56
+ * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a
57
+ * dynamic child of one. The browser reads these elements' content as raw text, so the value is written
58
+ * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region
59
+ * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of
60
+ * the element, in any letter case (`</style`, `<\/SCRIPT`), and `<!--` in a script, would end the element
61
+ * early or hide its end, so each is rewritten (`<\/style`, `<\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.
62
+ *
63
+ * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and
64
+ * a symbol throws, as in {@link escape}.
65
+ *
66
+ * @param tag The element, `"script"` or `"style"` (any letter case).
67
+ * @param value The child value: a string, a number, an array, an accessor or `null`.
68
+ * @returns The text as a trusted `SsrNode`.
69
+ * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of
70
+ * {@link escape} for the value.
71
+ * @example
72
+ * import { renderToString, ssr, ssrRawText } from "@shadow-js/web/server";
73
+ *
74
+ * const css = "a > b { color: red } </style><script>alert(1)<\/script>";
75
+ * const html = renderToString(() => ssr(["<style>", "</style>"], ssrRawText("style", css)));
76
+ * // "<style>a > b { color: red } <\/style><script>alert(1)<\/script></style>"
77
+ * @see escape
78
+ * @since 1.0.2
79
+ */
80
+ function ssrRawText(tag, value) {
81
+ if (typeof tag !== "string" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) throw invalid("INVALID_RAW_TEXT_TAG", "ssrRawText(): the tag must be script or style.");
82
+ return new SsrNode(rawTextContent(tag, value));
83
+ }
84
+ export { isTextOnlyElement, rawElementContent, rawTextContent, ssrRawText };
85
+
86
+ //# sourceMappingURL=raw-text.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"raw-text.js","names":[],"sources":["../../../src/server/raw-text.ts"],"sourcesContent":["import { invalid } from \"./errors\";\nimport { render, resolveValue } from \"./escape\";\nimport { isSsrNode, SsrNode } from \"./node\";\n\n/**\n * Elements whose content the HTML parser reads as text and nothing else: `script` and `style` (raw text, no\n * entities) and `title` and `textarea` (entities only). Neither kind can hold a comment, so the region markers\n * that delimit a dynamic child elsewhere would show up as literal text inside them.\n */\nconst TEXT_ONLY_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\", \"title\", \"textarea\"]);\n\n/**\n * True for an HTML element whose content is text only, so its children are written without region markers\n * and the client adopts the text as it is. Pass the tag in any letter case; SVG elements of the same names\n * are ordinary elements and are not text only.\n * @internal\n */\nexport function isTextOnlyElement(tag: string): boolean {\n return TEXT_ONLY_ELEMENTS.has(tag.toLowerCase());\n}\n\n/** The elements whose text the parser reads raw. */\nconst RAW_TEXT_ELEMENTS: ReadonlySet<string> = new Set([\"script\", \"style\"]);\n\n/** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */\nconst CLOSING_TAG = {\n script: /<\\/(script)|<!--/gi,\n style: /<\\/(style)/gi,\n} as const;\n\n/**\n * Keeps raw text from ending its element or the script data state. `</script` and `</style` get a backslash that\n * CSS, JavaScript and JSON all read as the character itself (`<\\/style` is `</style` in a string, a comment or a\n * selector escape), and `<!--` in a script becomes `<\\u0021--`: `\\!` is no JSON escape, and a script that holds\n * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does\n * not see a tag. Entities would instead change the text: raw text has none.\n */\nfunction neutralize(tag: \"script\" | \"style\", text: string): string {\n return text.replace(CLOSING_TAG[tag], (match: string) =>\n match === \"<!--\" ? \"<\\\\u0021--\" : `<\\\\/${match.slice(2)}`,\n );\n}\n\n/** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */\nexport function rawTextContent(tag: string, value: unknown): string {\n return neutralize(\n tag.toLowerCase() === \"script\" ? \"script\" : \"style\",\n render(value, (text) => text),\n );\n}\n\n/**\n * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)\n * is the application's own markup and is left as it is; any other value is raw text and is checked.\n * @internal\n */\nexport function rawElementContent(tag: string, value: unknown): string {\n const resolved = resolveValue(value);\n return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);\n}\n\n/**\n * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a\n * dynamic child of one. The browser reads these elements' content as raw text, so the value is written\n * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region\n * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of\n * the element, in any letter case (`</style`, `</SCRIPT`), and `<!--` in a script, would end the element\n * early or hide its end, so each is rewritten (`<\\/style`, `<\\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.\n *\n * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and\n * a symbol throws, as in {@link escape}.\n *\n * @param tag The element, `\"script\"` or `\"style\"` (any letter case).\n * @param value The child value: a string, a number, an array, an accessor or `null`.\n * @returns The text as a trusted `SsrNode`.\n * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of\n * {@link escape} for the value.\n * @example\n * import { renderToString, ssr, ssrRawText } from \"@shadow-js/web/server\";\n *\n * const css = \"a > b { color: red } </style><script>alert(1)</script>\";\n * const html = renderToString(() => ssr([\"<style>\", \"</style>\"], ssrRawText(\"style\", css)));\n * // \"<style>a > b { color: red } <\\/style><script>alert(1)</script></style>\"\n * @see escape\n * @since 1.0.2\n */\nexport function ssrRawText(tag: \"script\" | \"style\", value: unknown): SsrNode {\n if (typeof tag !== \"string\" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) {\n throw invalid(\"INVALID_RAW_TEXT_TAG\", \"ssrRawText(): the tag must be script or style.\");\n }\n return new SsrNode(rawTextContent(tag, value));\n}\n"],"mappings":";;;;;;;;;AASA,MAAM,qCAA0C,IAAI,IAAI;CAAC;CAAU;CAAS;CAAS;AAAU,CAAC;;;;;;;AAQhG,SAAgB,kBAAkB,KAAsB;CACtD,OAAO,mBAAmB,IAAI,IAAI,YAAY,CAAC;AACjD;;AAGA,MAAM,oCAAyC,IAAI,IAAI,CAAC,UAAU,OAAO,CAAC;;AAG1E,MAAM,cAAc;CAClB,QAAQ;CACR,OAAO;AACT;;;;;;;;AASA,SAAS,WAAW,KAAyB,MAAsB;CACjE,OAAO,KAAK,QAAQ,YAAY,OAAO,UACrC,UAAU,SAAS,eAAe,OAAO,MAAM,MAAM,CAAC,GACxD;AACF;;AAGA,SAAgB,eAAe,KAAa,OAAwB;CAClE,OAAO,WACL,IAAI,YAAY,MAAM,WAAW,WAAW,SAC5C,OAAO,QAAQ,SAAS,IAAI,CAC9B;AACF;;;;;;AAOA,SAAgB,kBAAkB,KAAa,OAAwB;CACrE,MAAM,WAAW,aAAa,KAAK;CACnC,OAAO,UAAU,QAAQ,IAAI,SAAS,IAAI,eAAe,KAAK,QAAQ;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,WAAW,KAAyB,OAAyB;CAC3E,IAAI,OAAO,QAAQ,YAAY,CAAC,kBAAkB,IAAI,IAAI,YAAY,CAAC,GACrE,MAAM,QAAQ,wBAAwB,gDAAgD;CAExF,OAAO,IAAI,QAAQ,eAAe,KAAK,KAAK,CAAC;AAC/C"}
@@ -1,9 +1,9 @@
1
1
  import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
2
- import { SsrError } from "./errors.js";
2
+ import { MAX_TIMER_MS, SsrError } from "./errors.js";
3
3
  import { escape } from "./escape.js";
4
4
  import { attachRootErrors } from "../control-flow/root-errors.js";
5
- import { portalCollectorFor, withPortalSink } from "./portals.js";
6
5
  import { runWithServerHead } from "../head/server-head.js";
6
+ import { portalCollectorFor, withPortalSink } from "./portals.js";
7
7
  import { ResourceCacheContext, createRoot } from "@shadow-js/core";
8
8
  // src/server/render.ts
9
9
  const DEFAULT_TIMEOUT_MS = 1e4;
@@ -239,7 +239,7 @@ async function renderToStringAsync(code, options) {
239
239
  timer = setTimeout(() => {
240
240
  job.canceled = true;
241
241
  reject(new SsrError("SSR_TIMEOUT", `The render did not finish within ${timeoutMs} ms.`));
242
- }, timeoutMs);
242
+ }, Math.min(timeoutMs, MAX_TIMER_MS));
243
243
  });
244
244
  try {
245
245
  const portals = portalCollectorFor(options?.portals);
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":[],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n }, timeoutMs);\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":";;;;;;;;AAuFA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,YAAY;;AAGlB,SAAS,cAAc,UAA0B;CAC/C,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,OAAO;AACT;;;;;AAM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Ac,kBAAkB,OAAO;CAC1D,MAAM,MAAW;EAAE,UAAU;EAAO,OAAO,CAAC;CAAE;CAC9C,IAAI;CACJ,MAAM,UAAU,IAAI,SAAgB,UAAU,WAAW;EACvD,QAAQ,iBAAiB;GACvB,IAAI,WAAW;GACf,OAAO,IAAI,SAAS,eAAe,oCAAoC,UAAU,KAAK,CAAC;EACzF,GAAG,SAAS;CACd,CAAC;CACD,IAAI;EACF,MAAM,UAAU,mBAAmB,SAAS,OAAO;EACnD,OAAO,MAAM,QAAQ,KAAK,CACxB,UAAU,MAAM,UAAU,WAAW,KAAK,SAAS,MAAM,SAAS,YAAY,OAAO,CAAC,GACtF,OACF,CAAC;CACH,UAAU;EACR,aAAa,KAAK;EAClB,IAAI,WAAW;EACf,KAAK,MAAM,WAAW,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ;CACrD;AACF"}
1
+ {"version":3,"file":"render.js","names":[],"sources":["../../../src/server/render.ts"],"sourcesContent":["import { createRoot, type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nimport { escape } from \"./escape\";\nimport {\n type PortalCollector,\n portalCollectorFor,\n type ServerPortals,\n withPortalSink,\n} from \"./portals\";\n\n/**\n * Options of {@link renderToString}, and the base of {@link AsyncRenderOptions}.\n * @since 1.0.0\n */\nexport interface RenderOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Give each app rendered into the\n * same page its own id, and pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * Collects the tags `useHead`, `<Title>`, `<Meta>`, ... register while rendering (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Collects the markup of the portals the render produces (see {@link createServerPortals}). Emit\n * `portals.html()` at the end of `<body>` once the render is done.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the render caught. The boundary's fallback is in the markup,\n * so the caller can answer the request with the status of the error. Called once per caught error.\n * For {@link renderToStringAsync} only the last pass is reported.\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the render does not throw that error and the markup\n * lacks the part that failed.\n * @default undefined (the error propagates out of the render)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\n/**\n * Options of {@link renderToStringAsync}: the {@link RenderOptions} plus the limits of the multi-pass\n * render.\n * @since 1.0.0\n */\nexport interface AsyncRenderOptions extends RenderOptions {\n /**\n * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the\n * timer range (2147483647, about 24.8 days) count as 2147483647.\n * @default 10000\n */\n readonly timeoutMs?: number;\n /**\n * Maximum number of render passes: an integer of at least 1. Each pass renders with the resource\n * values the previous passes resolved.\n * @default 10\n */\n readonly maxPasses?: number;\n}\n\n/**\n * What {@link renderToStringAsync} resolves to: the markup and the resource data to embed for\n * hydration.\n * @since 1.0.0\n */\nexport interface AsyncRenderResult {\n /** The markup of the last pass. */\n readonly html: string;\n /**\n * The resolved resource values the last pass read, keyed as the client looks them up. Embed it in\n * the page with {@link serialize} and pass it to `hydrate()` as its `data` option, so the client\n * reuses the values instead of fetching again.\n */\n readonly data: Record<string, unknown>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_PASSES = 10;\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\n\n/** Validates a render id: it is written into markup, so only plain tokens are accepted. */\nfunction checkRenderId(renderId: string): string {\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n return renderId;\n}\n\n/**\n * The reporters of a render, in the shape the root takes them. An `onUncaughtError` is set only when the\n * caller gave one: a root with a handler does not rethrow, so without one the error must keep propagating.\n */\nfunction reportersOf(options: RenderOptions | undefined): RootErrorOptions {\n return {\n ...(options?.onCaughtError === undefined ? {} : { onCaughtError: options.onCaughtError }),\n ...(options?.onUncaughtError === undefined ? {} : { onUncaughtError: options.onUncaughtError }),\n };\n}\n\n/**\n * Runs `code` under the render's resource cache and returns the escaped markup. The root scope\n * is entered inside the provider, so accessors evaluated during escaping see the same cache.\n * Must run inside the root that is being rendered: the reporters are attached to it.\n */\nfunction renderMarkup(\n code: () => unknown,\n renderId: string,\n cache: ResourceCache | null,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n reporters: RootErrorOptions,\n): string {\n attachRootErrors(reporters);\n // The provider returns an accessor; reading it surfaces an error thrown while rendering.\n return (\n withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n ) as () => string\n )();\n}\n\n/**\n * Renders an app to an HTML string synchronously: the simplest server render, for pages whose data\n * is already at hand. Suspense boundaries whose resources are still pending render their fallback\n * (use {@link renderToStringAsync} or {@link renderToStream} to wait for data). Effects never run.\n * The root is disposed before this returns, and an error from `code` propagates after that cleanup.\n *\n * @param code Builds the app: returns a component result, an `SsrNode`, text or an array.\n * @param options Hydration-key prefix, head and portal collectors, and error reporters. Undefined uses\n * the defaults of {@link RenderOptions}.\n * @returns The escaped markup of the app.\n * @throws TypeError for an invalid `renderId`, for `portals` not created by\n * {@link createServerPortals}, or for a value that cannot be rendered (see {@link escape}). An error\n * no boundary caught propagates unless `onUncaughtError` is set.\n * @example\n * import { createComponent, renderToString } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * const html = renderToString(() => createComponent(App, {}));\n * @see renderToStringAsync\n * @see renderToStream\n * @since 1.0.0\n */\nexport function renderToString(code: () => unknown, options?: RenderOptions): string {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const portals = portalCollectorFor(options?.portals);\n const reporters = reportersOf(options);\n return createRoot((dispose) => {\n try {\n return renderMarkup(code, renderId, null, options?.head, portals, reporters);\n } finally {\n dispose();\n }\n });\n}\n\n/** The errors one pass reported to its root, kept until the pass is known to be the answer. */\ninterface PassErrors {\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n}\n\n/** One render pass: its markup, the keys it asked for, and the fetches it started. */\ninterface Pass {\n readonly html: string;\n readonly requested: Set<string>;\n readonly tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }>;\n readonly errors: PassErrors;\n readonly dispose: () => void;\n}\n\n/**\n * Runs one pass. The root stays alive until the caller disposes it, so fetches are not aborted. The\n * pass records its errors instead of reporting them: every pass renders the same boundaries again, so\n * only the answering pass (see {@link reportPass}) reports.\n */\nfunction runPass(\n code: () => unknown,\n renderId: string,\n settled: ReadonlyMap<string, unknown>,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Pass {\n const requested = new Set<string>();\n const tracked: Array<{ readonly key: string; readonly promise: Promise<unknown> }> = [];\n const errors: PassErrors = { caught: [], uncaught: [] };\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n errors.caught.push(error);\n },\n // Recorded only when the caller reports uncaught errors; otherwise the error must still throw.\n ...(user.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n errors.uncaught.push(error);\n },\n }),\n };\n const seen = new Set<string>();\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise) => {\n if (seen.has(key)) return;\n seen.add(key);\n tracked.push({ key, promise });\n },\n };\n return createRoot((dispose) => {\n // Every pass registers the same tags and portals again: only the last pass counts.\n head?.clear();\n portals?.clear();\n const html = renderMarkup(code, renderId, cache, head, portals, reporters);\n return { html, requested, tracked, errors, dispose };\n });\n}\n\n/**\n * Hands the errors of the answering pass to the caller's reporters, in the order they happened. Called\n * once per render, so each caught error is reported once even when several passes rendered it.\n */\nfunction reportPass(errors: PassErrors, user: RootErrorOptions): void {\n for (const error of errors.caught) user.onCaughtError?.(error);\n for (const error of errors.uncaught) user.onUncaughtError?.(error);\n}\n\n/** Records a value under a key with defineProperty, so keys such as \"__proto__\" stay data. */\nfunction defineData(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** The values of `settled` that the pass asked for. */\nfunction collectData(\n requested: ReadonlySet<string>,\n settled: ReadonlyMap<string, unknown>,\n): Record<string, unknown> {\n const data: Record<string, unknown> = {};\n for (const key of requested) {\n if (settled.has(key)) defineData(data, key, settled.get(key));\n }\n return data;\n}\n\n/** Shared state of one async render: its cancellation flag and the roots still alive. */\ninterface Job {\n canceled: boolean;\n readonly roots: Array<() => void>;\n}\n\nfunction assertActive(job: Job): void {\n if (job.canceled)\n throw new SsrError(\"SSR_TIMEOUT\", \"The render was canceled after its time budget.\");\n}\n\n/**\n * The multi-pass algorithm. Pass N renders with the values resolved so far; the fetches it starts\n * are awaited, and another pass runs only if one of them produced a value that the next render can\n * use. A pass with no new value is final: its markup is the answer.\n */\nasync function runPasses(\n code: () => unknown,\n renderId: string,\n maxPasses: number,\n job: Job,\n head: ServerHead | undefined,\n portals: PortalCollector | null,\n user: RootErrorOptions,\n): Promise<AsyncRenderResult> {\n const settled = new Map<string, unknown>();\n for (let pass = 1; ; pass += 1) {\n assertActive(job);\n const current = runPass(code, renderId, settled, head, portals, user);\n job.roots.push(current.dispose);\n if (current.tracked.length === 0) {\n current.dispose();\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n const results = await Promise.allSettled(current.tracked.map((entry) => entry.promise));\n assertActive(job);\n let advanced = false;\n results.forEach((result, index) => {\n const entry = current.tracked[index];\n if (entry === undefined || result.status !== \"fulfilled\") return;\n if (!settled.has(entry.key)) advanced = true;\n settled.set(entry.key, result.value);\n });\n current.dispose();\n if (!advanced) {\n reportPass(current.errors, user);\n return { html: current.html, data: collectData(current.requested, settled) };\n }\n if (pass >= maxPasses) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept loading new resources after ${maxPasses} passes; raise maxPasses or flatten the data flow.`,\n );\n }\n }\n}\n\n/** Validates the numeric options. */\nfunction checkAsyncOptions(options: AsyncRenderOptions | undefined): {\n timeoutMs: number;\n maxPasses: number;\n} {\n const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const maxPasses = options?.maxPasses ?? DEFAULT_MAX_PASSES;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n if (!Number.isInteger(maxPasses) || maxPasses < 1) {\n throw new TypeError(\"render options: maxPasses must be an integer of at least 1.\");\n }\n return { timeoutMs, maxPasses };\n}\n\n/**\n * Renders an app to an HTML string once its data has loaded: each pass renders with the resource\n * values found so far, the fetches it starts are awaited, and another pass runs while one of them\n * produced a new value. Resources that reject are not cached and render their fallback. The error\n * reporters (`onCaughtError`, `onUncaughtError`) are called once, for the pass that gives the answer.\n *\n * @param code Builds the app.\n * @param options The {@link RenderOptions} plus `timeoutMs` and `maxPasses`. Undefined uses the\n * defaults of {@link AsyncRenderOptions}.\n * @returns A promise of the final markup and the resolved resource values, to embed in the page.\n * @throws TypeError (synchronously rejected) for an invalid `renderId`, `timeoutMs` or `maxPasses`.\n * The promise rejects with an `Error` named `SsrError` whose `code` is `SSR_BOUNDARY_WATERFALL` when\n * more than `maxPasses` passes are needed, or `SSR_TIMEOUT` when the time budget runs out; and with\n * the error of a failing render.\n * @example\n * import { createComponent, renderToStringAsync, serialize } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * async function page(): Promise<string> {\n * const { html, data } = await renderToStringAsync(() => createComponent(App, {}));\n * return `${html}<script type=\"application/json\" data-sh=\"0\">${serialize(data)}</script>`;\n * }\n * @see renderToString\n * @see renderToStream\n * @since 1.0.0\n */\nexport async function renderToStringAsync(\n code: () => unknown,\n options?: AsyncRenderOptions,\n): Promise<AsyncRenderResult> {\n const renderId = checkRenderId(options?.renderId ?? \"0\");\n const { timeoutMs, maxPasses } = checkAsyncOptions(options);\n const job: Job = { canceled: false, roots: [] };\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(\n () => {\n job.canceled = true;\n reject(new SsrError(\"SSR_TIMEOUT\", `The render did not finish within ${timeoutMs} ms.`));\n },\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n try {\n const portals = portalCollectorFor(options?.portals);\n return await Promise.race([\n runPasses(code, renderId, maxPasses, job, options?.head, portals, reportersOf(options)),\n expired,\n ]);\n } finally {\n clearTimeout(timer);\n job.canceled = true;\n for (const dispose of job.roots.splice(0)) dispose();\n }\n}\n"],"mappings":";;;;;;;;AAwFA,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,YAAY;;AAGlB,SAAS,cAAc,UAA0B;CAC/C,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,OAAO;AACT;;;;;AAMA,SAAS,YAAY,SAAsD;CACzE,OAAO;EACL,GAAI,SAAS,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,eAAe,QAAQ,cAAc;EACvF,GAAI,SAAS,oBAAoB,KAAA,IAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;CAC/F;AACF;;;;;;AAOA,SAAS,aACP,MACA,UACA,OACA,MACA,SACA,WACQ;CACR,iBAAiB,SAAS;CAE1B,OACE,eAAe,eACb,qBAAqB;EACnB,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SAAS,OAAO;EACnD,OAAO,MAAM,QAAQ,KAAK,CACxB,UAAU,MAAM,UAAU,WAAW,KAAK,SAAS,MAAM,SAAS,YAAY,OAAO,CAAC,GACtF,OACF,CAAC;CACH,UAAU;EACR,aAAa,KAAK;EAClB,IAAI,WAAW;EACf,KAAK,MAAM,WAAW,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ;CACrD;AACF"}
@@ -1,10 +1,10 @@
1
1
  import { createRootScope, resourceKey, withScope } from "../internal/hydration-scope.js";
2
- import { SsrError } from "./errors.js";
2
+ import { MAX_TIMER_MS, SsrError } from "./errors.js";
3
3
  import { escape } from "./escape.js";
4
4
  import { StreamContext } from "../internal/stream-context.js";
5
5
  import { attachRootErrors } from "../control-flow/root-errors.js";
6
- import { portalCollectorFor, withPortalSink } from "./portals.js";
7
6
  import { runWithServerHead } from "../head/server-head.js";
7
+ import { portalCollectorFor, withPortalSink } from "./portals.js";
8
8
  import { serialize } from "./serialize.js";
9
9
  import { ResourceCacheContext, createRoot, untrack } from "@shadow-js/core";
10
10
  // src/server/stream.ts
@@ -152,7 +152,7 @@ function renderToStream(code, options = {}) {
152
152
  let rejectAbort = () => void 0;
153
153
  const abort = new Promise((_resolve, reject) => {
154
154
  rejectAbort = reject;
155
- timer = setTimeout(() => reject(new SsrError("SSR_TIMEOUT", `The stream did not finish within ${timeoutMs} ms.`)), timeoutMs);
155
+ timer = setTimeout(() => reject(new SsrError("SSR_TIMEOUT", `The stream did not finish within ${timeoutMs} ms.`)), Math.min(timeoutMs, MAX_TIMER_MS));
156
156
  });
157
157
  const onAbort = () => rejectAbort(signal?.reason ?? /* @__PURE__ */ new Error("The render was aborted."));
158
158
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -1 +1 @@
1
- {"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n timeoutMs,\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAmC;CAG/D,OAAO,UADL,UAAU,KAAA,IAAY,KAAK,WAAW,MAAM,QAAQ,sBAAsB,EAAE,EAAE,GACrD,GAAG,KAAK;AACrC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,eACd,MACA,UAAyB,CAAC,GACE;CAC5B,MAAM,WAAW,QAAQ,YAAY;CACrC,IAAI,OAAO,aAAa,YAAY,CAAC,UAAU,KAAK,QAAQ,GAC1D,MAAM,IAAI,UAAU,oEAAoE;CAE1F,MAAM,YAAY,QAAQ,aAAa;CACvC,IAAI,OAAO,cAAc,YAAY,EAAE,YAAY,MAAM,CAAC,OAAO,SAAS,SAAS,GACjF,MAAM,IAAI,UAAU,6DAA6D;CAEnF,MAAM,SAAS,QAAQ;CACvB,MAAM,UAAU,mBAAmB,QAAQ,OAAO;CAClD,MAAM,UAAU,IAAI,YAAY;CAEhC,MAAM,SAAsB,CAAC;CAC7B,MAAM,mBAAyB;EAC7B,MAAM,SAAoB,CAAC;EAC3B,KAAK,MAAM,QAAQ,OAAO,OAAO,CAAC,GAChC,IAAI;GACF,KAAK,QAAQ;EACf,SAAS,OAAO;GACd,OAAO,KAAK,KAAK;EACnB;EAEF,IAAI,OAAO,SAAS,GAClB,MAAM,OAAO,WAAW,IAAI,OAAO,KAAK,IAAI,eAAe,QAAQ,wBAAwB;CAC/F;CACA,IAAI,WAAW;CAEf,IAAI;CACJ,IAAI,qBAAgD,KAAA;CAEpD,OAAO,IAAI,eAA2B;EACpC,MAAM,MAAM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,UAAU,IAAI;KACrE,IAAI,OAAO,WAAW,SAAS,KAAK,WAAW,GAAG,cAAc;IAClE;IAEA,MAAM,OAAgC,CAAC;IACvC,KAAK,MAAM,OAAO,OAAO,WAAW;KAClC,IAAI,CAAC,QAAQ,IAAI,GAAG,GAAG;KACvB,OAAO,eAAe,MAAM,KAAK;MAC/B,OAAO,QAAQ,IAAI,GAAG;MACtB,YAAY;MACZ,UAAU;MACV,cAAc;KAChB,CAAC;IACH;IACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,GAC7B,KAAK,4CAA4C,SAAS,IAAI,UAAU,IAAI,EAAE,WAAU;IAE1F,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"stream.js","names":[],"sources":["../../../src/server/stream.ts"],"sourcesContent":["import {\n createRoot,\n type ResourceCache,\n ResourceCacheContext,\n type ResourceTrackOptions,\n untrack,\n} from \"@shadow-js/core\";\nimport { attachRootErrors, type RootErrorOptions } from \"../control-flow/root-errors\";\nimport { runWithServerHead, type ServerHead } from \"../head/server-head\";\nimport { createRootScope, resourceKey, withScope } from \"../internal/hydration-scope\";\nimport { type StreamBoundary, StreamContext, type StreamSink } from \"../internal/stream-context\";\nimport { MAX_TIMER_MS, SsrError } from \"./errors\";\n// biome-ignore lint/suspicious/noShadowRestrictedNames: `escape` is the compiler's SSR helper name.\nimport { escape } from \"./escape\";\nimport { portalCollectorFor, type ServerPortals, withPortalSink } from \"./portals\";\nimport { serialize } from \"./serialize\";\n\n/**\n * Options of {@link renderToStream}.\n * @since 1.0.0\n */\nexport interface StreamOptions {\n /**\n * Prefix of every hydration key: letters, digits, `_` and `-` only. Pass the same id to `hydrate()`.\n * @default \"0\"\n */\n readonly renderId?: string;\n /**\n * CSP nonce for the inline swap scripts. Characters outside letters, digits, `+`, `/`, `=`, `_` and\n * `-` are removed before it is written.\n * @default undefined (the scripts get no nonce attribute)\n */\n readonly nonce?: string;\n /**\n * Upper bound for the whole stream, in milliseconds, a positive finite number (values above 2147483647 count as 2147483647). When it runs out, the stream errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT`.\n * @default 30000\n */\n readonly timeoutMs?: number;\n /**\n * Aborts the render: the stream errors with the signal's reason and every pending fetch is abandoned.\n * @default undefined (the render is bounded only by `timeoutMs`)\n */\n readonly signal?: AbortSignal;\n /**\n * Collects the tags `useHead`, `<Title>`, ... register while the shell renders (see\n * `createServerHead`).\n * @default undefined (head tags are not collected)\n */\n readonly head?: ServerHead;\n /**\n * Called with the shell markup as soon as it is ready, before it is enqueued: the moment to write\n * the document head and choose the response status.\n * @default undefined (no callback)\n */\n readonly onShellReady?: (shell: string) => void;\n /**\n * Collects the markup of the portals the stream produces (see {@link createServerPortals}). The stream\n * does not write it: once the stream has ended, emit `portals.html()` at the end of `<body>`.\n * @default undefined (a portal renders nothing on the server)\n */\n readonly portals?: ServerPortals;\n /**\n * Receives an error an `ErrorBoundary` of the stream caught, once per caught error. An error in the shell\n * happens before the first chunk, so the caller can still choose the response status; an error in a later\n * boundary happens after the shell and changes only that boundary (its fallback stays).\n * @default undefined (caught errors are not reported)\n */\n readonly onCaughtError?: (error: unknown) => void;\n /**\n * Receives an error no boundary took. With it the stream does not error on that error and the markup lacks\n * the part that failed.\n * @default undefined (the error ends the stream in its `error` state)\n */\n readonly onUncaughtError?: (error: unknown) => void;\n}\n\nconst RENDER_ID = /^[A-Za-z0-9_-]+$/;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n/**\n * The most shell renders a stream makes while resources hold its first flush. Each render uses the held\n * values the one before resolved, so a chain of held resources is bounded like a boundary waterfall.\n */\nconst MAX_SHELL_PASSES = 10;\n\n/**\n * One render of the shell: its markup, the boundaries still pending in it, the keys it asked for and the\n * fetches it started. Only the answering pass (the one the stream sends) reports its errors; the others\n * are discarded, and their fetches stay alive so a later pass can join them.\n */\ninterface ShellPass {\n html: string;\n boundaries: StreamBoundary[];\n readonly requested: Set<string>;\n /** The fetches this render started that hold the first flush (`deferStream`), by key. */\n readonly held: Array<{ readonly key: string; readonly entry: Promise<void> }>;\n /** The fetches this render started that the stream is still waiting for. */\n readonly inFlight: Set<Promise<void>>;\n readonly caught: unknown[];\n readonly uncaught: unknown[];\n answered: boolean;\n dispose: () => void;\n}\n\n/**\n * The constant swap runtime. `$S(id)` replaces the fallback of boundary `id` (the nodes between\n * its `<!--[b:id-->` and `<!--]-->` comments) with the content of `<template id=\"s:id\">`; with a\n * second argument the boundary failed on the server and keeps its fallback for the client.\n */\nconst SWAP_RUNTIME =\n 'window.$S=function(i,f){var t=document.getElementById(\"s:\"+i);if(!t)return;' +\n \"if(!f){var w=document.createTreeWalker(document,128),c;while(c=w.nextNode()){\" +\n 'if(c.data===\"[b:\"+i){var d=1,n=c.nextSibling,e=null;while(n){' +\n 'if(n.nodeType===8){if(n.data.charAt(0)===\"[\"){d++}else if(n.data===\"]\"){d--;if(d===0){e=n;break}}}' +\n \"n=n.nextSibling}if(e){while(c.nextSibling!==e)c.parentNode.removeChild(c.nextSibling);\" +\n \"e.parentNode.insertBefore(t.content,e)}break}}}t.remove()};\";\n\nfunction script(body: string, nonce: string | undefined): string {\n const attribute =\n nonce === undefined ? \"\" : ` nonce=\"${nonce.replace(/[^A-Za-z0-9+/=_-]/g, \"\")}\"`;\n return `<script${attribute}>${body}</script>`;\n}\n\n/**\n * Renders an app as a stream of HTML, for the fastest first byte: the shell first (pending Suspense\n * boundaries show their fallback), then one chunk per boundary as its data arrives, in the order the\n * data settles, and finally, when resources resolved, a\n * `<script type=\"application/json\" data-sh=\"RENDER_ID\">` block with their values. The page works without JavaScript: each chunk is a `<template>` that a\n * tiny inline script swaps in for the fallback. A boundary whose data can no longer arrive keeps its\n * fallback for the client.\n *\n * @param code Builds the app.\n * @param options Hydration-key prefix, nonce, time budget, abort signal, collectors, shell callback\n * and error reporters. Undefined uses the defaults of {@link StreamOptions}.\n * @returns A byte stream of the app markup, to be placed inside your document. Canceling it stops\n * the render.\n * @throws TypeError, synchronously, for an invalid `renderId` or `timeoutMs`. The stream itself errors with an\n * `SsrError` whose `code` is `SSR_TIMEOUT` when `timeoutMs` runs out, with the signal's reason when\n * `signal` aborts, and with an error no boundary caught when `onUncaughtError` is not set.\n * @example\n * import { createComponent, renderToStream } from \"@shadow-js/web/server\";\n *\n * function App() {\n * return <h1>Hello</h1>;\n * }\n * function handle(request: Request): Response {\n * const stream = renderToStream(() => createComponent(App, {}), { signal: request.signal });\n * return new Response(stream, { headers: { \"content-type\": \"text/html\" } });\n * }\n * @see renderToStringAsync\n * @since 1.0.0\n */\nexport function renderToStream(\n code: () => unknown,\n options: StreamOptions = {},\n): ReadableStream<Uint8Array> {\n const renderId = options.renderId ?? \"0\";\n if (typeof renderId !== \"string\" || !RENDER_ID.test(renderId)) {\n throw new TypeError(\"render options: renderId must be made of letters, digits, _ and -.\");\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (typeof timeoutMs !== \"number\" || !(timeoutMs > 0) || !Number.isFinite(timeoutMs)) {\n throw new TypeError(\"render options: timeoutMs must be a positive finite number.\");\n }\n const signal = options.signal;\n const portals = portalCollectorFor(options.portals);\n const encoder = new TextEncoder();\n // Every render of the shell, kept until the stream ends: a later pass joins the fetches an earlier one started.\n const passes: ShellPass[] = [];\n const disposeAll = (): void => {\n const errors: unknown[] = [];\n for (const pass of passes.splice(0)) {\n try {\n pass.dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0)\n throw errors.length === 1 ? errors[0] : new AggregateError(errors, \"Stream cleanup failed.\");\n };\n let canceled = false;\n // Cleared when the stream ends or is canceled, so a finished render never keeps the process alive.\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cancelRender: (reason: unknown) => void = () => undefined;\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const settled = new Map<string, unknown>();\n // The fetch each key was last started with: a render that finds it unsettled joins it (ResourceCache.pending).\n const fetching = new Map<string, Promise<unknown>>();\n const push = (text: string): void => {\n if (signal?.aborted) throw signal.reason;\n if (!canceled) controller.enqueue(encoder.encode(text));\n };\n\n /** Renders the shell once. Its resources, boundaries and errors belong to this pass alone. */\n const renderPass = (): ShellPass => {\n const pass: ShellPass = {\n html: \"\",\n boundaries: [],\n requested: new Set<string>(),\n held: [],\n inFlight: new Set<Promise<void>>(),\n caught: [],\n uncaught: [],\n answered: false,\n dispose: () => undefined,\n };\n passes.push(pass);\n const cache: ResourceCache = {\n key: (explicit) => {\n const key = resourceKey(explicit);\n pass.requested.add(key);\n return key;\n },\n read: (key) => (settled.has(key) ? { value: settled.get(key) } : undefined),\n track: (key, promise, trackOptions?: ResourceTrackOptions) => {\n fetching.set(key, promise);\n const entry = promise.then(\n (value) => {\n settled.set(key, value);\n },\n () => undefined,\n );\n pass.inFlight.add(entry);\n void entry.finally(() => pass.inFlight.delete(entry));\n if (trackOptions?.deferStream === true) pass.held.push({ key, entry });\n },\n pending: (key) => fetching.get(key),\n };\n const sink: StreamSink = {\n defer: (boundary: StreamBoundary) => {\n pass.boundaries.push(boundary);\n },\n };\n // Errors of a pass that is not the answer are held back: the answering pass reports them, once.\n const reporters: RootErrorOptions = {\n onCaughtError: (error) => {\n if (pass.answered) options.onCaughtError?.(error);\n else pass.caught.push(error);\n },\n ...(options.onUncaughtError === undefined\n ? {}\n : {\n onUncaughtError: (error: unknown) => {\n if (pass.answered) options.onUncaughtError?.(error);\n else pass.uncaught.push(error);\n },\n }),\n };\n options.head?.clear();\n portals?.clear();\n pass.html = createRoot((stop) => {\n pass.dispose = stop;\n // Attached to the root of this render, so every boundary of it reports through these.\n attachRootErrors(reporters);\n const view = StreamContext({\n value: sink,\n get children() {\n return withPortalSink(portals, () =>\n ResourceCacheContext({\n value: cache,\n get children() {\n return runWithServerHead(options.head, () =>\n withScope(createRootScope(renderId), () => escape(code())),\n );\n },\n }),\n );\n },\n });\n return ((view as () => unknown)() as () => string)();\n });\n return pass;\n };\n\n let rejectAbort: (reason: unknown) => void = () => undefined;\n const abort = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n timer = setTimeout(\n () =>\n reject(\n new SsrError(\"SSR_TIMEOUT\", `The stream did not finish within ${timeoutMs} ms.`),\n ),\n Math.min(timeoutMs, MAX_TIMER_MS),\n );\n });\n const onAbort = (): void =>\n rejectAbort(signal?.reason ?? new Error(\"The render was aborted.\"));\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n const cleanup = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n disposeAll();\n };\n // Wake a held shell or boundary immediately; late resource settlement must not render again.\n cancelRender = (reason) => {\n rejectAbort(reason);\n cleanup();\n };\n // Marks the abort handled for a render that has already finished (the stream closed, the timer\n // is cleared) and no longer awaits it. While the loop below awaits `abort`, its rejection is\n // rethrown there into `controller.error`, so a timeout or an abort is reported to the reader.\n abort.catch(() => undefined);\n\n try {\n if (signal?.aborted) throw signal.reason;\n // The shell is sent once the resources it holds have settled: a held render that finds a\n // value renders again with it, so the value is in the first chunk and not behind a fallback.\n let answer = renderPass();\n for (let round = 1; answer.held.length > 0; round += 1) {\n await Promise.race([abort, Promise.allSettled(answer.held.map((held) => held.entry))]);\n // No held value arrived (each held fetch failed): this render is the answer, with its fallbacks.\n if (!answer.held.some((held) => settled.has(held.key))) break;\n if (round >= MAX_SHELL_PASSES) {\n throw new SsrError(\n \"SSR_BOUNDARY_WATERFALL\",\n `Resources kept holding the stream after ${MAX_SHELL_PASSES} shell renders; flatten the data flow.`,\n );\n }\n answer = renderPass();\n }\n\n answer.answered = true;\n untrack(() => {\n for (const error of answer.caught) options.onCaughtError?.(error);\n for (const error of answer.uncaught) options.onUncaughtError?.(error);\n options.onShellReady?.(answer.html);\n });\n push(\n answer.boundaries.length > 0\n ? answer.html + script(SWAP_RUNTIME, options.nonce)\n : answer.html,\n );\n\n const failRemaining = (): void => {\n // Nothing can make progress (failed resources): leave the fallbacks for the client.\n for (const boundary of answer.boundaries.splice(0)) {\n push(\n `<template id=\"s:${boundary.id}\"></template>` +\n script(`$S(${JSON.stringify(boundary.id)},1)`, options.nonce),\n );\n }\n };\n let strikes = 0;\n while (answer.boundaries.length > 0) {\n if (answer.inFlight.size === 0) {\n failRemaining();\n break;\n }\n const settledBefore = settled.size;\n await Promise.race([abort, Promise.race([...answer.inFlight])]);\n const current = answer.boundaries;\n answer.boundaries = [];\n let emitted = false;\n for (const boundary of current) {\n const html = boundary.rebuild();\n if (html === null) continue;\n emitted = true;\n push(\n `<template id=\"s:${boundary.id}\">${html}</template>` +\n script(`$S(${JSON.stringify(boundary.id)})`, options.nonce),\n );\n }\n // Rounds that settle nothing new and emit nothing (only rejections) are bounded.\n strikes = settled.size === settledBefore && !emitted ? strikes + 1 : 0;\n if (answer.boundaries.length > 0 && strikes >= 2) failRemaining();\n }\n\n const data: Record<string, unknown> = {};\n for (const key of answer.requested) {\n if (!settled.has(key)) continue;\n Object.defineProperty(data, key, {\n value: settled.get(key),\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n if (Object.keys(data).length > 0) {\n push(`<script type=\"application/json\" data-sh=\"${renderId}\">${serialize(data)}</script>`);\n }\n cleanup();\n if (!canceled) controller.close();\n } catch (error) {\n cleanup();\n if (!canceled) controller.error(error);\n }\n },\n cancel(reason) {\n canceled = true;\n cancelRender(reason);\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA6EA,MAAM,YAAY;AAClB,MAAM,qBAAqB;;;;;AAK3B,MAAM,mBAAmB;;;;;;AA0BzB,MAAM,eACJ;AAOF,SAAS,OAAO,MAAc,OAAmC;CAG/D,OAAO,UADL,UAAU,KAAA,IAAY,KAAK,WAAW,MAAM,QAAQ,sBAAsB,EAAE,EAAE,GACrD,GAAG,KAAK;AACrC;;;;;;;;;;;;;;;;;;;;;;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AAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM;GAClC,SAAS,OAAO;IACd,QAAQ;IACR,IAAI,CAAC,UAAU,WAAW,MAAM,KAAK;GACvC;EACF;EACA,OAAO,QAAQ;GACb,WAAW;GACX,aAAa,MAAM;EACrB;CACF,CAAC;AACH"}
@@ -2,15 +2,16 @@ import { escape } from "./server/escape.js";
2
2
  import { ssrAttribute } from "./server/attributes.js";
3
3
  import { ssrClass, ssrStyle } from "./server/class-style.js";
4
4
  import { ssrSelectValue, ssrTextArea } from "./server/form-controls.js";
5
+ import { ssrRawText } from "./server/raw-text.js";
5
6
  import { ssr, ssrElement, ssrHydrationKey, ssrRaw } from "./server/element.js";
6
- import { createServerPortals } from "./server/portals.js";
7
7
  import { normalizeTags } from "./head/validate.js";
8
8
  import { createServerHead } from "./head/server-head.js";
9
9
  import { createComponent, memo } from "./server/component.js";
10
10
  import { derived } from "./server/derived.js";
11
11
  import { HydrationScript, generateHydrationScript } from "./server/hydration-script.js";
12
+ import { createServerPortals } from "./server/portals.js";
12
13
  import { renderToString, renderToStringAsync } from "./server/render.js";
13
14
  import { deserialize, serialize } from "./server/serialize.js";
14
15
  import { renderToStream } from "./server/stream.js";
15
16
  import { mergeProps } from "./server/index.js";
16
- export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrSelectValue, ssrStyle, ssrTextArea };
17
+ export { HydrationScript, createComponent, createServerHead, createServerPortals, derived, deserialize, escape, generateHydrationScript, memo, mergeProps, normalizeTags, renderToStream, renderToString, renderToStringAsync, serialize, ssr, ssrAttribute, ssrClass, ssrElement, ssrHydrationKey, ssrRaw, ssrRawText, ssrSelectValue, ssrStyle, ssrTextArea };