@astryxdesign/cli 0.7.16 → 0.7.17-canary.g9a957aa

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 (229) hide show
  1. package/README.md +12 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +47 -9
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +32 -0
  14. package/api/build/kit/words.mjs +49 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +48 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +491 -186
  34. package/api/render/render.doc.mjs +10 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +38 -0
  46. package/api/theme/build/build.mjs +144 -24
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +35 -0
  50. package/api/theme-edit/_adapter.mjs +477 -41
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1077 -200
  53. package/api/theme-edit/_compiler.mjs +9 -0
  54. package/api/theme-edit/_context.mjs +60 -3
  55. package/api/theme-edit/_css.mjs +21 -1
  56. package/api/theme-edit/_edit.d.mts +22 -0
  57. package/api/theme-edit/_edit.mjs +932 -82
  58. package/api/theme-edit/_how-commands.d.mts +49 -0
  59. package/api/theme-edit/_how-commands.mjs +386 -1
  60. package/api/theme-edit/_how-question.d.mts +56 -0
  61. package/api/theme-edit/_how-question.mjs +3509 -168
  62. package/api/theme-edit/_how.mjs +104 -4
  63. package/api/theme-edit/_marks.d.mts +31 -5
  64. package/api/theme-edit/_marks.mjs +57 -5
  65. package/api/theme-edit/_normal.d.mts +137 -0
  66. package/api/theme-edit/_normal.mjs +612 -0
  67. package/api/theme-edit/_palette.mjs +10 -4
  68. package/api/theme-edit/_parts.d.mts +4 -0
  69. package/api/theme-edit/_parts.mjs +28 -2
  70. package/api/theme-edit/_preview-app.d.mts +7 -1
  71. package/api/theme-edit/_preview-app.mjs +191 -15
  72. package/api/theme-edit/_preview.d.mts +64 -8
  73. package/api/theme-edit/_preview.mjs +401 -83
  74. package/api/theme-edit/_settings.d.mts +139 -5
  75. package/api/theme-edit/_settings.mjs +1659 -112
  76. package/api/theme-edit/_tables.mjs +17 -1
  77. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  78. package/api/theme-edit/theme-edit.type.mjs +4 -1
  79. package/api/theme-edit/themeEditPreviewApp.doc.mjs +2 -2
  80. package/assets/codemods/run-codemod.mjs +73 -6
  81. package/assets/codemods/transforms/next/index.mjs +11 -1
  82. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  83. package/assets/docs/author-a-theme.doc.mjs +1 -0
  84. package/assets/docs/theme.doc.dense.mjs +2 -2
  85. package/assets/docs/theme.doc.mjs +1 -1
  86. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  87. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  88. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  89. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  90. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  91. package/assets/docs/use-a-theme.doc.mjs +1 -1
  92. package/assets/docs.generated.json +2 -2
  93. package/assets/self-audit.generated.json +1 -1
  94. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  95. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  96. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  97. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  98. package/assets/templates/components.generated.json +1 -1
  99. package/assets/templates/pages/ai-chat/template.doc.mjs +8 -4
  100. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  101. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  102. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  103. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  104. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  105. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  106. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  107. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  108. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  110. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  111. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  112. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  113. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  114. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  115. package/assets/templates/pages/editor/template.doc.mjs +1 -7
  116. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  117. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  118. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  119. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  120. package/assets/templates/pages/ide/page.tsx +24 -2
  121. package/assets/templates/pages/library/template.doc.mjs +4 -1
  122. package/assets/templates/pages/login/template.doc.mjs +2 -1
  123. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  124. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  125. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  126. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  127. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  128. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  129. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  130. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  131. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  132. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  133. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  134. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  135. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  136. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  137. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  138. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  139. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -1
  140. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  141. package/authoring/debug/parse.d.mts +3 -3
  142. package/authoring/doctypes/_schema.d.mts +3 -3
  143. package/authoring/doctypes/command/command.doc.mjs +1 -1
  144. package/authoring/doctypes/template/template.doc.mjs +1 -1
  145. package/authoring/doctypes/template/type.ts +9 -0
  146. package/clients/cli/bin/astryx.mjs +6 -9
  147. package/clients/cli/build-id.generated.json +1 -1
  148. package/clients/cli/commands/component.doc.mjs +1 -1
  149. package/clients/cli/commands/component.mjs +20 -2
  150. package/clients/cli/commands/docs.doc.mjs +7 -1
  151. package/clients/cli/commands/docs.mjs +3 -1
  152. package/clients/cli/commands/doctor.mjs +22 -14
  153. package/clients/cli/commands/experimental/render.mjs +32 -1
  154. package/clients/cli/commands/experimental/theme.mjs +27 -2
  155. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  156. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  157. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  158. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  159. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  160. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  161. package/clients/cli/commands/search.doc.mjs +2 -1
  162. package/clients/cli/commands/search.mjs +6 -1
  163. package/clients/cli/commands/template.mjs +4 -2
  164. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  165. package/clients/cli/commands/theme.doc.mjs +1 -1
  166. package/clients/cli/commands/theme.mjs +138 -3
  167. package/clients/cli/commands/upgrade.mjs +42 -7
  168. package/clients/cli/index.mjs +1 -1
  169. package/clients/cli/lib/component-format.mjs +205 -98
  170. package/clients/cli/lib/hook-format.mjs +9 -19
  171. package/clients/cli/manifest.generated.json +1 -1
  172. package/foundation/agent-docs/agent-docs.mjs +1 -1
  173. package/foundation/config/theme-state.d.mts +13 -1
  174. package/foundation/config/theme-state.mjs +47 -7
  175. package/foundation/discovery/component-discovery.d.mts +11 -0
  176. package/foundation/discovery/component-discovery.mjs +27 -2
  177. package/foundation/discovery/component-replacement.mjs +130 -1
  178. package/foundation/discovery/entry-name-files.d.mts +43 -0
  179. package/foundation/discovery/entry-name-files.mjs +264 -0
  180. package/foundation/discovery/hook-discovery.d.mts +8 -2
  181. package/foundation/discovery/hook-discovery.mjs +20 -7
  182. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  183. package/foundation/discovery/runner-allowlist.mjs +2 -0
  184. package/foundation/discovery/template-adapter.d.mts +52 -0
  185. package/foundation/discovery/template-adapter.mjs +169 -0
  186. package/foundation/discovery/theme-imports.d.mts +14 -0
  187. package/foundation/discovery/theme-imports.mjs +43 -1
  188. package/foundation/doc-compiler/import.mjs +7 -1
  189. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  190. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  191. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  192. package/foundation/fs/cache-eviction.d.mts +21 -0
  193. package/foundation/fs/cache-eviction.mjs +73 -0
  194. package/foundation/fs/gather-cache.d.mts +25 -4
  195. package/foundation/fs/gather-cache.mjs +138 -52
  196. package/foundation/fs/jiti-cache.d.mts +19 -1
  197. package/foundation/fs/jiti-cache.mjs +130 -6
  198. package/foundation/fs/kept-tree.d.mts +60 -0
  199. package/foundation/fs/kept-tree.mjs +154 -0
  200. package/foundation/fs/module-loader.d.mts +18 -2
  201. package/foundation/fs/module-loader.mjs +92 -20
  202. package/foundation/identity/provider-identity.d.mts +6 -0
  203. package/foundation/identity/provider-identity.mjs +10 -1
  204. package/foundation/render/file-header.d.mts +66 -0
  205. package/foundation/render/file-header.mjs +118 -0
  206. package/foundation/render/host-answer.d.mts +18 -0
  207. package/foundation/render/host-answer.mjs +46 -0
  208. package/foundation/render/host-exit.d.mts +1 -0
  209. package/foundation/render/host-exit.mjs +6 -1
  210. package/foundation/render/html-reader.d.mts +55 -2
  211. package/foundation/render/html-reader.mjs +145 -26
  212. package/foundation/render/markup-edits.d.mts +57 -0
  213. package/foundation/render/markup-edits.mjs +182 -0
  214. package/foundation/render/page-host.mjs +29 -12
  215. package/foundation/render/page-worker.mjs +79 -10
  216. package/foundation/render/render-page.d.mts +34 -2
  217. package/foundation/render/render-page.mjs +210 -29
  218. package/foundation/render/source-block.d.mts +73 -6
  219. package/foundation/render/source-block.mjs +170 -19
  220. package/foundation/render/ts-paths.d.mts +4 -1
  221. package/foundation/render/ts-paths.mjs +7 -3
  222. package/foundation/response/error-codes.d.mts +2 -1
  223. package/foundation/response/error-codes.doc.mjs +7 -1
  224. package/foundation/response/error-codes.mjs +7 -0
  225. package/foundation/text/string-utils.d.mts +3 -2
  226. package/foundation/text/string-utils.mjs +16 -3
  227. package/foundation/text/suggest-order.d.mts +9 -0
  228. package/foundation/text/suggest-order.mjs +13 -0
  229. package/package.json +6 -6
