reactive-md 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG-ch.md +96 -0
  2. package/CHANGELOG.md +82 -39
  3. package/CONTRIBUTING-ch.md +62 -0
  4. package/CONTRIBUTING.md +64 -65
  5. package/README-ch.md +122 -0
  6. package/README-en.md +146 -0
  7. package/README.md +146 -89
  8. package/SECURITY-ch.md +80 -0
  9. package/SECURITY.md +58 -49
  10. package/THIRD_PARTY_NOTICES.md +85 -1
  11. package/bin/reactive-md.mjs +40 -0
  12. package/cli/args.mjs +181 -0
  13. package/cli/assets.mjs +390 -0
  14. package/cli/build.mjs +268 -0
  15. package/cli/document.mjs +130 -0
  16. package/cli/errors.mjs +61 -0
  17. package/cli/fs-utils.mjs +133 -0
  18. package/cli/glob.mjs +203 -0
  19. package/cli/help.mjs +138 -0
  20. package/cli/lint.mjs +177 -0
  21. package/cli/main.mjs +55 -0
  22. package/cli/migrate.mjs +368 -0
  23. package/cli/package.mjs +209 -0
  24. package/dist-library/reactive-md-react.js +3425 -1647
  25. package/dist-library/reactive-md.css +1 -1
  26. package/dist-library/reactive-md.js +1798 -4
  27. package/dist-library/runtime-DtjdPXxJ.js +15410 -0
  28. package/dist-library/types/index.d.ts +1 -0
  29. package/dist-library/types/local/LocalDocumentView.d.ts +66 -3
  30. package/dist-library/types/local/authoring.d.ts +63 -0
  31. package/dist-library/types/local/collection-functions.d.ts +4 -0
  32. package/dist-library/types/local/colors.d.ts +2 -0
  33. package/dist-library/types/local/computations.d.ts +53 -0
  34. package/dist-library/types/local/data-functions.d.ts +22 -0
  35. package/dist-library/types/local/data-table.d.ts +65 -0
  36. package/dist-library/types/local/dates.d.ts +2 -0
  37. package/dist-library/types/local/dependencies.d.ts +31 -0
  38. package/dist-library/types/local/diagnostics.d.ts +1450 -0
  39. package/dist-library/types/local/expression.d.ts +13 -3
  40. package/dist-library/types/local/formatting.d.ts +41 -0
  41. package/dist-library/types/local/heading-anchors.d.ts +13 -2
  42. package/dist-library/types/local/i18n.d.ts +18 -0
  43. package/dist-library/types/local/index.d.ts +18 -1
  44. package/dist-library/types/local/limits.d.ts +32 -1
  45. package/dist-library/types/local/locale.d.ts +1 -0
  46. package/dist-library/types/local/math.d.ts +6 -1
  47. package/dist-library/types/local/parser.d.ts +10 -4
  48. package/dist-library/types/local/render-types.d.ts +5 -1
  49. package/dist-library/types/local/retention.d.ts +23 -0
  50. package/dist-library/types/local/schema.d.ts +25 -3
  51. package/dist-library/types/local/source-migration.d.ts +35 -0
  52. package/dist-library/types/local/state.d.ts +80 -0
  53. package/dist-library/types/local/text-length.d.ts +13 -0
  54. package/dist-library/types/local/theme.d.ts +30 -0
  55. package/dist-library/types/local/types.d.ts +112 -4
  56. package/dist-library/types/local/validation.d.ts +32 -0
  57. package/dist-library/types/local/version.d.ts +1 -1
  58. package/dist-library/types/local/worker.d.ts +82 -0
  59. package/dist-library/types/react/index.d.ts +4 -1
  60. package/dist-library/types/shareable.d.ts +64 -0
  61. package/dist-standalone/reactive-md-standalone.css +2 -0
  62. package/dist-standalone/reactive-md-standalone.js +57 -0
  63. package/docs/author-tools-ch.md +56 -0
  64. package/docs/author-tools-en.md +56 -0
  65. package/docs/compatibility-ch.md +103 -0
  66. package/docs/compatibility-en.md +103 -0
  67. package/docs/{component-development.md → component-development-ch.md} +210 -206
  68. package/docs/component-development-en.md +210 -0
  69. package/docs/{component-protocol.md → component-protocol-ch.md} +710 -685
  70. package/docs/component-protocol-en.md +710 -0
  71. package/docs/computations-formatting-ch.md +87 -0
  72. package/docs/computations-formatting-en.md +87 -0
  73. package/docs/constraints-collections-ch.md +84 -0
  74. package/docs/constraints-collections-en.md +84 -0
  75. package/docs/diagnostics-counting-ch.md +84 -0
  76. package/docs/diagnostics-counting-en.md +84 -0
  77. package/docs/local-components-v2-ch.md +138 -0
  78. package/docs/local-components-v2-en.md +104 -0
  79. package/docs/{local-guide.md → local-guide-ch.md} +28 -8
  80. package/docs/local-guide-en.md +961 -0
  81. package/docs/local-integration-ch.md +363 -0
  82. package/docs/local-integration-en.md +363 -0
  83. package/docs/{local-interaction-syntax.md → local-interaction-syntax-ch.md} +66 -20
  84. package/docs/local-interaction-syntax-en.md +483 -0
  85. package/docs/{performance.md → performance-ch.md} +12 -3
  86. package/docs/performance-en.md +76 -0
  87. package/docs/release-0.4.0-ch.md +89 -0
  88. package/docs/release-0.4.0-en.md +89 -0
  89. package/docs/releasing-ch.md +101 -0
  90. package/docs/releasing-en.md +101 -0
  91. package/docs/shareable-export-ch.md +205 -0
  92. package/docs/shareable-export-en.md +207 -0
  93. package/docs/source-versioning-ch.md +159 -0
  94. package/docs/source-versioning-en.md +159 -0
  95. package/docs/theme-protocol-ch.md +107 -0
  96. package/docs/theme-protocol-en.md +107 -0
  97. package/examples/conformance/README.md +33 -31
  98. package/examples/conformance/component-protocol-1.json +482 -194
  99. package/examples/conformance/component-protocol-1.schema.json +76 -76
  100. package/examples/conformance/history/v0.3.1/catalog.reactive.md +20 -0
  101. package/examples/conformance/history/v0.3.1/charts.reactive.md +73 -0
  102. package/examples/conformance/history/v0.3.1/checklist.reactive.md +32 -0
  103. package/examples/conformance/history/v0.3.1/comparison.reactive.md +47 -0
  104. package/examples/conformance/history/v0.3.1/components.reactive.md +44 -0
  105. package/examples/conformance/history/v0.3.1/counter.reactive.md +7 -0
  106. package/examples/conformance/history/v0.3.1/diagnostics.reactive.md +54 -0
  107. package/examples/conformance/history/v0.3.1/diagram.reactive.md +44 -0
  108. package/examples/conformance/history/v0.3.1/gallery.reactive.md +61 -0
  109. package/examples/conformance/history/v0.3.1/local-draft-1.json +50 -0
  110. package/examples/conformance/history/v0.3.1/parameters.reactive.md +36 -0
  111. package/examples/conformance/history/v0.3.1/planning.reactive.md +24 -0
  112. package/examples/conformance/history/v0.3.1/pricing.reactive.md +20 -0
  113. package/examples/conformance/history/v0.3.1/provenance.json +72 -0
  114. package/examples/conformance/local-draft-2.json +212 -0
  115. package/examples/integration/README.md +45 -29
  116. package/examples/integration/core/index.mjs +32 -19
  117. package/examples/integration/react/index.html +1 -1
  118. package/examples/integration/react/main.jsx +5 -5
  119. package/examples/integration/worker/index.html +19 -0
  120. package/examples/integration/worker/main.js +61 -0
  121. package/examples/integration/worker/package.json +13 -0
  122. package/examples/integration/worker/worker.js +3 -0
  123. package/examples/local/README.md +64 -58
  124. package/examples/local/catalog.reactive.md +14 -14
  125. package/examples/local/charts.reactive.md +34 -34
  126. package/examples/local/checklist.reactive.md +19 -19
  127. package/examples/local/comparison.reactive.md +23 -23
  128. package/examples/local/components.reactive.md +20 -20
  129. package/examples/local/counter.reactive.md +4 -4
  130. package/examples/local/diagnostics.reactive.md +25 -25
  131. package/examples/local/diagram.reactive.md +20 -20
  132. package/examples/local/gallery.reactive.md +31 -31
  133. package/examples/local/parameters.reactive.md +19 -19
  134. package/examples/local/planning.reactive.md +15 -15
  135. package/examples/local/pricing.reactive.md +10 -10
  136. package/examples/local/recipes/invoice-zh.reactive.md +36 -0
  137. package/examples/local/recipes/invoice.reactive.md +36 -0
  138. package/examples/local/recipes/workshop-zh.reactive.md +33 -0
  139. package/examples/local/recipes/workshop.reactive.md +33 -0
  140. package/examples/local/showcase/README.md +25 -0
  141. package/examples/local/showcase/explore.reactive.md +102 -0
  142. package/examples/local/showcase/flow.reactive.md +86 -0
  143. package/examples/local/showcase/forms.reactive.md +126 -0
  144. package/examples/local/showcase/functions.reactive.md +119 -0
  145. package/examples/local/showcase/layout.reactive.md +100 -0
  146. package/examples/local/showcase/statistics.reactive.md +108 -0
  147. package/examples/local/showcase/tasks.reactive.md +89 -0
  148. package/examples/local/showcase/zh/explore.reactive.md +102 -0
  149. package/examples/local/showcase/zh/flow.reactive.md +86 -0
  150. package/examples/local/showcase/zh/forms.reactive.md +126 -0
  151. package/examples/local/showcase/zh/functions.reactive.md +119 -0
  152. package/examples/local/showcase/zh/layout.reactive.md +100 -0
  153. package/examples/local/showcase/zh/statistics.reactive.md +108 -0
  154. package/examples/local/showcase/zh/tasks.reactive.md +89 -0
  155. package/examples/local/zh/catalog.reactive.md +20 -0
  156. package/examples/local/zh/charts.reactive.md +73 -0
  157. package/examples/local/zh/checklist.reactive.md +32 -0
  158. package/examples/local/zh/comparison.reactive.md +47 -0
  159. package/examples/local/zh/components.reactive.md +44 -0
  160. package/examples/local/zh/counter.reactive.md +7 -0
  161. package/examples/local/zh/diagnostics.reactive.md +54 -0
  162. package/examples/local/zh/diagram.reactive.md +44 -0
  163. package/examples/local/zh/gallery.reactive.md +61 -0
  164. package/examples/local/zh/parameters.reactive.md +36 -0
  165. package/examples/local/zh/planning.reactive.md +24 -0
  166. package/examples/local/zh/pricing.reactive.md +20 -0
  167. package/package.json +16 -3
  168. package/README.en.md +0 -76
  169. package/dist-library/runtime-CPzMEMcW.js +0 -11111
  170. package/docs/compatibility.md +0 -68
  171. package/docs/local-integration.md +0 -218
  172. package/docs/releasing.md +0 -92
