@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
@@ -33,11 +33,11 @@ function resolveValue(value) {
33
33
  }
34
34
  return current;
35
35
  }
36
- /** Writes the markup for one resolved value that is not an array. */
37
- function appendLeaf(value, out) {
36
+ /** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */
37
+ function appendLeaf(value, out, text) {
38
38
  if (value === null || value === void 0 || typeof value === "boolean") return;
39
39
  if (typeof value === "string") {
40
- out.push(escapeHtml(value));
40
+ out.push(text(value));
41
41
  return;
42
42
  }
43
43
  if (typeof value === "number" || typeof value === "bigint") {
@@ -50,7 +50,7 @@ function appendLeaf(value, out) {
50
50
  return;
51
51
  }
52
52
  if (typeof value === "object") throw invalid("UNRECOGNIZED_INSERT_VALUE", "A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.");
53
- out.push(escapeHtml(String(value)));
53
+ out.push(text(String(value)));
54
54
  }
55
55
  /**
56
56
  * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls
@@ -79,6 +79,14 @@ function appendLeaf(value, out) {
79
79
  * @since 1.0.0
80
80
  */
81
81
  function escape(value) {
82
+ return render(value, escapeHtml);
83
+ }
84
+ /**
85
+ * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and
86
+ * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).
87
+ * @internal
88
+ */
89
+ function render(value, text) {
82
90
  const out = [];
83
91
  const frames = [];
84
92
  const cursors = [];
@@ -91,7 +99,7 @@ function escape(value) {
91
99
  open.add(resolved);
92
100
  frames.push(resolved);
93
101
  cursors.push(0);
94
- } else appendLeaf(resolved, out);
102
+ } else appendLeaf(resolved, out, text);
95
103
  let next;
96
104
  let found = false;
97
105
  while (!found && frames.length > 0) {
@@ -113,6 +121,6 @@ function escape(value) {
113
121
  item = next;
114
122
  }
115
123
  }
116
- export { escape, escapeHtml, resolveValue };
124
+ export { escape, escapeHtml, render, resolveValue };
117
125
 
118
126
  //# sourceMappingURL=escape.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"escape.js","names":["accessor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array. */\nfunction appendLeaf(value: unknown, out: string[]): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(escapeHtml(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(escapeHtml(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, &lt;Ada&gt;3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors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,aAAa,IAAI;EAClC,IAAI,MAAM,QAAQ,QAAQ,GAAG;GAC3B,IAAI,KAAK,IAAI,QAAQ,GAAG,MAAM,IAAI,UAAU,qCAAqC;GACjF,KAAK,IAAI,QAAQ;GACjB,OAAO,KAAK,QAAQ;GACpB,QAAQ,KAAK,CAAC;EAChB,OACE,WAAW,UAAU,GAAG;EAG1B,IAAI;EACJ,IAAI,QAAQ;EACZ,OAAO,CAAC,SAAS,OAAO,SAAS,GAAG;GAClC,MAAM,MAAM,OAAO,SAAS;GAC5B,MAAM,QAAQ,OAAO;GACrB,MAAM,SAAS,QAAQ,QAAQ;GAC/B,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,SAAS,MAAM,QAAQ;IACzB,QAAQ,OAAO,SAAS;IACxB,OAAO,MAAM;IACb,QAAQ;GACV,OAAO;IACL,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,KAAK,OAAO,KAAK;GACnB;EACF;EACA,IAAI,CAAC,OAAO,OAAO,IAAI,KAAK,EAAE;EAC9B,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"escape.js","names":["accessor"],"sources":["../../../src/server/escape.ts"],"sourcesContent":["import { untrack } from \"@shadow-js/core\";\nimport { invalid } from \"./errors\";\nimport { isSsrNode } from \"./node\";\n\nconst HTML_ESCAPES: Readonly<Record<string, string>> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n};\n\nconst HTML_SPECIAL = /[&<>\"']/g;\n\n/** Longest chain of accessors that returns accessors; longer chains are a bug in user code. */\nconst MAX_ACCESSOR_LAYERS = 1000;\n\n/**\n * Escapes the five HTML-significant characters. Escaping `&` too means entity-looking text is\n * written literally, and the result is safe in text and in quoted attribute values alike.\n * @internal\n */\nexport function escapeHtml(text: string): string {\n return text.replace(HTML_SPECIAL, (char) => HTML_ESCAPES[char] ?? char);\n}\n\n/**\n * Calls accessors until a plain value remains. Accessors run untracked; a chain longer than\n * {@link MAX_ACCESSOR_LAYERS} throws instead of looping.\n * @internal\n */\nexport function resolveValue(value: unknown): unknown {\n let current = value;\n for (let layer = 0; typeof current === \"function\"; layer += 1) {\n if (layer >= MAX_ACCESSOR_LAYERS) {\n throw new TypeError(\"An accessor returns accessors more than 1000 levels deep.\");\n }\n const accessor = current as () => unknown;\n current = untrack(accessor);\n }\n return current;\n}\n\n/** Writes the markup for one resolved value that is not an array; `text` encodes the text of a string. */\nfunction appendLeaf(value: unknown, out: string[], text: (value: string) => string): void {\n if (value === null || value === undefined || typeof value === \"boolean\") return;\n if (typeof value === \"string\") {\n out.push(text(value));\n return;\n }\n // Numbers and bigints never contain markup characters.\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n out.push(String(value));\n return;\n }\n if (typeof value === \"symbol\") {\n throw invalid(\"UNRECOGNIZED_INSERT_VALUE\", \"A symbol cannot be rendered.\");\n }\n if (isSsrNode(value)) {\n out.push(value.t);\n return;\n }\n // Any other object is not trusted markup. Dev fails loudly; production renders nothing.\n if (typeof value === \"object\") {\n if (__DEV__) {\n throw invalid(\n \"UNRECOGNIZED_INSERT_VALUE\",\n \"A plain object cannot be rendered. Use a string, a number, an array or an SsrNode.\",\n );\n }\n return;\n }\n out.push(text(String(value)));\n}\n\n/**\n * Converts any value a JSX child may hold to escaped HTML: the helper compiled server output calls\n * for every dynamic child, and what the renderers call on the app's result.\n *\n * - Strings are escaped (`& < > \" '`); numbers and bigints are written as they are; `null`,\n * `undefined` and booleans render nothing.\n * - `SsrNode` values (from `ssr`, `ssrRaw` and the other helpers) pass through unchanged: they were\n * escaped when they were built.\n * - Accessors are called (untracked) and their result is rendered; a chain of more than 1000\n * accessors returning accessors throws.\n * - Arrays are flattened in order, with an explicit stack, so nesting depth is not limited by the\n * call stack.\n * - Plain objects throw in development builds and render nothing in production builds.\n *\n * @param value The value to render.\n * @returns The escaped markup.\n * @throws TypeError when an array contains itself, for a symbol (`UNRECOGNIZED_INSERT_VALUE`), for an\n * object that is not an `SsrNode` (`UNRECOGNIZED_INSERT_VALUE`, development builds only), and for an\n * accessor chain deeper than 1000.\n * @example\n * import { escape } from \"@shadow-js/web/server\";\n *\n * const name = () => \"<Ada>\";\n * escape([\"Hello, \", name, null, 3]); // \"Hello, &lt;Ada&gt;3\"\n * @since 1.0.0\n */\n// biome-ignore lint/suspicious/noShadowRestrictedNames: the name \"escape\" is part of the compiler contract (SSR output).\nexport function escape(value: unknown): string {\n return render(value, escapeHtml);\n}\n\n/**\n * {@link escape} with the encoding of strings left to the caller: the walk over accessors, arrays and\n * trusted nodes that every kind of text shares (an element's text is encoded one way, a script's another).\n * @internal\n */\nexport function render(value: unknown, text: (value: string) => string): string {\n const out: string[] = [];\n const frames: unknown[][] = [];\n const cursors: number[] = [];\n const open = new Set<unknown[]>();\n let item: unknown = value;\n for (;;) {\n const resolved = resolveValue(item);\n if (Array.isArray(resolved)) {\n if (open.has(resolved)) throw new TypeError(\"escape(): an array contains itself.\");\n open.add(resolved);\n frames.push(resolved);\n cursors.push(0);\n } else {\n appendLeaf(resolved, out, text);\n }\n // Find the next item, closing every array that has no items left.\n let next: unknown;\n let found = false;\n while (!found && frames.length > 0) {\n const top = frames.length - 1;\n const frame = frames[top];\n const cursor = cursors[top] ?? 0;\n if (frame === undefined) break;\n if (cursor < frame.length) {\n cursors[top] = cursor + 1;\n next = frame[cursor];\n found = true;\n } else {\n frames.pop();\n cursors.pop();\n open.delete(frame);\n }\n }\n if (!found) return out.join(\"\");\n item = next;\n }\n}\n"],"mappings":";;;;AAIA,MAAM,eAAiD;CACrD,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;AACP;AAEA,MAAM,eAAe;;AAGrB,MAAM,sBAAsB;;;;;;AAO5B,SAAgB,WAAW,MAAsB;CAC/C,OAAO,KAAK,QAAQ,eAAe,SAAS,aAAa,SAAS,IAAI;AACxE;;;;;;AAOA,SAAgB,aAAa,OAAyB;CACpD,IAAI,UAAU;CACd,KAAK,I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O,CAAC,SAAS,OAAO,SAAS,GAAG;GAClC,MAAM,MAAM,OAAO,SAAS;GAC5B,MAAM,QAAQ,OAAO;GACrB,MAAM,SAAS,QAAQ,QAAQ;GAC/B,IAAI,UAAU,KAAA,GAAW;GACzB,IAAI,SAAS,MAAM,QAAQ;IACzB,QAAQ,OAAO,SAAS;IACxB,OAAO,MAAM;IACb,QAAQ;GACV,OAAO;IACL,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,KAAK,OAAO,KAAK;GACnB;EACF;EACA,IAAI,CAAC,OAAO,OAAO,IAAI,KAAK,EAAE;EAC9B,OAAO;CACT;AACF"}
@@ -19,7 +19,10 @@ function valueText(value) {
19
19
  * @internal
20
20
  */
21
21
  function textareaContent(value) {
22
- const html = escapeHtml(valueText(resolveValue(value)));
22
+ return keepLeadingNewline(escapeHtml(valueText(resolveValue(value))));
23
+ }
24
+ /** Content markup of a textarea with the line break its parser would drop kept. @internal */
25
+ function keepLeadingNewline(html) {
23
26
  const first = html.charAt(0);
24
27
  return first === "\n" || first === "\r" ? `\n${html}` : html;
25
28
  }
@@ -187,6 +190,6 @@ function ssrSelectValue(value, children) {
187
190
  function markSelectedOptions(value, html) {
188
191
  return markOptions(html, wantedValues(value));
189
192
  }
190
- export { markSelectedOptions, ssrSelectValue, ssrTextArea, textareaContent };
193
+ export { keepLeadingNewline, markSelectedOptions, ssrSelectValue, ssrTextArea, textareaContent };
191
194
 
192
195
  //# sourceMappingURL=form-controls.js.map
@@ -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): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,0CAA0C;CAEvF,OAAO,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;AAClE;;;;;;AAOA,SAAgB,gBAAgB,OAAwB;CACtD,MAAM,OAAO,WAAW,UAAU,aAAa,KAAK,CAAC,CAA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B,cAAc,MAAM,QAAQ,MAAM,EAAE,CAAC;GACvC,OAAO,IAAI,SAAS,WAAW,UAAU,KAAA,GACvC,QAAQ,eAAe,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,EAAE;EAEjE;EAEA,MAAM,WACH,OAAO,QAAQ,CAAC,UAAU,OAAO,OAAO,IAAI,SAAS,WAAW,MAAM,MAAM,GAAG,UAAU,CAAC;EAC7F,IAAI,SAAS,QAAQ;EACrB,IAAI,WAAW,eAAe,IAAI;GAChC,MAAM,QAAQ,OAAO,SAAS,GAAG,IAAI,OAAO,SAAS,IAAI,OAAO;GAChE,OAAO,GAAG,KAAK,MAAM,QAAQ,iBAAiB,KAAK,EAAE;GACrD,SAAS,iBAAiB;EAC5B,OAAO,IAAI,CAAC,WAAW,eAAe,IAAI;GACxC,OAAO,KAAK,MAAM,QAAQ,iBAAiB,UAAU;GACrD,SAAS,iBAAiB;EAC5B;EACA,KAAK;CACP;CACA,OAAO,WAAW,IAAI,OAAO,MAAM,KAAK,MAAM,MAAM;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,eAAe,OAAgB,UAA4B;CACzE,OAAO,IAAI,QAAQ,oBAAoB,OAAO,OAAO,QAAQ,CAAC,CAAC;AACjE;;AAGA,SAAgB,oBAAoB,OAAgB,MAAsB;CACxE,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC;AAC9C"}
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 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 markSelectedOptions(value: unknown, html: string): string {\n return markOptions(html, wantedValues(value));\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,UAAU,OAAwB;CACzC,IAAI,OAAO,UAAU,UACnB,MAAM,QAAQ,6BAA6B,0CAA0C;CAEvF,OAAO,UAAU,QAAQ,UAAU,KAAA,IAAY,KAAK,OAAO,KAAK;AAClE;;;;;;AAOA,SAAgB,gBAAgB,OAAwB;CACtD,OAAO,mBAAmB,WAAW,UAAU,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AAA,CAAI,YAAY;GAC1C,IAAI,SAAS,YAAY;IACvB,aAAa,MAAM;IACnB,cAAc,MAAM,QAAQ,MAAM,EAAE,CAAC;GACvC,OAAO,IAAI,SAAS,WAAW,UAAU,KAAA,GACvC,QAAQ,eAAe,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,EAAE;EAEjE;EAEA,MAAM,WACH,OAAO,QAAQ,CAAC,UAAU,OAAO,OAAO,IAAI,SAAS,WAAW,MAAM,MAAM,GAAG,UAAU,CAAC;EAC7F,IAAI,SAAS,QAAQ;EACrB,IAAI,WAAW,eAAe,IAAI;GAChC,MAAM,QAAQ,OAAO,SAAS,GAAG,IAAI,OAAO,SAAS,IAAI,OAAO;GAChE,OAAO,GAAG,KAAK,MAAM,QAAQ,iBAAiB,KAAK,EAAE;GACrD,SAAS,iBAAiB;EAC5B,OAAO,IAAI,CAAC,WAAW,eAAe,IAAI;GACxC,OAAO,KAAK,MAAM,QAAQ,iBAAiB,UAAU;GACrD,SAAS,iBAAiB;EAC5B;EACA,KAAK;CACP;CACA,OAAO,WAAW,IAAI,OAAO,MAAM,KAAK,MAAM,MAAM;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,eAAe,OAAgB,UAA4B;CACzE,OAAO,IAAI,QAAQ,oBAAoB,OAAO,OAAO,QAAQ,CAAC,CAAC;AACjE;;AAGA,SAAgB,oBAAoB,OAAgB,MAAsB;CACxE,OAAO,YAAY,MAAM,aAAa,KAAK,CAAC;AAC9C"}
@@ -9,8 +9,9 @@ import { escape } from "./escape.js";
9
9
  import { ssrSelectValue, ssrTextArea } from "./form-controls.js";
10
10
  import { HydrationScript, HydrationScriptOptions, generateHydrationScript } from "./hydration-script.js";
11
11
  import { ServerPortals, createServerPortals } from "./portals.js";
12
+ import { ssrRawText } from "./raw-text.js";
12
13
  import { AsyncRenderOptions, AsyncRenderResult, RenderOptions, renderToString, renderToStringAsync } from "./render.js";
13
14
  import { deserialize, serialize } from "./serialize.js";
14
15
  import { StreamOptions, renderToStream } from "./stream.js";
15
16
  import { mergeProps as mergeProps$1 } from "@shadow-js/core";
16
- export { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, 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 { type AsyncRenderOptions, type AsyncRenderResult, type Derived, HydrationScript, type HydrationScriptOptions, type NormalizedTag, type RenderOptions, type ServerHead, type ServerPortals, type StreamOptions, 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 };
@@ -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,KAC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the helper compiled server output calls for a
4
+ * dynamic child of one. The browser reads these elements' content as raw text, so the value is written
5
+ * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region
6
+ * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of
7
+ * the element, in any letter case (`</style`, `<\/SCRIPT`), and `<!--` in a script, would end the element
8
+ * early or hide its end, so each is rewritten (`<\/style`, `<\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.
9
+ *
10
+ * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and
11
+ * a symbol throws, as in {@link escape}.
12
+ *
13
+ * @param tag The element, `"script"` or `"style"` (any letter case).
14
+ * @param value The child value: a string, a number, an array, an accessor or `null`.
15
+ * @returns The text as a trusted `SsrNode`.
16
+ * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of
17
+ * {@link escape} for the value.
18
+ * @example
19
+ * import { renderToString, ssr, ssrRawText } from "@shadow-js/web/server";
20
+ *
21
+ * const css = "a > b { color: red } </style><script>alert(1)<\/script>";
22
+ * const html = renderToString(() => ssr(["<style>", "</style>"], ssrRawText("style", css)));
23
+ * // "<style>a > b { color: red } <\/style><script>alert(1)<\/script></style>"
24
+ * @see escape
25
+ * @since 1.0.2
26
+ */
27
+ export declare function ssrRawText(tag: "script" | "style", value: unknown): SsrNode;
28
+ //# sourceMappingURL=raw-text.d.ts.map
@@ -0,0 +1,66 @@
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
+ /** The elements whose text the parser reads raw. */
6
+ const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set(["script", "style"]);
7
+ /** The closing tag of a script or style in any case, and the `<!--` that opens a script's double-escaped state. */
8
+ const CLOSING_TAG = {
9
+ script: /<\/(script)|<!--/gi,
10
+ style: /<\/(style)/gi
11
+ };
12
+ /**
13
+ * Keeps raw text from ending its element or the script data state. `<\/script` and `</style` get a backslash that
14
+ * CSS, JavaScript and JSON all read as the character itself (`<\/style` is `</style` in a string, a comment or a
15
+ * selector escape), and `<!--` in a script becomes `<\u0021--`: `\!` is no JSON escape, and a script that holds
16
+ * JSON data (`application/json`, `ld+json`) must still parse. The text means what it meant and the parser does
17
+ * not see a tag. Entities would instead change the text: raw text has none.
18
+ */
19
+ function neutralize(tag, text) {
20
+ return text.replace(CLOSING_TAG[tag], (match) => match === "<!--" ? "<\\u0021--" : `<\\/${match.slice(2)}`);
21
+ }
22
+ /** The text of a child value for a `script` or `style`: strings unescaped, the whole checked by {@link neutralize}. @internal */
23
+ function rawTextContent(tag, value) {
24
+ return neutralize(tag.toLowerCase() === "script" ? "script" : "style", render(value, (text) => text));
25
+ }
26
+ /**
27
+ * The content of a `script` or `style` element made by `ssrElement`. A node the compiler built (`ssr`, `ssrRaw`)
28
+ * is the application's own markup and is left as it is; any other value is raw text and is checked.
29
+ * @internal
30
+ */
31
+ function rawElementContent(tag, value) {
32
+ const resolved = resolveValue(value);
33
+ return isSsrNode(resolved) ? resolved.t : rawTextContent(tag, resolved);
34
+ }
35
+ /**
36
+ * Writes the children of a `<script>` or `<style>` element: the helper compiled server output calls for a
37
+ * dynamic child of one. The browser reads these elements' content as raw text, so the value is written
38
+ * as it is (`a > b` stays `a > b`; HTML entities would corrupt the stylesheet or the code) with no region
39
+ * markers around it, and the client adopts the text when it hydrates. Only one thing is changed: a closing tag of
40
+ * the element, in any letter case (`</style`, `<\/SCRIPT`), and `<!--` in a script, would end the element
41
+ * early or hide its end, so each is rewritten (`<\/style`, `<\u0021--`) to text that CSS, JavaScript and JSON read as the same characters.
42
+ *
43
+ * Accessors are called untracked, arrays are flattened, `null`, `undefined` and booleans write nothing, and
44
+ * a symbol throws, as in {@link escape}.
45
+ *
46
+ * @param tag The element, `"script"` or `"style"` (any letter case).
47
+ * @param value The child value: a string, a number, an array, an accessor or `null`.
48
+ * @returns The text as a trusted `SsrNode`.
49
+ * @throws TypeError `INVALID_RAW_TEXT_TAG` when `tag` is not `script` or `style`, and the errors of
50
+ * {@link escape} for the value.
51
+ * @example
52
+ * import { renderToString, ssr, ssrRawText } from "@shadow-js/web/server";
53
+ *
54
+ * const css = "a > b { color: red } </style><script>alert(1)<\/script>";
55
+ * const html = renderToString(() => ssr(["<style>", "</style>"], ssrRawText("style", css)));
56
+ * // "<style>a > b { color: red } <\/style><script>alert(1)<\/script></style>"
57
+ * @see escape
58
+ * @since 1.0.2
59
+ */
60
+ function ssrRawText(tag, value) {
61
+ if (typeof tag !== "string" || !RAW_TEXT_ELEMENTS.has(tag.toLowerCase())) throw invalid("INVALID_RAW_TEXT_TAG", "ssrRawText(): the tag must be script or style.");
62
+ return new SsrNode(rawTextContent(tag, value));
63
+ }
64
+ export { rawElementContent, rawTextContent, ssrRawText };
65
+
66
+ //# 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":";;;;;AAsBA,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"}
@@ -44,7 +44,8 @@ export interface RenderOptions {
44
44
  */
45
45
  export interface AsyncRenderOptions extends RenderOptions {
46
46
  /**
47
- * Upper bound for the whole render, in milliseconds: a positive finite number.
47
+ * Upper bound for the whole render, in milliseconds: a positive finite number. Values above the
48
+ * timer range (2147483647, about 24.8 days) count as 2147483647.
48
49
  * @default 10000
49
50
  */
50
51
  readonly timeoutMs?: number;
@@ -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,oEAAo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G;CACvD,MAAM,EAAE,WAAW,cAAc,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,O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AI;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"}
@@ -17,7 +17,7 @@ export interface StreamOptions {
17
17
  */
18
18
  readonly nonce?: string;
19
19
  /**
20
- * Upper bound for the whole stream, in milliseconds, a positive finite number. When it runs out, the stream errors with an
20
+ * 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
21
21
  * `SsrError` whose `code` is `SSR_TIMEOUT`.
22
22
  * @default 30000
23
23
  */
@@ -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 });