@@ -17,17 +17,22 @@
17
17
  */
18
18
 
19
19
  import * as fs from 'node:fs';
20
+ import * as os from 'node:os';
20
21
  import * as path from 'node:path';
21
22
  import {fork, spawnSync} from 'node:child_process';
23
+ import {builtinModules} from 'node:module';
22
24
  import {fileURLToPath} from 'node:url';
23
25
  import postcss from 'postcss';
24
26
  import {assetDataUri, isAssetBytes, isAssetPath, RenderAssetError} from './assets.mjs';
25
27
  import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';
26
- import {sourceBlock} from './source-block.mjs';
28
+ import {RENDER_FORMAT, asParsed, sha256, sourceBlock} from './source-block.mjs';
27
29
  import {embeddedPathProblem} from './embedded-files.mjs';
28
- import {resolveServed} from './served-packages.mjs';
30
+ import {isServedPackage, resolveServed} from './served-packages.mjs';
29
31
  import {CHART_CSS} from './charts.mjs';
30
32
  import {HOST_EXIT} from './host-exit.mjs';
33
+ import {endNote, headerNote} from './file-header.mjs';
34
+ import {textRuns} from './markup-edits.mjs';
35
+ import {findNodeModulesPackage} from '../fs/paths.mjs';
31
36
 