package/cli/assets.mjs ADDED
@@ -0,0 +1,390 @@
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
+ const clipped = text.length > 200 ? `${text.slice(0, 197)}...` : text;
26
+ return clipped.replace(CONTROL_CHARACTERS, (character) => (
27
+ `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`
28
+ ));
29
+ }
30
+
31
+ /** @param {unknown} url @param {string} detail */
32
+ function assetFailure(url, detail) {
33
+ return new CliError(
34
+ `Image "${displayAssetUrl(url)}": ${detail} Use --assets omit to export without images, `
35
+ + 'or place the file next to the document (or under --asset-root) and reference it with a relative URL.',
36
+ EXIT.ASSET,
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Validate an image URL before touching the filesystem. Only host-explicit
42
+ * relative paths are accepted; remote URLs are never fetched.
43
+ *
44
+ * @param {unknown} rawUrl
45
+ * @returns {{ok: true, url: string, path: string} | {ok: false, reason: string, message: string}}
46
+ */
47
+ export function classifyAssetUrl(rawUrl) {
48
+ const url = typeof rawUrl === 'string' ? rawUrl.trim() : '';
49
+ const fail = (reason, message) => ({ ok: false, reason, message });
50
+
51
+ if (!url) {
52
+ return fail('empty', 'The image URL is empty or missing.');
53
+ }
54
+ if (CONTROL_CHARACTERS.test(url)) {
55
+ return fail('control', 'The image URL contains NUL or control characters.');
56
+ }
57
+ if (url.includes('\\')) {
58
+ return fail('backslash', 'Backslash paths are not allowed; use a relative URL with "/" separators.');
59
+ }
60
+ if (url.startsWith('//')) {
61
+ return fail('protocol-relative', 'Protocol-relative image URLs are not allowed.');
62
+ }
63
+ if (WINDOWS_DRIVE_PATH.test(url)) {
64
+ return fail('absolute', 'Absolute image paths are not allowed.');
65
+ }
66
+ const scheme = URL_SCHEME.exec(url);
67
+ if (scheme) {
68
+ const name = scheme[1].toLowerCase();
69
+ if (name === 'http' || name === 'https') {
70
+ return fail('remote', 'Remote images are never fetched; download the image and use a relative path.');
71
+ }
72
+ return fail('scheme', `The "${name}:" URL scheme is not supported; only relative file assets are allowed.`);
73
+ }
74
+ if (url.startsWith('/')) {
75
+ return fail('absolute', 'Absolute image paths are not allowed.');
76
+ }
77
+
78
+ // Query strings and fragments belong to the URL, not the local file name.
79
+ let end = url.length;
80
+ for (const marker of ['?', '#']) {
81
+ const index = url.indexOf(marker);
82
+ if (index !== -1 && index < end) end = index;
83
+ }
84
+ const rawPath = url.slice(0, end);
85
+ if (!rawPath) {
86
+ return fail('empty', 'The image URL does not contain a file path.');
87
+ }
88
+
89
+ let decoded;
90
+ try {
91
+ decoded = decodeURIComponent(rawPath);
92
+ } catch {
93
+ return fail('encoding', 'The image URL contains malformed percent-encoding.');
94
+ }
95
+ if (!decoded) {
96
+ return fail('empty', 'The image URL does not contain a file path.');
97
+ }
98
+ if (CONTROL_CHARACTERS.test(decoded)) {
99
+ return fail('control', 'The decoded image path contains NUL or control characters.');
100
+ }
101
+ if (decoded.includes('\\')) {
102
+ return fail('backslash', 'The decoded image path contains a backslash.');
103
+ }
104
+ if (decoded.startsWith('/') || WINDOWS_DRIVE_PATH.test(decoded) || URL_SCHEME.test(decoded)) {
105
+ return fail('absolute', 'The decoded image path is absolute or uses a URL scheme.');
106
+ }
107
+
108
+ return { ok: true, url, path: decoded };
109
+ }
110
+
111
+ /** @param {Uint8Array} bytes @param {number} start @param {string} text */
112
+ function hasAscii(bytes, start, text) {
113
+ if (bytes.length < start + text.length) return false;
114
+ for (let index = 0; index < text.length; index += 1) {
115
+ if (bytes[start + index] !== text.charCodeAt(index)) return false;
116
+ }
117
+ return true;
118
+ }
119
+
120
+ /**
121
+ * Identify a supported raster image by magic bytes. The extension and any
122
+ * caller-supplied MIME are ignored.
123
+ *
124
+ * @param {Uint8Array | null | undefined} bytes
125
+ * @returns {'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp' | null}
126
+ */
127
+ export function detectImageMime(bytes) {
128
+ if (!bytes || bytes.length < 3) return null;
129
+ if (
130
+ bytes.length >= 8
131
+ && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47
132
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a
133
+ ) {
134
+ return 'image/png';
135
+ }
136
+ if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg';
137
+ if (hasAscii(bytes, 0, 'GIF87a') || hasAscii(bytes, 0, 'GIF89a')) return 'image/gif';
138
+ if (
139
+ bytes.length >= 12
140
+ && hasAscii(bytes, 0, 'RIFF')
141
+ && hasAscii(bytes, 8, 'WEBP')
142
+ ) {
143
+ return 'image/webp';
144
+ }
145
+ return null;
146
+ }
147
+
148
+ /**
149
+ * Used only to explain why an unrecognized file was rejected. SVG is never a
150
+ * supported image format, even when it contains no XML declaration.
151
+ *
152
+ * @param {Uint8Array | null | undefined} bytes
153
+ */
154
+ export function looksLikeSvg(bytes) {
155
+ if (!bytes || bytes.length === 0) return false;
156
+ const length = Math.min(bytes.length, 4096);
157
+ const head = Buffer.from(bytes.subarray(0, length))
158
+ .toString('utf8')
159
+ .replace(/^\uFEFF/, '')
160
+ .trimStart()
161
+ .toLowerCase();
162
+ return head.startsWith('<svg') || head.includes('<svg');
163
+ }
164
+
165
+ /**
166
+ * Collect image nodes in document order, including nested blocks.
167
+ * @param {any[] | undefined} nodes
168
+ * @returns {any[]}
169
+ */
170
+ export function collectImageNodes(nodes) {
171
+ const images = [];
172
+ const walk = (list) => {
173
+ if (!Array.isArray(list)) return;
174
+ for (const node of list) {
175
+ if (node?.type === 'image') images.push(node);
176
+ if (Array.isArray(node?.children)) walk(node.children);
177
+ }
178
+ };
179
+ walk(nodes);
180
+ return images;
181
+ }
182
+
183
+ /**
184
+ * @param {string} root
185
+ * @param {string} candidate
186
+ */
187
+ export function isPathInside(root, candidate) {
188
+ const relative = path.relative(root, candidate);
189
+ if (relative === '') return true;
190
+ if (path.isAbsolute(relative)) return false;
191
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`);
192
+ }
193
+
194
+ /**
195
+ * Try the document directory first, then an optional asset root. Resolution is
196
+ * based on the real path so `..` segments and symlinks cannot escape a root.
197
+ *
198
+ * @param {string} relativePath
199
+ * @param {{base: string, root: string}[]} roots
200
+ */
201
+ async function locateAsset(relativePath, roots) {
202
+ let sawOutside = false;
203
+ let sawDirectory = false;
204
+ let sawUnreadable = false;
205
+
206
+ for (const entry of roots) {
207
+ const candidate = path.resolve(entry.base, relativePath);
208
+ let real;
209
+ try {
210
+ real = await realpath(candidate);
211
+ } catch (error) {
212
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null;
213
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') sawUnreadable = true;
214
+ continue;
215
+ }
216
+ if (!isPathInside(entry.root, real)) {
217
+ sawOutside = true;
218
+ continue;
219
+ }
220
+ let info;
221
+ try {
222
+ info = await stat(real);
223
+ } catch {
224
+ sawUnreadable = true;
225
+ continue;
226
+ }
227
+ if (!info.isFile()) {
228
+ sawDirectory = true;
229
+ continue;
230
+ }
231
+ return { ok: true, realPath: real, size: info.size };
232
+ }
233
+
234
+ if (sawDirectory) {
235
+ return { ok: false, message: 'The resolved path is a directory, not a file.' };
236
+ }
237
+ if (sawOutside) {
238
+ return {
239
+ ok: false,
240
+ message: 'The resolved file is outside the allowed roots; path traversal and symlink escapes are not allowed.',
241
+ };
242
+ }
243
+ if (sawUnreadable) {
244
+ return { ok: false, message: 'The file could not be resolved or inspected.' };
245
+ }
246
+ return { ok: false, message: 'The file was not found relative to the document or --asset-root.' };
247
+ }
248
+
249
+ /**
250
+ * Resolve and verify every image referenced by the compiled document, then
251
+ * inline the accepted files as data URLs. Nothing is fetched from the network
252
+ * and no URL is ever read from `--asset-root` as a remote base.
253
+ *
254
+ * @param {{document: {nodes?: any[]}, inputPath: string, assetRoot?: string}} options
255
+ */
256
+ export async function collectInlineAssets({ document, inputPath, assetRoot }) {
257
+ const documentDirectory = path.dirname(path.resolve(inputPath));
258
+ let documentRoot;
259
+ try {
260
+ documentRoot = await realpath(documentDirectory);
261
+ } catch (error) {
262
+ throw fsFailure('Cannot resolve document directory', documentDirectory, error, EXIT.IO);
263
+ }
264
+
265
+ /** @type {{base: string, root: string}[]} */
266
+ const roots = [{ base: documentDirectory, root: documentRoot }];
267
+
268
+ if (assetRoot !== undefined) {
269
+ const absoluteAssetRoot = path.resolve(assetRoot);
270
+ let info;
271
+ try {
272
+ info = await stat(absoluteAssetRoot);
273
+ } catch (error) {
274
+ throw fsFailure('Asset root does not exist', absoluteAssetRoot, error, EXIT.IO);
275
+ }
276
+ if (!info.isDirectory()) {
277
+ throw new CliError(`Asset root is not a directory: "${absoluteAssetRoot}".`, EXIT.IO);
278
+ }
279
+ let assetRootReal;
280
+ try {
281
+ assetRootReal = await realpath(absoluteAssetRoot);
282
+ } catch (error) {
283
+ throw fsFailure('Cannot resolve asset root', absoluteAssetRoot, error, EXIT.IO);
284
+ }
285
+ roots.push({ base: absoluteAssetRoot, root: assetRootReal });
286
+ }
287
+
288
+ const imageNodes = collectImageNodes(document?.nodes);
289
+ /** @type {Map<string, string>} */
290
+ const byUrl = new Map();
291
+ /** @type {Map<string, string>} */
292
+ const contents = new Map();
293
+ let totalBytes = 0;
294
+
295
+ for (const node of imageNodes) {
296
+ const classified = classifyAssetUrl(node.url);
297
+ if (!classified.ok) {
298
+ throw assetFailure(node.url, classified.message);
299
+ }
300
+ const key = classified.url;
301
+ if (byUrl.has(key)) continue;
302
+
303
+ const located = await locateAsset(classified.path, roots);
304
+ if (!located.ok) {
305
+ throw assetFailure(key, located.message);
306
+ }
307
+ if (located.size > MAX_ASSET_BYTES) {
308
+ throw assetFailure(
309
+ key,
310
+ `The file is ${located.size} bytes, larger than the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit.`,
311
+ );
312
+ }
313
+
314
+ let bytes;
315
+ try {
316
+ bytes = await readFile(located.realPath);
317
+ } catch {
318
+ throw assetFailure(key, 'The file exists but could not be read.');
319
+ }
320
+ if (bytes.length > MAX_ASSET_BYTES) {
321
+ throw assetFailure(
322
+ key,
323
+ `The file grew beyond the 8 MiB (${MAX_ASSET_BYTES} byte) per-image limit while it was read.`,
324
+ );
325
+ }
326
+
327
+ const hash = createHash('sha256').update(bytes).digest('hex');
328
+ const existing = contents.get(hash);
329
+ if (existing) {
330
+ byUrl.set(key, existing);
331
+ continue;
332
+ }
333
+
334
+ const mime = detectImageMime(bytes);
335
+ if (!mime) {
336
+ if (looksLikeSvg(bytes)) {
337
+ throw assetFailure(key, 'SVG images are not supported; use PNG, JPEG, GIF or WebP.');
338
+ }
339
+ throw assetFailure(
340
+ key,
341
+ 'The file is not a supported raster image; use PNG, JPEG, GIF or WebP (identified from file contents, not the extension).',
342
+ );
343
+ }
344
+
345
+ if (contents.size >= MAX_ASSETS) {
346
+ throw assetFailure(key, `The document references more than ${MAX_ASSETS} distinct image assets.`);
347
+ }
348
+ if (totalBytes + bytes.length > MAX_TOTAL_ASSET_BYTES) {
349
+ throw assetFailure(
350
+ key,
351
+ `Inlined images would exceed the 24 MiB (${MAX_TOTAL_ASSET_BYTES} byte) total limit `
352
+ + `(${totalBytes} bytes already accepted, this file is ${bytes.length} bytes).`,
353
+ );
354
+ }
355
+
356
+ const dataUrl = `data:${mime};base64,${bytes.toString('base64')}`;
357
+ contents.set(hash, dataUrl);
358
+ totalBytes += bytes.length;
359
+ byUrl.set(key, dataUrl);
360
+ }
361
+
362
+ return {
363
+ byUrl,
364
+ imageCount: byUrl.size,
365
+ assetCount: contents.size,
366
+ totalBytes,
367
+ };
368
+ }
369
+
370
+ /**
371
+ * Host URL policy for the React renderer. Links keep the renderer's existing
372
+ * protocol checks. Images are true only for URLs that were verified and
373
+ * inlined; imageResolver maps exactly those URLs to their data URI.
374
+ *
375
+ * @param {Map<string, string>} byUrl
376
+ */
377
+ export function createAssetPolicy(byUrl) {
378
+ const images = byUrl instanceof Map ? byUrl : new Map();
379
+ return {
380
+ /** @param {string} url @param {'image' | 'link'} kind */
381
+ urlPolicy(url, kind) {
382
+ if (kind === 'link') return true;
383
+ return kind === 'image' && typeof url === 'string' && images.has(url);
384
+ },
385
+ /** @param {string} url */
386
+ imageResolver(url) {
387
+ return typeof url === 'string' ? images.get(url) ?? null : null;
388
+ },
389
+ };
390
+ }
package/cli/build.mjs ADDED
@@ -0,0 +1,268 @@
1
+ import path from 'node:path';
2
+ import { collectImageNodes, collectInlineAssets, createAssetPolicy } from './assets.mjs';
3
+ import { displayPath, extractDocumentTitle, formatDiagnostic } from './document.mjs';
4
+ import { CliError, EXIT, errorText } from './errors.mjs';
5
+ import {
6
+ assertDistinctPaths,
7
+ assertOutputDirectory,
8
+ atomicWriteUtf8,
9
+ readTextFile,
10
+ } from './fs-utils.mjs';
11
+ import {
12
+ loadCore,
13
+ loadReact,
14
+ loadReactRenderer,
15
+ readArtifactText,
16
+ readNotices,
17
+ readPackageInfo,
18
+ } from './package.mjs';
19
+
20
+ /** @param {NodeJS.WritableStream} stream @param {string} file @param {any[]} diagnostics */
21
+ function writeDiagnostics(stream, file, diagnostics) {
22
+ for (const diagnostic of diagnostics) {
23
+ stream.write(`${formatDiagnostic(file, diagnostic)}\n`);
24
+ }
25
+ }
26
+
27
+ /**
28
+ * `reactive-md build`
29
+ * @param {any} options
30
+ * @param {{packageRoot: string, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream}} context
31
+ */
32
+ export async function runBuild(options, context) {
33
+ const { packageRoot, stdout, stderr } = context;
34
+ const inputPath = path.resolve(options.input);
35
+ const outputPath = path.resolve(options.output);
36
+ const fileLabel = displayPath(inputPath);
37
+
38
+ const source = await readTextFile(inputPath, {
39
+ label: 'Cannot read input document',
40
+ exitCode: EXIT.IO,
41
+ });
42
+ await assertDistinctPaths(inputPath, outputPath);
43
+ await assertOutputDirectory(outputPath);
44
+
45
+ const packageInfo = await readPackageInfo(packageRoot);
46
+ const generator = { name: 'reactive-md', version: packageInfo.version };
47
+
48
+ const core = await loadCore(packageRoot, [
49
+ 'compileLocal',
50
+ 'createLocalRuntime',
51
+ 'createLocalStateFile',
52
+ 'resolveLocalStateBaseline',
53
+ 'createShareableHtml',
54
+ ]);
55
+
56
+ let compiled;
57
+ try {
58
+ compiled = core.compileLocal(source);
59
+ } catch (error) {
60
+ throw new CliError(
61
+ `The compiler failed on "${fileLabel}": ${errorText(error)}`,
62
+ EXIT.DOCUMENT,
63
+ { cause: error },
64
+ );
65
+ }
66
+ if (!compiled || typeof compiled !== 'object' || !Array.isArray(compiled.diagnostics)) {
67
+ throw new CliError('The core build returned an invalid compile result. Run "npm run build" again.', EXIT.DOCUMENT);
68
+ }
69
+
70
+ const diagnostics = compiled.diagnostics;
71
+ const errors = diagnostics.filter((diagnostic) => diagnostic?.severity === 'error');
72
+ const warnings = diagnostics.filter((diagnostic) => diagnostic?.severity === 'warning');
73
+ if (compiled.ok !== true || errors.length > 0) {
74
+ writeDiagnostics(stderr, fileLabel, diagnostics);
75
+ if (diagnostics.length === 0) {
76
+ stderr.write(`reactive-md: error: "${fileLabel}" could not be compiled.\n`);
77
+ }
78
+ throw new CliError('', EXIT.DOCUMENT, { reported: true });
79
+ }
80
+ if (warnings.length > 0) {
81
+ writeDiagnostics(stderr, fileLabel, warnings);
82
+ if (options.strict) {
83
+ stderr.write('reactive-md: error: warnings are treated as errors because --strict is set.\n');
84
+ throw new CliError('', EXIT.DOCUMENT, { reported: true });
85
+ }
86
+ }
87
+
88
+ /* ------------------------------------------------------------ state baseline */
89
+ let outcome;
90
+ let stateLabel = fileLabel;
91
+ try {
92
+ if (options.stateFile !== undefined) {
93
+ const statePath = path.resolve(options.stateFile);
94
+ stateLabel = displayPath(statePath);
95
+ const stateText = await readTextFile(statePath, {
96
+ label: 'Cannot read state file',
97
+ exitCode: EXIT.IO,
98
+ });
99
+ outcome = core.resolveLocalStateBaseline(compiled.document, stateText);
100
+ } else {
101
+ const generated = core.createLocalStateFile(
102
+ compiled.document,
103
+ compiled.document.initialState,
104
+ generator,
105
+ );
106
+ outcome = core.resolveLocalStateBaseline(compiled.document, generated);
107
+ }
108
+ } catch (error) {
109
+ if (error instanceof CliError) throw error;
110
+ throw new CliError(
111
+ `Cannot resolve the exported state for "${fileLabel}": ${errorText(error)}`,
112
+ EXIT.DOCUMENT,
113
+ { cause: error },
114
+ );
115
+ }
116
+
117
+ if (!outcome || outcome.ok !== true || !outcome.baseline) {
118
+ const stateDiagnostics = Array.isArray(outcome?.diagnostics) ? outcome.diagnostics : [];
119
+ if (stateDiagnostics.length > 0) {
120
+ for (const diagnostic of stateDiagnostics) {
121
+ // Parsing/digest/parameter-set failures belong to the state file.
122
+ // Runtime constraint failures keep their document node position.
123
+ const code = typeof diagnostic?.code === 'string' ? diagnostic.code : '';
124
+ const diagnosticFile = code.startsWith('local.state.') ? stateLabel : fileLabel;
125
+ stderr.write(`${formatDiagnostic(diagnosticFile, diagnostic)}\n`);
126
+ }
127
+ } else {
128
+ stderr.write(`reactive-md: error: the exported state could not be resolved for "${fileLabel}".\n`);
129
+ }
130
+ throw new CliError('', EXIT.DOCUMENT, { reported: true });
131
+ }
132
+
133
+ const baseline = outcome.baseline;
134
+ let stateFile;
135
+ try {
136
+ stateFile = core.createLocalStateFile(baseline.document, baseline.state, generator);
137
+ } catch (error) {
138
+ throw new CliError(
139
+ `Cannot finalize the exported state for "${fileLabel}": ${errorText(error)}`,
140
+ EXIT.DOCUMENT,
141
+ { cause: error },
142
+ );
143
+ }
144
+
145
+ /* ------------------------------------------------------------------- assets */
146
+ const imageNodes = collectImageNodes(baseline.document.nodes);
147
+ /** @type {Map<string, string>} */
148
+ let byUrl = new Map();
149
+ // The shell records how many image nodes the document contains, including
150
+ // images the author chose to omit. Inline payloads are deduplicated
151
+ // separately by content.
152
+ const imageCount = imageNodes.length;
153
+
154
+ if (options.assets === 'omit') {
155
+ if (imageNodes.length > 0) {
156
+ stderr.write(
157
+ `reactive-md: warning: ${imageNodes.length} image(s) will render as alt text because --assets omit was selected.\n`,
158
+ );
159
+ if (options.strict) {
160
+ throw new CliError(
161
+ `--strict treats omitted images as an error; ${imageNodes.length} image(s) would not be inlined. `
162
+ + 'Re-run without --assets omit or without --strict.',
163
+ EXIT.ASSET,
164
+ );
165
+ }
166
+ }
167
+ } else if (imageNodes.length > 0) {
168
+ const collected = await collectInlineAssets({
169
+ document: baseline.document,
170
+ inputPath,
171
+ assetRoot: options.assetRoot,
172
+ });
173
+ byUrl = collected.byUrl;
174
+ }
175
+ const { urlPolicy, imageResolver } = createAssetPolicy(byUrl);
176
+
177
+ /* ------------------------------------------------------------- build inputs */
178
+ const css = await readArtifactText(packageRoot, 'css');
179
+ let runtimeScript;
180
+ if (options.mode === 'interactive') {
181
+ runtimeScript = await readArtifactText(packageRoot, 'standalone');
182
+ }
183
+ // The shared shell records verified image URLs in the auto-mount payload so
184
+ // the standalone renderer can hydrate the same data URLs without a global
185
+ // image-policy relaxation. Static output needs only the SSR markup.
186
+ const embeddedImages = options.mode === 'interactive' && byUrl.size > 0
187
+ ? Object.fromEntries(byUrl)
188
+ : undefined;
189
+ const { createElement, renderToString } = await loadReact();
190
+ const { LocalDocumentView } = await loadReactRenderer(packageRoot);
191
+ const notices = await readNotices(packageRoot);
192
+
193
+ /* -------------------------------------------------------------------- render */
194
+ let runtime;
195
+ try {
196
+ runtime = core.createLocalRuntime(baseline.document);
197
+ } catch (error) {
198
+ throw new CliError(
199
+ `Cannot create the document runtime for "${fileLabel}": ${errorText(error)}`,
200
+ EXIT.DOCUMENT,
201
+ { cause: error },
202
+ );
203
+ }
204
+
205
+ let staticMarkup;
206
+ try {
207
+ const props = {
208
+ document: baseline.document,
209
+ runtime,
210
+ mode: options.mode,
211
+ locale: options.locale,
212
+ colorScheme: options.colorScheme,
213
+ urlPolicy,
214
+ imageResolver,
215
+ };
216
+ if (options.mode === 'interactive') props.staticFirst = true;
217
+ staticMarkup = renderToString(createElement(LocalDocumentView, props));
218
+ } catch (error) {
219
+ throw new CliError(
220
+ `HTML rendering failed for "${fileLabel}": ${errorText(error)}`,
221
+ EXIT.DOCUMENT,
222
+ { cause: error },
223
+ );
224
+ } finally {
225
+ try {
226
+ runtime.dispose();
227
+ } catch {
228
+ /* Disposal is always best effort; the render error is more important. */
229
+ }
230
+ }
231
+
232
+ if (typeof staticMarkup !== 'string' || staticMarkup.trim() === '') {
233
+ throw new CliError(`The React renderer produced empty markup for "${fileLabel}".`, EXIT.DOCUMENT);
234
+ }
235
+
236
+ const explicitTitle = options.title !== undefined ? options.title.trim() : '';
237
+ const title = explicitTitle || extractDocumentTitle(baseline.document, path.basename(inputPath));
238
+
239
+ let html;
240
+ try {
241
+ html = core.createShareableHtml({
242
+ title,
243
+ source: baseline.document.source,
244
+ state: stateFile,
245
+ staticMarkup,
246
+ css,
247
+ mode: options.mode,
248
+ ...(runtimeScript === undefined ? {} : { runtimeScript }),
249
+ locale: options.locale,
250
+ colorScheme: options.colorScheme,
251
+ generator,
252
+ assets: options.assets,
253
+ imageCount,
254
+ ...(embeddedImages === undefined ? {} : { images: embeddedImages }),
255
+ notices,
256
+ });
257
+ } catch (error) {
258
+ throw new CliError(
259
+ `Cannot assemble the shareable HTML for "${fileLabel}": ${errorText(error)}`,
260
+ EXIT.DOCUMENT,
261
+ { cause: error },
262
+ );
263
+ }
264
+
265
+ await atomicWriteUtf8(outputPath, html);
266
+ stdout.write(`Wrote ${options.output}\n`);
267
+ return EXIT.OK;
268
+ }