reactive-md 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/CHANGELOG-ch.md +333 -319
  2. package/CHANGELOG.md +334 -320
  3. package/CONTRIBUTING-ch.md +22 -22
  4. package/CONTRIBUTING.md +22 -22
  5. package/README-ch.md +431 -431
  6. package/README-en.md +431 -431
  7. package/README.md +429 -429
  8. package/SECURITY-ch.md +83 -83
  9. package/SECURITY.md +83 -83
  10. package/bin/reactive-md.mjs +39 -39
  11. package/cli/args.mjs +263 -263
  12. package/cli/assets.mjs +395 -395
  13. package/cli/build.mjs +445 -445
  14. package/cli/check.mjs +444 -444
  15. package/cli/document.mjs +130 -130
  16. package/cli/errors.mjs +61 -61
  17. package/cli/fs-utils.mjs +133 -133
  18. package/cli/glob.mjs +203 -203
  19. package/cli/help.mjs +323 -323
  20. package/cli/init.mjs +1577 -1577
  21. package/cli/lint.mjs +177 -177
  22. package/cli/main.mjs +65 -65
  23. package/cli/migrate.mjs +368 -368
  24. package/cli/package-loader.mjs +41 -41
  25. package/cli/package.mjs +211 -211
  26. package/dist-library/{LocalDocumentView-sthUP0ct.js → LocalDocumentView-BuqgJZEY.js} +11 -11
  27. package/dist-library/{LocalDocumentViewCore-GiWV3bey.js → LocalDocumentViewCore-DXE0I0Qc.js} +210 -209
  28. package/dist-library/{LocalReactiveDocumentCore-ZjQSGyHE.js → LocalReactiveDocumentCore-CWBe4Mm5.js} +8 -8
  29. package/dist-library/{authoring-Dsune4Hy.js → authoring-Ci_KzJ0q.js} +53 -53
  30. package/dist-library/{compile-wUv8KEge.js → compile-Dx6Uw3D9.js} +11 -11
  31. package/dist-library/{compiler-core-As_m-MNm.js → compiler-core-DDDdvuLy.js} +883 -818
  32. package/dist-library/compiler-dxLPB9Ym.js +86 -0
  33. package/dist-library/{component-state-C52ZFJGl.js → component-state-BRwvTV0d.js} +15 -14
  34. package/dist-library/component-state-CwKX_SN5.js +763 -0
  35. package/dist-library/{config-BadfhjdP.js → config-DXLvctiZ.js} +68 -66
  36. package/dist-library/config-validation-D3D7Dy2J.js +586 -0
  37. package/dist-library/{controls-CcT6n7k_.js → controls-DoZyLCrV.js} +3 -3
  38. package/dist-library/{coordinate-CWS9p5q_.js → coordinate-B1VFK9fd.js} +2 -2
  39. package/dist-library/{data-table-Bgccxd7h.js → data-table-8-3F15Jf.js} +3 -3
  40. package/dist-library/{default-components-BwQf0oP-.js → default-components-s21NevON.js} +29 -28
  41. package/dist-library/{display-B-VhqVND.js → display-B_uutKkN.js} +1 -1
  42. package/dist-library/{config-validation-F47AcE6o.js → document-theme-C8J6UyNO.js} +193 -731
  43. package/dist-library/{export-BqVmTXm8.js → export-CIAIPBov.js} +35 -34
  44. package/dist-library/{gallery-CY6mTx8i.js → gallery-Dv1rOvL0.js} +1 -1
  45. package/dist-library/{html-CNT4KD-2.js → html-Cr4CBwAH.js} +42 -41
  46. package/dist-library/identity-BUx0Q_-d.js +40 -0
  47. package/dist-library/{incremental-Dv0FSp_U.js → incremental-9nx92u9c.js} +12 -10
  48. package/dist-library/{layout-C0YlEPGr.js → layout-BBB2VF0S.js} +1 -1
  49. package/dist-library/{mount-preset-KxvtKgJb.js → mount-preset-DMZ5wd3t.js} +3 -3
  50. package/dist-library/observability-4KqXhIEU.js +421 -0
  51. package/dist-library/observability-core-Bcu7vpnl.js +24 -0
  52. package/dist-library/{options-1aDLK7JY.js → options-BBp9IcHm.js} +4 -4
  53. package/dist-library/{package-core-WFK1RhAZ.js → package-core-K5xesGqy.js} +30 -29
  54. package/dist-library/{parser-standard-Yuf3A_VI.js → parser-standard-CBA1-hdG.js} +352 -352
  55. package/dist-library/{plugin-packs-B1XPWcFs.js → plugin-packs-Bh1HhLym.js} +3 -2
  56. package/dist-library/preset-core-DeZPA8IE.js +1298 -0
  57. package/dist-library/react-0DCh-Mar.js +7 -0
  58. package/dist-library/reactive-md-authoring.js +19 -19
  59. package/dist-library/reactive-md-build.js +48 -10
  60. package/dist-library/reactive-md-compiler-standard.js +6 -6
  61. package/dist-library/reactive-md-compiler.js +3 -3
  62. package/dist-library/reactive-md-default-packs.js +3 -2
  63. package/dist-library/reactive-md-default-preset.js +3 -2
  64. package/dist-library/reactive-md-export.js +4 -4
  65. package/dist-library/reactive-md-minimal-preset.js +2 -2
  66. package/dist-library/reactive-md-minimal-react-preset.js +3 -3
  67. package/dist-library/reactive-md-observability.js +4 -0
  68. package/dist-library/reactive-md-plugin-chart.js +3 -3
  69. package/dist-library/reactive-md-plugin-data.js +5 -5
  70. package/dist-library/reactive-md-plugin-diagram.js +4 -4
  71. package/dist-library/reactive-md-plugin-forms.js +4 -4
  72. package/dist-library/reactive-md-plugin-gallery.js +3 -3
  73. package/dist-library/reactive-md-plugin-navigation.js +3 -3
  74. package/dist-library/reactive-md-plugin-network.js +4 -3
  75. package/dist-library/reactive-md-plugin-plot.js +4 -4
  76. package/dist-library/reactive-md-print.css +304 -304
  77. package/dist-library/reactive-md-react-minimal.js +4 -4
  78. package/dist-library/reactive-md-react-server.js +6 -6
  79. package/dist-library/reactive-md-react-unstyled.js +11 -11
  80. package/dist-library/reactive-md-react.js +11 -11
  81. package/dist-library/reactive-md-runtime-browser.js +2 -1
  82. package/dist-library/reactive-md-runtime.js +4 -3
  83. package/dist-library/reactive-md-sdk.js +8 -7
  84. package/dist-library/reactive-md-standalone-configured.js +2 -2
  85. package/dist-library/reactive-md-standalone-host.js +2 -2
  86. package/dist-library/reactive-md-testing-browser.js +2 -2
  87. package/dist-library/reactive-md-testing-react.js +6 -6
  88. package/dist-library/reactive-md-testing.js +5 -5
  89. package/dist-library/reactive-md.js +556 -367
  90. package/dist-library/{registry-B9NGct4d.js → registry-D6OGkOcX.js} +3 -3
  91. package/dist-library/{registry-core-Bbad9Bm2.js → registry-core-C9xOunaw.js} +1 -1
  92. package/dist-library/{resources-D2GDQS0p.js → resources-B0x_w3s9.js} +71 -46
  93. package/dist-library/{runtime-B2fxeveq.js → runtime-BDnnimPA.js} +17 -16
  94. package/dist-library/{runtime-kcA7bG7G.js → runtime-BpQdZmFI.js} +311 -305
  95. package/dist-library/{schema-BufhKUSM.js → schema-BryM_VRW.js} +14 -14
  96. package/dist-library/{sdk-core-BoJT1SIt.js → sdk-core-ChslheKs.js} +33 -32
  97. package/dist-library/{session-core-nmJHuR9c.js → session-core-dxQCJBNa.js} +15 -14
  98. package/dist-library/{shareable-DpbE-59H.js → shareable-B8xMoGEa.js} +179 -176
  99. package/dist-library/types/build/diagnostics.d.ts +1 -1
  100. package/dist-library/types/local/index.d.ts +6 -0
  101. package/dist-library/types/local/observability-codes.d.ts +2 -0
  102. package/dist-library/types/local/observability-core.d.ts +25 -0
  103. package/dist-library/types/local/observability-messages.d.ts +6 -0
  104. package/dist-library/types/local/observability.d.ts +43 -0
  105. package/dist-library/types/local/parsing/parser-internals.d.ts +2 -1
  106. package/dist-library/types/local/transport/worker.d.ts +52 -1
  107. package/dist-library/types/local/types.d.ts +8 -0
  108. package/dist-library/types/observability.d.ts +7 -0
  109. package/dist-library/{types-BeNtPqdY.js → types-Ib5kSScP.js} +1 -1
  110. package/dist-library/types-daDo2c_w.js +3 -0
  111. package/dist-library/{validation-BEBA_HvS.js → validation-B3RI0xOk.js} +251 -249
  112. package/dist-library/version-DAxuGOG2.js +147 -0
  113. package/dist-library/{visual-frame-CyV1FXzs.js → visual-frame-_rcd5HUv.js} +1 -1
  114. package/dist-library/{visuals-BZbZYA7w.js → visuals-DkDhNdEZ.js} +17 -17
  115. package/dist-standalone/reactive-md-standalone.js +118 -118
  116. package/docs/README-ch.md +101 -95
  117. package/docs/README.md +101 -95
  118. package/docs/compatibility/api-stability-ch.md +25 -0
  119. package/docs/compatibility/api-stability-en.md +25 -0
  120. package/docs/compatibility/compatibility-ch.md +146 -129
  121. package/docs/compatibility/compatibility-en.md +146 -129
  122. package/docs/compatibility/compatibility-manifest.schema.json +161 -0
  123. package/docs/compatibility/deprecation-ch.md +21 -0
  124. package/docs/compatibility/deprecation-en.md +21 -0
  125. package/docs/compatibility/source-versioning-ch.md +162 -162
  126. package/docs/compatibility/source-versioning-en.md +162 -162
  127. package/docs/compatibility/support-matrix-ch.md +108 -0
  128. package/docs/compatibility/support-matrix-en.md +108 -0
  129. package/docs/development/component-development-ch.md +66 -66
  130. package/docs/development/component-development-en.md +66 -66
  131. package/docs/development/component-development-reference-ch.md +253 -253
  132. package/docs/development/component-development-reference-en.md +238 -238
  133. package/docs/development/component-protocol-ch.md +748 -748
  134. package/docs/development/component-protocol-en.md +750 -750
  135. package/docs/development/extension-tutorial-ch.md +308 -308
  136. package/docs/development/extension-tutorial-en.md +308 -308
  137. package/docs/development/performance-overview-ch.md +422 -422
  138. package/docs/development/performance-overview-en.md +422 -422
  139. package/docs/guides/local-guide-ch.md +532 -532
  140. package/docs/guides/local-guide-en.md +532 -532
  141. package/docs/integration/author-tools-ch.md +64 -64
  142. package/docs/integration/author-tools-en.md +64 -64
  143. package/docs/integration/compiler-ch.md +49 -49
  144. package/docs/integration/compiler-en.md +36 -36
  145. package/docs/integration/directory-discovery-en.md +1 -1
  146. package/docs/integration/editor-ch.md +295 -295
  147. package/docs/integration/editor-en.md +303 -303
  148. package/docs/integration/extension-sdk-ch.md +394 -394
  149. package/docs/integration/extension-sdk-en.md +379 -379
  150. package/docs/integration/local-integration-ch.md +646 -646
  151. package/docs/integration/local-integration-en.md +662 -662
  152. package/docs/integration/shareable-export-ch.md +307 -307
  153. package/docs/integration/shareable-export-en.md +309 -309
  154. package/docs/reference/diagnostics-counting-ch.md +104 -104
  155. package/docs/reference/diagnostics-counting-en.md +104 -104
  156. package/docs/reference/html-compatibility-ch.md +93 -93
  157. package/docs/reference/html-compatibility-en.md +95 -95
  158. package/docs/reference/local-interaction-syntax-ch.md +724 -724
  159. package/docs/reference/local-interaction-syntax-en.md +722 -722
  160. package/docs/reference/public-api-ch.md +33 -4
  161. package/docs/reference/public-api-en.md +33 -4
  162. package/docs/reference/theme-protocol-ch.md +198 -198
  163. package/docs/reference/theme-protocol-en.md +217 -217
  164. package/docs/releases/release-0.4.0-ch.md +91 -91
  165. package/docs/releases/release-0.4.0-en.md +91 -91
  166. package/docs/releases/release-0.4.1-ch.md +25 -25
  167. package/docs/releases/release-0.4.1-en.md +25 -25
  168. package/docs/releases/release-0.5.0-ch.md +43 -43
  169. package/docs/releases/release-0.5.0-en.md +43 -43
  170. package/docs/releases/release-0.5.1-ch.md +41 -41
  171. package/docs/releases/release-0.5.1-en.md +41 -41
  172. package/docs/releases/release-0.5.2-ch.md +37 -37
  173. package/docs/releases/release-0.5.2-en.md +37 -37
  174. package/docs/releases/release-0.5.3-ch.md +26 -26
  175. package/docs/releases/release-0.5.3-en.md +26 -26
  176. package/docs/releases/release-0.6.0-ch.md +59 -59
  177. package/docs/releases/release-0.6.0-en.md +59 -59
  178. package/docs/releases/release-0.6.1-ch.md +29 -29
  179. package/docs/releases/release-0.6.1-en.md +29 -29
  180. package/docs/releases/release-0.7.0-ch.md +86 -86
  181. package/docs/releases/release-0.7.0-en.md +86 -86
  182. package/docs/releases/release-0.9.2-ch.md +33 -0
  183. package/docs/releases/release-0.9.2-en.md +33 -0
  184. package/examples/component-package/README-ch.md +101 -101
  185. package/examples/component-package/README.md +133 -133
  186. package/examples/conformance/README-ch.md +55 -55
  187. package/examples/conformance/README.md +55 -55
  188. package/examples/conformance/component-protocol-1.json +482 -482
  189. package/examples/conformance/component-protocol-1.schema.json +76 -76
  190. package/examples/conformance/local-draft-1.json +50 -50
  191. package/examples/conformance/local-draft-2.json +212 -212
  192. package/examples/game-2048-package/LICENSE +21 -21
  193. package/examples/game-2048-package/NOTICES.md +11 -11
  194. package/examples/game-2048-package/README-ch.md +91 -91
  195. package/examples/game-2048-package/README.md +98 -98
  196. package/examples/game-2048-package/package.json +35 -35
  197. package/examples/game-2048-package/sample/document.reactive.md +17 -17
  198. package/examples/game-2048-package/scripts/build-export.mjs +44 -44
  199. package/examples/game-2048-package/scripts/build.mjs +130 -130
  200. package/examples/game-2048-package/scripts/verify.mjs +180 -180
  201. package/examples/game-2048-package/src/component.css +161 -161
  202. package/examples/game-2048-package/src/components.tsx +326 -326
  203. package/examples/game-2048-package/src/game-engine.ts +228 -228
  204. package/examples/game-2048-package/src/harness.tsx +34 -34
  205. package/examples/game-2048-package/src/manifest.ts +85 -85
  206. package/examples/game-2048-package/src/node-entry.ts +30 -30
  207. package/examples/game-2048-package/src/sample.ts +4 -4
  208. package/examples/game-2048-package/tsconfig.json +15 -15
  209. package/examples/integration/README-ch.md +82 -82
  210. package/examples/integration/README.md +82 -82
  211. package/examples/integration/core/index.mjs +32 -32
  212. package/examples/integration/extension-sdk/README-ch.md +24 -24
  213. package/examples/integration/extension-sdk/README.md +24 -24
  214. package/examples/integration/worker/index.html +19 -19
  215. package/examples/integration/worker/main.js +61 -61
  216. package/examples/integration/worker/package.json +13 -13
  217. package/examples/integration/worker/worker.js +3 -3
  218. package/examples/local/README-ch.md +76 -76
  219. package/examples/local/README.md +76 -76
  220. package/examples/local/charts.reactive.md +73 -73
  221. package/examples/local/recipes/invoice-zh.reactive.md +36 -36
  222. package/examples/local/recipes/invoice.reactive.md +36 -36
  223. package/examples/local/recipes/workshop-zh.reactive.md +33 -33
  224. package/examples/local/recipes/workshop.reactive.md +33 -33
  225. package/examples/local/showcase/README-ch.md +22 -22
  226. package/examples/local/showcase/README.md +31 -31
  227. package/examples/local/showcase/explore.reactive.md +102 -102
  228. package/examples/local/showcase/flow.reactive.md +86 -86
  229. package/examples/local/showcase/forms.reactive.md +126 -126
  230. package/examples/local/showcase/functions.reactive.md +119 -119
  231. package/examples/local/showcase/layout.reactive.md +100 -100
  232. package/examples/local/showcase/statistics.reactive.md +108 -108
  233. package/examples/local/showcase/tasks.reactive.md +89 -89
  234. package/examples/local/showcase/zh/explore.reactive.md +102 -102
  235. package/examples/local/showcase/zh/flow.reactive.md +86 -86
  236. package/examples/local/showcase/zh/forms.reactive.md +126 -126
  237. package/examples/local/showcase/zh/functions.reactive.md +119 -119
  238. package/examples/local/showcase/zh/layout.reactive.md +100 -100
  239. package/examples/local/showcase/zh/statistics.reactive.md +108 -108
  240. package/examples/local/showcase/zh/tasks.reactive.md +89 -89
  241. package/examples/minimal-extension/README-ch.md +78 -78
  242. package/examples/minimal-extension/README.md +78 -78
  243. package/examples/minimal-extension/index.html +15 -15
  244. package/examples/minimal-extension/package.json +26 -26
  245. package/examples/minimal-extension/sample/document.reactive.md +10 -10
  246. package/examples/minimal-extension/scripts/build.mjs +32 -32
  247. package/examples/minimal-extension/scripts/export.mjs +72 -72
  248. package/examples/minimal-extension/scripts/test-node.mjs +75 -75
  249. package/examples/minimal-extension/src/extension.tsx +90 -90
  250. package/examples/minimal-extension/src/preview.tsx +12 -12
  251. package/examples/minimal-extension/src/source.ts +4 -4
  252. package/examples/minimal-extension/tsconfig.json +14 -14
  253. package/examples/sci-fi-theme/README-ch.md +133 -133
  254. package/examples/sci-fi-theme/README.md +148 -148
  255. package/examples/sci-fi-theme/demo/acceptance.reactive.md +454 -454
  256. package/examples/sci-fi-theme/demo/demo.css +638 -638
  257. package/examples/sci-fi-theme/demo/document.reactive.md +206 -206
  258. package/examples/sci-fi-theme/demo/index.html +13 -13
  259. package/examples/sci-fi-theme/demo/main.tsx +215 -215
  260. package/examples/sci-fi-theme/docs/design-system-ch.md +245 -245
  261. package/examples/sci-fi-theme/docs/design-system.md +474 -474
  262. package/examples/sci-fi-theme/package.json +28 -28
  263. package/examples/sci-fi-theme/scripts/screenshot.mjs +98 -98
  264. package/examples/sci-fi-theme/src/components.css +2370 -2370
  265. package/examples/sci-fi-theme/src/index.ts +6 -6
  266. package/examples/sci-fi-theme/src/notch.css +142 -142
  267. package/examples/sci-fi-theme/src/sci-fi.css +7 -7
  268. package/examples/sci-fi-theme/src/theme.ts +39 -39
  269. package/examples/sci-fi-theme/tsconfig.json +20 -20
  270. package/examples/sci-fi-theme/vite.config.ts +24 -24
  271. package/examples/tetris-package/LICENSE +21 -21
  272. package/examples/tetris-package/NOTICES.md +11 -11
  273. package/examples/tetris-package/README-ch.md +91 -91
  274. package/examples/tetris-package/README.md +95 -95
  275. package/examples/tetris-package/package.json +35 -35
  276. package/examples/tetris-package/sample/document.reactive.md +16 -16
  277. package/examples/tetris-package/scripts/build-export.mjs +44 -44
  278. package/examples/tetris-package/scripts/build.mjs +130 -130
  279. package/examples/tetris-package/scripts/verify.mjs +173 -173
  280. package/examples/tetris-package/src/component.css +145 -145
  281. package/examples/tetris-package/src/components.tsx +334 -334
  282. package/examples/tetris-package/src/harness.tsx +34 -34
  283. package/examples/tetris-package/src/manifests.ts +93 -93
  284. package/examples/tetris-package/src/node-entry.ts +16 -16
  285. package/examples/tetris-package/src/sample.ts +4 -4
  286. package/examples/tetris-package/src/tetris-engine.ts +325 -325
  287. package/examples/tetris-package/tsconfig.json +15 -15
  288. package/package.json +7 -1
  289. package/dist-library/compiler-eOfcinZs.js +0 -62
  290. package/dist-library/component-state-BoLCGee4.js +0 -801
  291. package/dist-library/preset-core-CKc5YXSM.js +0 -1443
  292. package/dist-library/react-D5iGiUdL.js +0 -7