32
37
  /** How long one page may take to render before it is stopped. */
33
38
  export const RENDER_TIMEOUT_MS = 60_000;
@@ -68,19 +73,33 @@ export class RenderError extends Error {
68
73
  }
69
74
 
70
75
  /**
71
- * The nearest folder at or above `dir` with a package.json, else `dir`.
76
+ * The nearest folder at or above `dir` with a package.json, or null outside
77
+ * a project.
72
78
  * @param {string} dir
79
+ * @returns {string | null}
73
80
  */
74
- function projectRootOf(dir) {
75
- let d = dir;
76
- for (;;) {
81
+ function projectOf(dir) {
82
+ for (let d = dir; ; d = path.dirname(d)) {
77
83
  if (fs.existsSync(path.join(d, 'package.json'))) return d;
78
- const up = path.dirname(d);
79
- if (up === d) return dir;
80
- d = up;
84
+ if (path.dirname(d) === d) return null;
81
85
  }
82
86
  }
83
87
 
88
+ /**
89
+ * The folder whose modules the page carries: its project's. Outside a
90
+ * project, the current folder when it holds the page, so a page with
91
+ * neighbours above its own folder (as a restore lays them out) carries them;
92
+ * else the page's folder.
93
+ * @param {string} dir
94
+ * @param {string} [cwd]
95
+ */
96
+ function carryScopeOf(dir, cwd) {
97
+ const project = projectOf(dir);
98
+ if (project) return project;
99
+ const fromCwd = cwd ? path.relative(cwd, dir) : '..';
100
+ return fromCwd.startsWith('..') || path.isAbsolute(fromCwd) ? dir : /** @type {string} */ (cwd);
101
+ }
102
+
84
103
  /** @param {string} s */
85
104
  const escapeHtml = s =>
86
105
  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
@@ -305,24 +324,61 @@ function hostEndError(/** @type {number | null} */ code) {
305
324
  if (code === HOST_EXIT.timeout) {
306
325
  return new RenderError('ERR_RENDER_TIMEOUT', "The page's process stopped at its own time limit before this process read an answer.", {reason: 'host-timeout', exit: code});
307
326
  }
327
+ if (code === HOST_EXIT.sendFailed) {
328
+ return new RenderError('ERR_RENDER_FAILED', "The page's process could not send its answer to this process.", {reason: 'send-failed', exit: code});
329
+ }
308
330
  return new RenderError('ERR_RENDER_FAILED', `The page's process ended without an answer (exit ${code}).`, {reason: 'host-ended', exit: code});
309
331
  }
310
332
 
333
+ /**
334
+ * The error for a host that ended with no answer reaching this process, from
335
+ * the state it left in its per-run file: an answer it sent that never
336
+ * arrived, or the stage it ended in.
337
+ * @param {number | null} code
338
+ * @param {string | undefined} stateFile
339
+ */
340
+ function noMessageError(code, stateFile) {
341
+ if (code !== 0 && code !== null && Object.values(HOST_EXIT).includes(code)) return hostEndError(code);
342
+ /** @type {any} */
343
+ let saved = null;
344
+ try {
345
+ saved = stateFile ? JSON.parse(fs.readFileSync(stateFile, 'utf8')) : null;
346
+ } catch {
347
+ // No readable state: fall back to the bare message below.
348
+ }
349
+ if (!saved) return hostEndError(code);
350
+ const detail = {exit: code, stage: saved.stage, elapsedMs: saved.elapsedMs, rssMb: saved.rssMb, freeMb: saved.freeMb, ...(saved.stderrTail ? {stderrTail: saved.stderrTail} : {})};
351
+ if (saved.answered === 'sent') {
352
+ return new RenderError('ERR_RENDER_FAILED', `The page's process sent its answer, but this process did not receive it (exit ${code}).`, {reason: 'answer-lost', ...detail});
353
+ }
354
+ if (saved.answered === 'sending') {
355
+ return new RenderError('ERR_RENDER_FAILED', `The page's process ended while it sent its answer (exit ${code}).`, {reason: 'ended-while-sending', ...detail});
356
+ }
357
+ const seconds = Math.round((saved.elapsedMs ?? 0) / 1000);
358
+ const last = saved.stderrTail ? ` Its last output: ${String(saved.stderrTail).split('\n').at(-1)}` : '';
359
+ return new RenderError(
360
+ 'ERR_RENDER_FAILED',
361
+ `The page's process ended without an answer (exit ${code}) while ${saved.stage}, after ${seconds} seconds, with ${saved.freeMb} MB of memory free.${last}`,
362
+ {reason: 'host-ended', ...detail},
363
+ );
364
+ }
365
+
311
366
  /**
312
367
  * Run the page in a host process (page-host.mjs), stopping it after
313
368
  * `timeoutMs`. The host runs the page in a worker thread, and it exits when
314
369
  * this process goes away.
315
- * @param {{entry: string, root: string, served: ServedSet | null, withoutSegmenter: boolean}} input
370
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null, withoutSegmenter: boolean}} input
316
371
  * @param {number} timeoutMs
317
372
  * @returns {Promise<any>} the page's answer, or `{crashed: how}` when a
318
373
  * native crash ended the host
319
374
  */
320
375
  function runWorker(input, timeoutMs) {
321
- return new Promise((resolve, reject) => {
376
+ return withHostStateFile(stateFile => {
322
377
  const data = {
323
378
  ...input,
324
379
  served: input.served ? {dir: input.served.dir, integrations: [...input.served.integrations]} : null,
325
380
  timeoutMs,
381
+ stateFile,
326
382
  };
327
383
  const host = fork(fileURLToPath(new URL('./page-host.mjs', import.meta.url)), [JSON.stringify(data)], {
328
384
  // Never the CLI's own flags (such as --input-type).
@@ -330,6 +386,52 @@ function runWorker(input, timeoutMs) {
330
386
  stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
331
387
  serialization: 'advanced',
332
388
  });
389
+ return awaitHost(host, {timeoutMs, withoutSegmenter: input.withoutSegmenter, stateFile});
390
+ });
391
+ }
392
+
393
+ /**
394
+ * Run `use` with a state file for one host in a new folder under the system's
395
+ * temporary folder, never in the project, and remove the folder after. The
396
+ * state file only explains a failure: without a temporary folder, `use` gets
397
+ * none and the render runs without it.
398
+ * @template T
399
+ * @param {(stateFile: string | undefined) => Promise<T>} use
400
+ * @param {{makeTempDir?: (prefix: string) => string}} [options]
401
+ * @returns {Promise<T>}
402
+ */
403
+ export async function withHostStateFile(
404
+ use,
405
+ {makeTempDir = prefix => fs.mkdtempSync(prefix)} = {},
406
+ ) {
407
+ /** @type {string} */
408
+ let dir;
409
+ try {
410
+ dir = makeTempDir(path.join(os.tmpdir(), 'astryx-render-'));
411
+ } catch {
412
+ // No temporary folder (missing or read-only): render without the state file.
413
+ return use(undefined);
414
+ }
415
+ try {
416
+ return await use(path.join(dir, 'host-state.json'));
417
+ } finally {
418
+ try {
419
+ fs.rmSync(dir, {recursive: true, force: true, maxRetries: 3});
420
+ } catch {
421
+ // Best effort: a removal that fails (a file still held open) never
422
+ // replaces the render's own result.
423
+ }
424
+ }
425
+ }
426
+
427
+ /**
428
+ * The page's answer from its host process, or the reason it has none.
429
+ * @param {import('node:child_process').ChildProcess} host
430
+ * @param {{timeoutMs: number, withoutSegmenter: boolean, stateFile?: string}} options
431
+ * @returns {Promise<any>}
432
+ */
433
+ export function awaitHost(host, {timeoutMs, withoutSegmenter, stateFile}) {
434
+ return new Promise((resolve, reject) => {
333
435
  let settled = false;
334
436
  /** @param {() => void} settle */
335
437
  const finish = settle => {
@@ -369,12 +471,14 @@ function runWorker(input, timeoutMs) {
369
471
  host.once('error', error => {
370
472
  finish(() => reject(new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`)));
371
473
  });
372
- host.once('exit', (code, signal) => {
474
+ // 'close' comes after the IPC channel drains, so an answer the host sent
475
+ // just before it exited still wins; 'exit' can come first under load.
476
+ host.once('close', (code, signal) => {
373
477
  finish(() => {
374
478
  const crash = crashOf(code, signal);
375
479
  if (crash) resolve({crashed: crash});
376
- else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter: input.withoutSegmenter}));
377
- else reject(hostEndError(code));
480
+ else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter}));
481
+ else reject(noMessageError(code, stateFile));
378
482
  });
379
483
  });
380
484
  });
@@ -383,7 +487,7 @@ function runWorker(input, timeoutMs) {
383
487
  /**
384
488
  * Run the page. When this Node crashes in Intl.Segmenter, run it once more
385
489
  * without Intl.Segmenter and say so in a warning.
386
- * @param {{entry: string, root: string, served: ServedSet | null}} input
490
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null}} input
387
491
  * @param {number} timeoutMs
388
492
  * @param {RenderWarning[]} warnings
389
493
  */
@@ -484,6 +588,26 @@ function inlineAssets(text, kind, ctx) {
484
588
  });
485
589
  }
486
590
 
591
+ /**
592
+ * The version of a package the page rendered with: the package set's copy
593
+ * when the page took it from there, else the copy Node's resolver finds from
594
+ * the page's folder.
595
+ * @param {string} name
596
+ * @param {string} dir the page's folder
597
+ * @param {Map<string, string>} setDirs the packages the page took from the package set: their folders
598
+ * @returns {string | null}
599
+ */
600
+ function installedVersion(name, dir, setDirs) {
601
+ const packageDir = setDirs.get(name) ?? findNodeModulesPackage(dir, name)?.packageDir;
602
+ if (!packageDir) return null;
603
+ try {
604
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
605
+ return pkg?.name === name && typeof pkg.version === 'string' ? pkg.version : null;
606
+ } catch {
607
+ return null;
608
+ }
609
+ }
610
+
487
611
  /** The light and dark switch every rendered page carries. */
488
612
  const SCHEME_CSS =
489
613
  ':root{color-scheme:light dark}:root[data-theme="light"]{color-scheme:light}:root[data-theme="dark"]{color-scheme:dark}';
@@ -491,18 +615,27 @@ const SCHEME_CSS =
491
615
  /**
492
616
  * Render a page module to one self-contained HTML file.
493
617
  * @param {string} entry absolute path of the page module
494
- * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null}} [options]
618
+ * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null, output?: string, cwd?: string}} [options]
495
619
  * `served`: the Core of the package set the CLI runs from, for the packages
496
- * the page's folder has no copy of
620
+ * the page's folder has no copy of; `output`: the file the HTML goes to;
621
+ * `cwd`: the current folder, whose files are the page's own outside a
622
+ * project.
623
+ * With `output`, the file describes itself: notes at its top and end name
624
+ * what made it and the commands that give the page back and render it
625
+ * again, and its embedded source records the CLI version, the packages
626
+ * the page rendered with, and the markup as rendered.
497
627
  * @returns {Promise<RenderedPage>}
498
628
  */
499
629
  export async function renderPage(entry, options = {}) {
500
630
  const dir = path.dirname(entry);
501
- const root = projectRootOf(dir);
631
+ // The project's folder, else the page's: where its tsconfig.json and
632
+ // public/ images are read.
633
+ const root = projectOf(dir) ?? dir;
634
+ const scope = carryScopeOf(dir, options.cwd);
502
635
  const served = options.served ?? null;
503
636
  /** @type {RenderWarning[]} */
504
637
  const warnings = [];
505
- const message = await runPage({entry, root, served}, options.timeoutMs ?? RENDER_TIMEOUT_MS, warnings);
638
+ const message = await runPage({entry, root, scope, served}, options.timeoutMs ?? RENDER_TIMEOUT_MS, warnings);
506
639
  if (!message.ok) {
507
640
  throw new RenderError(message.error.code, message.error.message, message.error.detail);
508
641
  }
@@ -696,12 +829,12 @@ export async function renderPage(entry, options = {}) {
696
829
  // (`<img src="./logo.png">`, `url(./bg.png)`) are carried too, so the page
697
830
  // comes back with them; a package's own files are not.
698
831
  for (const sheet of carriedCss) {
699
- const rel = path.relative(root, sheet);
832
+ const rel = path.relative(scope, sheet);
700
833
  if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
701
834
  if (!files.includes(sheet)) files.push(sheet);
702
835
  }
703
836
  for (const asset of ctx.localAssets) {
704
- const rel = path.relative(root, asset);
837
+ const rel = path.relative(scope, asset);
705
838
  if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
706
839
  if (files.includes(asset)) continue;
707
840
  // Carried only when its bytes are a known image, font or media format,
@@ -739,14 +872,62 @@ export async function renderPage(entry, options = {}) {
739
872
  }
740
873
  const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(markup)?.[1]?.replace(/<[^>]*>/g, '').trim();
741
874
  const title = options.title ?? (heading ? decodeAttr(heading) : path.basename(entry).replace(/\.[^.]+$/, ''));
742
- const html =
743
- '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
744
- '<meta name="viewport" content="width=device-width,initial-scale=1">' +
745
- '<meta name="color-scheme" content="light dark">' +
746
- `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">` +
747
- `<title>${escapeHtml(title)}</title>` +
748
- `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style></head><body>${markup}` +
749
- `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
875
+ const generator = `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">`;
876
+ const style = `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style>`;
877
+ let html;
878
+ if (options.output) {
879
+ // The charset and generator metas come first: a browser reads the
880
+ // charset only from the first 1024 bytes, and a CLI decides whether a
881
+ // render wrote a file from its first 4096.
882
+ const setDirs = new Map(/** @type {{name: string, dir: string}[]} */ (message.fromSet ?? []).map(p => [p.name, p.dir]));
883
+ const names = new Set([...(message.packages ?? []), ...setDirs.keys(), 'react', 'react-dom']);
884
+ if (hasCore) names.add('@astryxdesign/core');
885
+ /** @type {Record<string, string>} */
886
+ const packages = {};
887
+ for (const name of [...names].sort()) {
888
+ if (name.startsWith('node:') || builtinModules.includes(name)) continue;
889
+ const version = installedVersion(name, dir, setDirs);
890
+ if (version) packages[name] = version;
891
+ }
892
+ const file = path.basename(options.output);
893
+ const facts = {
894
+ cli: options.version ?? null,
895
+ format: RENDER_FORMAT,
896
+ file,
897
+ page: path.relative(root, entry).split(path.sep).join('/'),
898
+ restored: `${file.replace(/\.[^.]+$/, '')}-restored/${embedded[0].path}`,
899
+ files: embedded.map(f => f.path),
900
+ packages,
901
+ install: Object.entries(packages)
902
+ .filter(([name]) => !isServedPackage(name, []))
903
+ .map(([name, version]) => `${name}@${version}`),
904
+ ...(options.title === undefined ? {} : {title: options.title}),
905
+ };
906
+ const record = {
907
+ ...(facts.cli ? {cli: facts.cli} : {}),
908
+ page: facts.page,
909
+ ...(options.title === undefined ? {} : {title: options.title}),
910
+ packages,
911
+ markup: {
912
+ sha256: sha256(asParsed(markup)),
913
+ style: sha256(asParsed(style)),
914
+ text: Buffer.from(JSON.stringify({title, runs: textRuns(markup)})).toString('base64'),
915
+ },
916
+ };
917
+ html =
918
+ `<!doctype html><html lang="en"><head><meta charset="utf-8">${generator}\n${headerNote(facts)}\n` +
919
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
920
+ '<meta name="color-scheme" content="light dark">' +
921
+ `<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
922
+ `${sourceBlock(path.basename(entry), embedded, record)}\n${endNote(facts)}\n</body></html>\n`;
923
+ } else {
924
+ html =
925
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
926
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
927
+ '<meta name="color-scheme" content="light dark">' +
928
+ `${generator}<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
929
+ `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
930
+ }
750
931
  return {
751
932
  html,
752
933
  files: embedded.map(f => f.path),
@@ -5,16 +5,17 @@
5
5
  * The data block for a page's files.
6
6
  * @param {string} entry the page's file name
7
7
  * @param {{path: string, bytes: Buffer}[]} files the page first
8
+ * @param {RenderRecord} [record] what the render records about itself
8
9
  * @returns {string}
9
10
  */
10
11
  export function sourceBlock(entry: string, files: {
11
12
  path: string;
12
13
  bytes: Buffer;
13
- }[]): string;
14
+ }[], record?: RenderRecord): string;
14
15
  /**
15
16
  * Read the embedded source from a rendered file.
16
17
  * @param {string} html
17
- * @returns {{found: false} | {found: true, source: EmbeddedSource} | {found: true, damaged: string}}
18
+ * @returns {{found: false} | {found: true, source: EmbeddedSource} | {found: true, damaged: string} | {found: true, newer: {format: number, cli: string | null}}}
18
19
  */
19
20
  export function readSourceBlock(html: string): {
20
21
  found: false;
@@ -24,10 +25,49 @@ export function readSourceBlock(html: string): {
24
25
  } | {
25
26
  found: true;
26
27
  damaged: string;
28
+ } | {
29
+ found: true;
30
+ newer: {
31
+ format: number;
32
+ cli: string | null;
33
+ };
27
34
  };
35
+ /**
36
+ * The markup between `<body>` and the embedded source: what a render wrote
37
+ * there, unless someone changed it since. Null when the file no longer has
38
+ * that shape.
39
+ * @param {string} html
40
+ * @returns {string | null}
41
+ */
42
+ export function renderedMarkupOf(html: string): string | null;
43
+ /**
44
+ * The title and the <style> element a render wrote in <head>, unless someone
45
+ * changed them since.
46
+ * @param {string} html
47
+ * @returns {{title: string | null, style: string | null}}
48
+ */
49
+ export function renderedHeadOf(html: string): {
50
+ title: string | null;
51
+ style: string | null;
52
+ };
53
+ /**
54
+ * The title and the runs of text a record keeps, or null when the record
55
+ * keeps none or they do not decode.
56
+ * @param {{text?: unknown}} markup
57
+ * @returns {{title: string | null, runs: string[]} | null}
58
+ */
59
+ export function recordedText(markup: {
60
+ text?: unknown;
61
+ }): {
62
+ title: string | null;
63
+ runs: string[];
64
+ } | null;
28
65
  /** The script type of the embedded-source block. */
29
66
  export const SOURCE_TYPE: "application/x-astryx-source";
30
- export function sha256(bytes: Buffer): string;
67
+ /** The render format this CLI writes, and the newest one it reads. */
68
+ export const RENDER_FORMAT: 1;
69
+ export function sha256(bytes: Buffer | string): string;
70
+ export function asParsed(text: string): string;
31
71
  export type EmbeddedFile = {
32
72
  /**
33
73
  * - Path relative to the folder that holds every embedded file, `/`-separated; the page itself first.
@@ -42,11 +82,38 @@ export type EmbeddedFile = {
42
82
  */
43
83
  base64: string;
44
84
  };
45
- export type EmbeddedSource = {
46
- version: 1;
85
+ /**
86
+ * What the render records about itself beside the files. Every field is
87
+ * optional: files from older CLIs have none of them.
88
+ */
89
+ export type RenderRecord = {
90
+ /**
91
+ * - The version of the CLI that rendered the file.
92
+ */
93
+ cli?: string | undefined;
94
+ /**
95
+ * - The page's path from its project's root, `/`-separated.
96
+ */
97
+ page?: string | undefined;
47
98
  /**
48
- * - The page's file name.
99
+ * - The title given with --title, which a render again needs too.
49
100
  */
101
+ title?: string | undefined;
102
+ /**
103
+ * - The packages the page rendered with, by name: their versions.
104
+ */
105
+ packages?: Record<string, string> | undefined;
106
+ /**
107
+ * - The page as rendered, so a reverse can tell what changed after the render: the SHA-256 of the markup in <body> and of the <style> element, and `text`, the base64 of the JSON `{title, runs}` (the title and the markup's runs of text in order). The text stays encoded so that a find-and-replace over the page's text cannot change the record too.
108
+ */
109
+ markup?: {
110
+ sha256: string;
111
+ style?: string;
112
+ text?: string;
113
+ } | undefined;
114
+ };
115
+ export type EmbeddedSource = RenderRecord & {
116
+ version: number;
50
117
  entry: string;
51
118
  files: EmbeddedFile[];
52
119
  };