package/cli/assets.mjs CHANGED
@@ -1,395 +1,395 @@
1
- import { createHash } from 'node:crypto';
2
- import { readFile, realpath, stat } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { CliError, EXIT, fsFailure } from './errors.mjs';
5
-
6
- /** 8 MiB of decoded image bytes per asset. */
7
- export const MAX_ASSET_BYTES = 8 * 1024 * 1024;
8
- /** 24 MiB of decoded bytes across all distinct assets. */
9
- export const MAX_TOTAL_ASSET_BYTES = 24 * 1024 * 1024;
10
- /** At most 64 distinct image payloads. */
11
- export const MAX_ASSETS = 64;
12
-
13
- const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/;
14
- const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i;
15
- const WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
16
-
17
- /**
18
- * Keep rejected URLs printable in diagnostics without allowing terminal
19
- * control sequences or unbounded output.
20
- *
21
- * @param {unknown} value
22
- */
23
- export function displayAssetUrl(value) {
24
- const text = typeof value === 'string' ? value : String(value ?? '');
25
- let clipped = text;
26
- if (text.length > 200) {
27
- // Do not leave half of a surrogate pair before the ellipsis.
28
- const end = /[\uD800-\uDBFF]/.test(text[196]) ? 196 : 197;
29
- clipped = `${text.slice(0, end)}...`;
30
- }
31
- return clipped.replace(CONTROL_CHARACTERS, (character) => (
32
- `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
33
- ));
34
- }
35
-
36
- /** @param {unknown} url @param {string} detail */
37
- function assetFailure(url, detail) {
38
- return new CliError(
39
- `Image "${displayAssetUrl(url)}": ${detail} Use --assets omit to export without images, `
40
- + 'or place the file next to the document (or under --asset-root) and reference it with a relative URL.',
41
- EXIT.ASSET,
42
- );
43
- }
44
-
45
- /**
46
- * Validate an image URL before touching the filesystem. Only host-explicit
47
- * relative paths are accepted; remote URLs are never fetched.
48
- *
49
- * @param {unknown} rawUrl
50
- * @returns {{ok: true, url: string, path: string} | {ok: false, reason: string, message: string}}
51
- */
52
- export function classifyAssetUrl(rawUrl) {
53
- const url = typeof rawUrl === 'string' ? rawUrl.trim() : '';
54
- const fail = (reason, message) => ({ ok: false, reason, message });
55
-
56
- if (!url) {
57
- return fail('empty', 'The image URL is empty or missing.');
58
- }
59
- if (CONTROL_CHARACTERS.test(url)) {
60
- return fail('control', 'The image URL contains NUL or control characters.');
61
- }
62
- if (url.includes('\\')) {
63
- return fail('backslash', 'Backslash paths are not allowed; use a relative URL with "/" separators.');
64
- }
65
- if (url.startsWith('//')) {
66
- return fail('protocol-relative', 'Protocol-relative image URLs are not allowed.');
67
- }
68
- if (WINDOWS_DRIVE_PATH.test(url)) {
69
- return fail('absolute', 'Absolute image paths are not allowed.');
70
- }
71
- const scheme = URL_SCHEME.exec(url);
72
- if (scheme) {
73
- const name = scheme[1].toLowerCase();
74
- if (name === 'http' || name === 'https') {
75
- return fail('remote', 'Remote images are never fetched; download the image and use a relative path.');
76
- }
77
- return fail('scheme', `The "${name}:" URL scheme is not supported; only relative file assets are allowed.`);
78
- }
79
- if (url.startsWith('/')) {
80
- return fail('absolute', 'Absolute image paths are not allowed.');
81
- }
82
-
83
- // Query strings and fragments belong to the URL, not the local file name.
84
- let end = url.length;
85
- for (const marker of ['?', '#']) {
86
- const index = url.indexOf(marker);
87
- if (index !== -1 && index < end) end = index;
88
- }
89
- const rawPath = url.slice(0, end);
90
- if (!rawPath) {
91
- return fail('empty', 'The image URL does not contain a file path.');
92
- }
93
-
94
- let decoded;
95
- try {
96
- decoded = decodeURIComponent(rawPath);
97
- } catch {
98
- return fail('encoding', 'The image URL contains malformed percent-encoding.');
99
- }
100
- if (!decoded) {
101
- return fail('empty', 'The image URL does not contain a file path.');
102
- }
103
- if (CONTROL_CHARACTERS.test(decoded)) {
104
- return fail('control', 'The decoded image path contains NUL or control characters.');
105
- }
106
- if (decoded.includes('\\')) {
107
- return fail('backslash', 'The decoded image path contains a backslash.');
108
- }
109
- if (decoded.startsWith('/') || WINDOWS_DRIVE_PATH.test(decoded) || URL_SCHEME.test(decoded)) {
110
- return fail('absolute', 'The decoded image path is absolute or uses a URL scheme.');
111
- }
112
-
113
- return { ok: true, url, path: decoded };
114
- }
115
-
116
- /** @param {Uint8Array} bytes @param {number} start @param {string} text */
117
- function hasAscii(bytes, start, text) {
118
- if (bytes.length < start + text.length) return false;
119
- for (let index = 0; index < text.length; index += 1) {
120
- if (bytes[start + index] !== text.charCodeAt(index)) return false;
121
- }
122
- return true;
123
- }
124
-
125
- /**
126
- * Identify a supported raster image by magic bytes. The extension and any
127
- * caller-supplied MIME are ignored.
128
- *
129
- * @param {Uint8Array | null | undefined} bytes
130
- * @returns {'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | null}
131
- */
132
- export function detectImageMime(bytes) {
133
- if (!bytes || bytes.length < 3) return null;
134
- if (
135
- bytes.length >= 8
136
- && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
137
- && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
138
- ) {
139
- return 'image/png';
140
- }
141
- if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
142
- if (hasAscii(bytes, 0, 'GIF87a') || hasAscii(bytes, 0, 'GIF89a')) return 'image/gif';
143
- if (
144
- bytes.length >= 12
145
- && hasAscii(bytes, 0, 'RIFF')
146
- && hasAscii(bytes, 8, 'WEBP')
147
- ) {
148
- return 'image/webp';
149
- }
150
- return null;
151
- }
152
-
153
- /**
154
- * Used only to explain why an unrecognized file was rejected. SVG is never a
155
- * supported image format, even when it contains no XML declaration.
156
- *
157
- * @param {Uint8Array | null | undefined} bytes
158
- */
159
- export function looksLikeSvg(bytes) {
160
- if (!bytes || bytes.length === 0) return false;
161
- const length = Math.min(bytes.length, 4096);
162
- const head = Buffer.from(bytes.subarray(0, length))
163
- .toString('utf8')
164
- .replace(/^\uFEFF/, '')
165
- .trimStart()
166
- .toLowerCase();
167
- return head.startsWith('<svg') || head.includes('<svg');
168
- }
169
-
170
- /**
171
- * Collect image nodes in document order, including nested blocks.
172
- * @param {any[] | undefined} nodes
173
- * @returns {any[]}
174
- */
175
- export function collectImageNodes(nodes) {
176
- const images = [];
177
- const walk = (list) => {
178
- if (!Array.isArray(list)) return;
179
- for (const node of list) {
180
- if (node?.type === 'image') images.push(node);
181
- if (Array.isArray(node?.children)) walk(node.children);
182
- }
183
- };
184
- walk(nodes);
185
- return images;
186
- }
187
-
188
- /**
189
- * @param {string} root
190
- * @param {string} candidate
191
- */
192
- export function isPathInside(root, candidate) {
193
- const relative = path.relative(root, candidate);
194
- if (relative === '') return true;
195
- if (path.isAbsolute(relative)) return false;
196
- return relative !== '..' && !relative.startsWith(`..${path.sep}`);
197
- }
198
-
199
- /**
200
- * Try the document directory first, then an optional asset root. Resolution is
201
- * based on the real path so `..` segments and symlinks cannot escape a root.
202
- *
203
- * @param {string} relativePath
204
- * @param {{base: string, root: string}[]} roots
205
- */
206
- async function locateAsset(relativePath, roots) {
207
- let sawOutside = false;
208
- let sawDirectory = false;
209
- let sawUnreadable = false;
210
-
211
- for (const entry of roots) {
212
- const candidate = path.resolve(entry.base, relativePath);
213
- let real;
214
- try {
215
- real = await realpath(candidate);
216
- } catch (error) {
217
- const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
218
- if (code !== 'ENOENT' && code !== 'ENOTDIR') sawUnreadable = true;
219
- continue;
220
- }
221
- if (!isPathInside(entry.root, real)) {
222
- sawOutside = true;
223
- continue;
224
- }
225
- let info;
226
- try {
227
- info = await stat(real);
228
- } catch {
229
- sawUnreadable = true;
230
- continue;
231
- }
232
- if (!info.isFile()) {
233
- sawDirectory = true;
234
- continue;
235
- }
236
- return { ok: true, realPath: real, size: info.size };
237
- }
238
-
239
- if (sawDirectory) {
240
- return { ok: false, message: 'The resolved path is a directory, not a file.' };
241
- }
242
- if (sawOutside) {
243
- return {
244
- ok: false,
245
- message: 'The resolved file is outside the allowed roots; path traversal and symlink escapes are not allowed.',
246
- };
247
- }
248
- if (sawUnreadable) {
249
- return { ok: false, message: 'The file could not be resolved or inspected.' };
250
- }
251
- return { ok: false, message: 'The file was not found relative to the document or --asset-root.' };
252
- }
253
-
254
- /**
255
- * Resolve and verify every image referenced by the compiled document, then
256
- * inline the accepted files as data URLs. Nothing is fetched from the network
257
- * and no URL is ever read from `--asset-root` as a remote base.
258
- *
259
- * @param {{document: {nodes?: any[]}, inputPath: string, assetRoot?: string}} options
260
- */
261
- export async function collectInlineAssets({ document, inputPath, assetRoot }) {
262
- const documentDirectory = path.dirname(path.resolve(inputPath));
263
- let documentRoot;
264
- try {
265
- documentRoot = await realpath(documentDirectory);
266
- } catch (error) {
267
- throw fsFailure('Cannot resolve document directory', documentDirectory, error, EXIT.IO);
268
- }
269
-
270
- /** @type {{base: string, root: string}[]} */
271
- const roots = [{ base: documentDirectory, root: documentRoot }];
272
-
273
- if (assetRoot !== undefined) {
274
- const absoluteAssetRoot = path.resolve(assetRoot);
275
- let info;
276
- try {
277
- info = await stat(absoluteAssetRoot);
278
- } catch (error) {
279
- throw fsFailure('Asset root does not exist', absoluteAssetRoot, error, EXIT.IO);
280
- }
281
- if (!info.isDirectory()) {
282
- throw new CliError(`Asset root is not a directory: "${absoluteAssetRoot}".`, EXIT.IO);
283
- }
284
- let assetRootReal;
285
- try {
286
- assetRootReal = await realpath(absoluteAssetRoot);
287
- } catch (error) {
288
- throw fsFailure('Cannot resolve asset root', absoluteAssetRoot, error, EXIT.IO);
289
- }
290
- roots.push({ base: absoluteAssetRoot, root: assetRootReal });
291
- }
292
-
293
- const imageNodes = collectImageNodes(document?.nodes);
294
- /** @type {Map<string, string>} */
295
- const byUrl = new Map();
296
- /** @type {Map<string, string>} */
297
- const contents = new Map();
298
- let totalBytes = 0;
299
-
300
- for (const node of imageNodes) {
301
- const classified = classifyAssetUrl(node.url);
302
- if (!classified.ok) {
303
- throw assetFailure(node.url, classified.message);
304
- }
305
- const key = classified.url;
306
- if (byUrl.has(key)) continue;
307
-
308
- const located = await locateAsset(classified.path, roots);
309
- if (!located.ok) {
310
- throw assetFailure(key, located.message);
311
- }
312
- if (located.size > MAX_ASSET_BYTES) {
313
- throw assetFailure(
314
- key,
315
- `The file is ${located.size} bytes, larger than the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit.`,
316
- );
317
- }
318
-
319
- let bytes;
320
- try {
321
- bytes = await readFile(located.realPath);
322
- } catch {
323
- throw assetFailure(key, 'The file exists but could not be read.');
324
- }
325
- if (bytes.length > MAX_ASSET_BYTES) {
326
- throw assetFailure(
327
- key,
328
- `The file grew beyond the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit while it was read.`,
329
- );
330
- }
331
-
332
- const hash = createHash('sha256').update(bytes).digest('hex');
333
- const existing = contents.get(hash);
334
- if (existing) {
335
- byUrl.set(key, existing);
336
- continue;
337
- }
338
-
339
- const mime = detectImageMime(bytes);
340
- if (!mime) {
341
- if (looksLikeSvg(bytes)) {
342
- throw assetFailure(key, 'SVG images are not supported; use PNG, JPEG, GIF or WebP.');
343
- }
344
- throw assetFailure(
345
- key,
346
- 'The file is not a supported raster image; use PNG, JPEG, GIF or WebP (identified from file contents, not the extension).',
347
- );
348
- }
349
-
350
- if (contents.size >= MAX_ASSETS) {
351
- throw assetFailure(key, `The document references more than ${MAX_ASSETS} distinct image assets.`);
352
- }
353
- if (totalBytes + bytes.length > MAX_TOTAL_ASSET_BYTES) {
354
- throw assetFailure(
355
- key,
356
- `Inlined images would exceed the 24 MiB (${MAX_TOTAL_ASSET_BYTES} byte) total limit `
357
- + `(${totalBytes} bytes already accepted, this file is ${bytes.length} bytes).`,
358
- );
359
- }
360
-
361
- const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
362
- contents.set(hash, dataUrl);
363
- totalBytes += bytes.length;
364
- byUrl.set(key, dataUrl);
365
- }
366
-
367
- return {
368
- byUrl,
369
- imageCount: byUrl.size,
370
- assetCount: contents.size,
371
- totalBytes,
372
- };
373
- }
374
-
375
- /**
376
- * Host URL policy for the React renderer. Links keep the renderer's existing
377
- * protocol checks. Images are true only for URLs that were verified and
378
- * inlined; imageResolver maps exactly those URLs to their data URI.
379
- *
380
- * @param {Map<string, string>} byUrl
381
- */
382
- export function createAssetPolicy(byUrl) {
383
- const images = byUrl instanceof Map ? byUrl : new Map();
384
- return {
385
- /** @param {string} url @param {'image' | 'link'} kind */
386
- urlPolicy(url, kind) {
387
- if (kind === 'link') return true;
388
- return kind === 'image' && typeof url === 'string' && images.has(url);
389
- },
390
- /** @param {string} url */
391
- imageResolver(url) {
392
- return typeof url === 'string' ? images.get(url) ?? null : null;
393
- },
394
- };
395
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { CliError, EXIT, fsFailure } from './errors.mjs';
5
+
6
+ /** 8 MiB of decoded image bytes per asset. */
7
+ export const MAX_ASSET_BYTES = 8 * 1024 * 1024;
8
+ /** 24 MiB of decoded bytes across all distinct assets. */
9
+ export const MAX_TOTAL_ASSET_BYTES = 24 * 1024 * 1024;
10
+ /** At most 64 distinct image payloads. */
11
+ export const MAX_ASSETS = 64;
12
+
13
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/;
14
+ const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i;
15
+ const WINDOWS_DRIVE_PATH = /^[a-z]:[\\/]/i;
16
+
17
+ /**
18
+ * Keep rejected URLs printable in diagnostics without allowing terminal
19
+ * control sequences or unbounded output.
20
+ *
21
+ * @param {unknown} value
22
+ */
23
+ export function displayAssetUrl(value) {
24
+ const text = typeof value === 'string' ? value : String(value ?? '');
25
+ let clipped = text;
26
+ if (text.length > 200) {
27
+ // Do not leave half of a surrogate pair before the ellipsis.
28
+ const end = /[\uD800-\uDBFF]/.test(text[196]) ? 196 : 197;
29
+ clipped = `${text.slice(0, end)}...`;
30
+ }
31
+ return clipped.replace(CONTROL_CHARACTERS, (character) => (
32
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
33
+ ));
34
+ }
35
+
36
+ /** @param {unknown} url @param {string} detail */
37
+ function assetFailure(url, detail) {
38
+ return new CliError(
39
+ `Image "${displayAssetUrl(url)}": ${detail} Use --assets omit to export without images, `
40
+ + 'or place the file next to the document (or under --asset-root) and reference it with a relative URL.',
41
+ EXIT.ASSET,
42
+ );
43
+ }
44
+
45
+ /**
46
+ * Validate an image URL before touching the filesystem. Only host-explicit
47
+ * relative paths are accepted; remote URLs are never fetched.
48
+ *
49
+ * @param {unknown} rawUrl
50
+ * @returns {{ok: true, url: string, path: string} | {ok: false, reason: string, message: string}}
51
+ */
52
+ export function classifyAssetUrl(rawUrl) {
53
+ const url = typeof rawUrl === 'string' ? rawUrl.trim() : '';
54
+ const fail = (reason, message) => ({ ok: false, reason, message });
55
+
56
+ if (!url) {
57
+ return fail('empty', 'The image URL is empty or missing.');
58
+ }
59
+ if (CONTROL_CHARACTERS.test(url)) {
60
+ return fail('control', 'The image URL contains NUL or control characters.');
61
+ }
62
+ if (url.includes('\\')) {
63
+ return fail('backslash', 'Backslash paths are not allowed; use a relative URL with "/" separators.');
64
+ }
65
+ if (url.startsWith('//')) {
66
+ return fail('protocol-relative', 'Protocol-relative image URLs are not allowed.');
67
+ }
68
+ if (WINDOWS_DRIVE_PATH.test(url)) {
69
+ return fail('absolute', 'Absolute image paths are not allowed.');
70
+ }
71
+ const scheme = URL_SCHEME.exec(url);
72
+ if (scheme) {
73
+ const name = scheme[1].toLowerCase();
74
+ if (name === 'http' || name === 'https') {
75
+ return fail('remote', 'Remote images are never fetched; download the image and use a relative path.');
76
+ }
77
+ return fail('scheme', `The "${name}:" URL scheme is not supported; only relative file assets are allowed.`);
78
+ }
79
+ if (url.startsWith('/')) {
80
+ return fail('absolute', 'Absolute image paths are not allowed.');
81
+ }
82
+
83
+ // Query strings and fragments belong to the URL, not the local file name.
84
+ let end = url.length;
85
+ for (const marker of ['?', '#']) {
86
+ const index = url.indexOf(marker);
87
+ if (index !== -1 && index < end) end = index;
88
+ }
89
+ const rawPath = url.slice(0, end);
90
+ if (!rawPath) {
91
+ return fail('empty', 'The image URL does not contain a file path.');
92
+ }
93
+
94
+ let decoded;
95
+ try {
96
+ decoded = decodeURIComponent(rawPath);
97
+ } catch {
98
+ return fail('encoding', 'The image URL contains malformed percent-encoding.');
99
+ }
100
+ if (!decoded) {
101
+ return fail('empty', 'The image URL does not contain a file path.');
102
+ }
103
+ if (CONTROL_CHARACTERS.test(decoded)) {
104
+ return fail('control', 'The decoded image path contains NUL or control characters.');
105
+ }
106
+ if (decoded.includes('\\')) {
107
+ return fail('backslash', 'The decoded image path contains a backslash.');
108
+ }
109
+ if (decoded.startsWith('/') || WINDOWS_DRIVE_PATH.test(decoded) || URL_SCHEME.test(decoded)) {
110
+ return fail('absolute', 'The decoded image path is absolute or uses a URL scheme.');
111
+ }
112
+
113
+ return { ok: true, url, path: decoded };
114
+ }
115
+
116
+ /** @param {Uint8Array} bytes @param {number} start @param {string} text */
117
+ function hasAscii(bytes, start, text) {
118
+ if (bytes.length < start + text.length) return false;
119
+ for (let index = 0; index < text.length; index += 1) {
120
+ if (bytes[start + index] !== text.charCodeAt(index)) return false;
121
+ }
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * Identify a supported raster image by magic bytes. The extension and any
127
+ * caller-supplied MIME are ignored.
128
+ *
129
+ * @param {Uint8Array | null | undefined} bytes
130
+ * @returns {'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | null}
131
+ */
132
+ export function detectImageMime(bytes) {
133
+ if (!bytes || bytes.length < 3) return null;
134
+ if (
135
+ bytes.length >= 8
136
+ && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
137
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
138
+ ) {
139
+ return 'image/png';
140
+ }
141
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
142
+ if (hasAscii(bytes, 0, 'GIF87a') || hasAscii(bytes, 0, 'GIF89a')) return 'image/gif';
143
+ if (
144
+ bytes.length >= 12
145
+ && hasAscii(bytes, 0, 'RIFF')
146
+ && hasAscii(bytes, 8, 'WEBP')
147
+ ) {
148
+ return 'image/webp';
149
+ }
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * Used only to explain why an unrecognized file was rejected. SVG is never a
155
+ * supported image format, even when it contains no XML declaration.
156
+ *
157
+ * @param {Uint8Array | null | undefined} bytes
158
+ */
159
+ export function looksLikeSvg(bytes) {
160
+ if (!bytes || bytes.length === 0) return false;
161
+ const length = Math.min(bytes.length, 4096);
162
+ const head = Buffer.from(bytes.subarray(0, length))
163
+ .toString('utf8')
164
+ .replace(/^\uFEFF/, '')
165
+ .trimStart()
166
+ .toLowerCase();
167
+ return head.startsWith('<svg') || head.includes('<svg');
168
+ }
169
+
170
+ /**
171
+ * Collect image nodes in document order, including nested blocks.
172
+ * @param {any[] | undefined} nodes
173
+ * @returns {any[]}
174
+ */
175
+ export function collectImageNodes(nodes) {
176
+ const images = [];
177
+ const walk = (list) => {
178
+ if (!Array.isArray(list)) return;
179
+ for (const node of list) {
180
+ if (node?.type === 'image') images.push(node);
181
+ if (Array.isArray(node?.children)) walk(node.children);
182
+ }
183
+ };
184
+ walk(nodes);
185
+ return images;
186
+ }
187
+
188
+ /**
189
+ * @param {string} root
190
+ * @param {string} candidate
191
+ */
192
+ export function isPathInside(root, candidate) {
193
+ const relative = path.relative(root, candidate);
194
+ if (relative === '') return true;
195
+ if (path.isAbsolute(relative)) return false;
196
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`);
197
+ }
198
+
199
+ /**
200
+ * Try the document directory first, then an optional asset root. Resolution is
201
+ * based on the real path so `..` segments and symlinks cannot escape a root.
202
+ *
203
+ * @param {string} relativePath
204
+ * @param {{base: string, root: string}[]} roots
205
+ */
206
+ async function locateAsset(relativePath, roots) {
207
+ let sawOutside = false;
208
+ let sawDirectory = false;
209
+ let sawUnreadable = false;
210
+
211
+ for (const entry of roots) {
212
+ const candidate = path.resolve(entry.base, relativePath);
213
+ let real;
214
+ try {
215
+ real = await realpath(candidate);
216
+ } catch (error) {
217
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
218
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') sawUnreadable = true;
219
+ continue;
220
+ }
221
+ if (!isPathInside(entry.root, real)) {
222
+ sawOutside = true;
223
+ continue;
224
+ }
225
+ let info;
226
+ try {
227
+ info = await stat(real);
228
+ } catch {
229
+ sawUnreadable = true;
230
+ continue;
231
+ }
232
+ if (!info.isFile()) {
233
+ sawDirectory = true;
234
+ continue;
235
+ }
236
+ return { ok: true, realPath: real, size: info.size };
237
+ }
238
+
239
+ if (sawDirectory) {
240
+ return { ok: false, message: 'The resolved path is a directory, not a file.' };
241
+ }
242
+ if (sawOutside) {
243
+ return {
244
+ ok: false,
245
+ message: 'The resolved file is outside the allowed roots; path traversal and symlink escapes are not allowed.',
246
+ };
247
+ }
248
+ if (sawUnreadable) {
249
+ return { ok: false, message: 'The file could not be resolved or inspected.' };
250
+ }
251
+ return { ok: false, message: 'The file was not found relative to the document or --asset-root.' };
252
+ }
253
+
254
+ /**
255
+ * Resolve and verify every image referenced by the compiled document, then
256
+ * inline the accepted files as data URLs. Nothing is fetched from the network
257
+ * and no URL is ever read from `--asset-root` as a remote base.
258
+ *
259
+ * @param {{document: {nodes?: any[]}, inputPath: string, assetRoot?: string}} options
260
+ */
261
+ export async function collectInlineAssets({ document, inputPath, assetRoot }) {
262
+ const documentDirectory = path.dirname(path.resolve(inputPath));
263
+ let documentRoot;
264
+ try {
265
+ documentRoot = await realpath(documentDirectory);
266
+ } catch (error) {
267
+ throw fsFailure('Cannot resolve document directory', documentDirectory, error, EXIT.IO);
268
+ }
269
+
270
+ /** @type {{base: string, root: string}[]} */
271
+ const roots = [{ base: documentDirectory, root: documentRoot }];
272
+
273
+ if (assetRoot !== undefined) {
274
+ const absoluteAssetRoot = path.resolve(assetRoot);
275
+ let info;
276
+ try {
277
+ info = await stat(absoluteAssetRoot);
278
+ } catch (error) {
279
+ throw fsFailure('Asset root does not exist', absoluteAssetRoot, error, EXIT.IO);
280
+ }
281
+ if (!info.isDirectory()) {
282
+ throw new CliError(`Asset root is not a directory: "${absoluteAssetRoot}".`, EXIT.IO);
283
+ }
284
+ let assetRootReal;
285
+ try {
286
+ assetRootReal = await realpath(absoluteAssetRoot);
287
+ } catch (error) {
288
+ throw fsFailure('Cannot resolve asset root', absoluteAssetRoot, error, EXIT.IO);
289
+ }
290
+ roots.push({ base: absoluteAssetRoot, root: assetRootReal });
291
+ }
292
+
293
+ const imageNodes = collectImageNodes(document?.nodes);
294
+ /** @type {Map<string, string>} */
295
+ const byUrl = new Map();
296
+ /** @type {Map<string, string>} */
297
+ const contents = new Map();
298
+ let totalBytes = 0;
299
+
300
+ for (const node of imageNodes) {
301
+ const classified = classifyAssetUrl(node.url);
302
+ if (!classified.ok) {
303
+ throw assetFailure(node.url, classified.message);
304
+ }
305
+ const key = classified.url;
306
+ if (byUrl.has(key)) continue;
307
+
308
+ const located = await locateAsset(classified.path, roots);
309
+ if (!located.ok) {
310
+ throw assetFailure(key, located.message);
311
+ }
312
+ if (located.size > MAX_ASSET_BYTES) {
313
+ throw assetFailure(
314
+ key,
315
+ `The file is ${located.size} bytes, larger than the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit.`,
316
+ );
317
+ }
318
+
319
+ let bytes;
320
+ try {
321
+ bytes = await readFile(located.realPath);
322
+ } catch {
323
+ throw assetFailure(key, 'The file exists but could not be read.');
324
+ }
325
+ if (bytes.length > MAX_ASSET_BYTES) {
326
+ throw assetFailure(
327
+ key,
328
+ `The file grew beyond the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit while it was read.`,
329
+ );
330
+ }
331
+
332
+ const hash = createHash('sha256').update(bytes).digest('hex');
333
+ const existing = contents.get(hash);
334
+ if (existing) {
335
+ byUrl.set(key, existing);
336
+ continue;
337
+ }
338
+
339
+ const mime = detectImageMime(bytes);
340
+ if (!mime) {
341
+ if (looksLikeSvg(bytes)) {
342
+ throw assetFailure(key, 'SVG images are not supported; use PNG, JPEG, GIF or WebP.');
343
+ }
344
+ throw assetFailure(
345
+ key,
346
+ 'The file is not a supported raster image; use PNG, JPEG, GIF or WebP (identified from file contents, not the extension).',
347
+ );
348
+ }
349
+
350
+ if (contents.size >= MAX_ASSETS) {
351
+ throw assetFailure(key, `The document references more than ${MAX_ASSETS} distinct image assets.`);
352
+ }
353
+ if (totalBytes + bytes.length > MAX_TOTAL_ASSET_BYTES) {
354
+ throw assetFailure(
355
+ key,
356
+ `Inlined images would exceed the 24 MiB (${MAX_TOTAL_ASSET_BYTES} byte) total limit `
357
+ + `(${totalBytes} bytes already accepted, this file is ${bytes.length} bytes).`,
358
+ );
359
+ }
360
+
361
+ const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
362
+ contents.set(hash, dataUrl);
363
+ totalBytes += bytes.length;
364
+ byUrl.set(key, dataUrl);
365
+ }
366
+
367
+ return {
368
+ byUrl,
369
+ imageCount: byUrl.size,
370
+ assetCount: contents.size,
371
+ totalBytes,
372
+ };
373
+ }
374
+
375
+ /**
376
+ * Host URL policy for the React renderer. Links keep the renderer's existing
377
+ * protocol checks. Images are true only for URLs that were verified and
378
+ * inlined; imageResolver maps exactly those URLs to their data URI.
379
+ *
380
+ * @param {Map<string, string>} byUrl
381
+ */
382
+ export function createAssetPolicy(byUrl) {
383
+ const images = byUrl instanceof Map ? byUrl : new Map();
384
+ return {
385
+ /** @param {string} url @param {'image' | 'link'} kind */
386
+ urlPolicy(url, kind) {
387
+ if (kind === 'link') return true;
388
+ return kind === 'image' && typeof url === 'string' && images.has(url);
389
+ },
390
+ /** @param {string} url */
391
+ imageResolver(url) {
392
+ return typeof url === 'string' ? images.get(url) ?? null : null;
393
+ },
394
+ };
395
+ }