@astryxdesign/cli 0.7.16 → 0.7.17-canary.g0135e03

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 (369) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +12 -0
  3. package/api/build/_adapter.mjs +51 -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 +4 -3
  7. package/api/build/build.type.d.mts +2 -2
  8. package/api/build/build.type.mjs +3 -3
  9. package/api/build/kit/kind.d.mts +2 -1
  10. package/api/build/kit/kind.mjs +199 -10
  11. package/api/build/kit/kit.mjs +6 -4
  12. package/api/build/kit/rank.d.mts +4 -2
  13. package/api/build/kit/rank.mjs +125 -24
  14. package/api/build/kit/start.d.mts +5 -4
  15. package/api/build/kit/start.mjs +12 -8
  16. package/api/build/kit/weights.d.mts +39 -3
  17. package/api/build/kit/weights.json +1 -1
  18. package/api/build/kit/weights.mjs +340 -43
  19. package/api/build/kit/word-model.d.mts +23 -0
  20. package/api/build/kit/word-model.mjs +46 -0
  21. package/api/build/kit/words.d.mts +48 -0
  22. package/api/build/kit/words.mjs +90 -1
  23. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  24. package/api/component/list/list.d.mts +1 -1
  25. package/api/component/list/list.mjs +48 -6
  26. package/api/discover/_adapter.d.mts +1 -1
  27. package/api/discover/search/search.mjs +3 -2
  28. package/api/docs/_adapter.d.mts +26 -2
  29. package/api/docs/_adapter.mjs +219 -6
  30. package/api/docs/docs.d.mts +3 -0
  31. package/api/docs/docs.doc.mjs +7 -1
  32. package/api/docs/docs.mjs +12 -0
  33. package/api/docs/docs.type.d.mts +5 -0
  34. package/api/docs/docs.type.mjs +2 -0
  35. package/api/docs/node/node.mjs +1 -1
  36. package/api/doctor/_adapter.d.mts +27 -5
  37. package/api/doctor/_adapter.mjs +83 -10
  38. package/api/doctor/built-checks.mjs +40 -14
  39. package/api/doctor/doctor.d.mts +4 -3
  40. package/api/doctor/doctor.mjs +14 -7
  41. package/api/doctor/theme-checks.mjs +121 -17
  42. package/api/icon/_records.mjs +2 -1
  43. package/api/index.d.mts +2 -0
  44. package/api/index.mjs +2 -0
  45. package/api/integration/_adapter.d.mts +44 -0
  46. package/api/integration/_adapter.mjs +77 -1
  47. package/api/integration/authoring-checks.mjs +6 -6
  48. package/api/integration/example-scope.d.mts +14 -0
  49. package/api/integration/example-scope.mjs +44 -0
  50. package/api/integration/example-scope.type.d.mts +29 -0
  51. package/api/integration/example-scope.type.mjs +25 -0
  52. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  53. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  54. package/api/integration/validate-integration.mjs +19 -1
  55. package/api/integration/validate-integration.type.d.mts +9 -0
  56. package/api/integration/validate-integration.type.mjs +1 -1
  57. package/api/integration/validateIntegration.doc.mjs +1 -1
  58. package/api/render/_adapter.mjs +591 -195
  59. package/api/render/render.doc.mjs +11 -3
  60. package/api/render/render.type.d.mts +52 -0
  61. package/api/render/render.type.mjs +31 -1
  62. package/api/search/ORDERING.md +1 -1
  63. package/api/search/_adapter.d.mts +9 -0
  64. package/api/search/_adapter.mjs +85 -0
  65. package/api/search/_candidate-score.mjs +51 -32
  66. package/api/search/_fit-order.mjs +3 -3
  67. package/api/search/_gather-components.d.mts +3 -2
  68. package/api/search/_gather-components.mjs +12 -3
  69. package/api/search/_lexical.d.mts +5 -0
  70. package/api/search/_lexical.mjs +8 -2
  71. package/api/search/_result.d.mts +11 -9
  72. package/api/search/_result.mjs +4 -4
  73. package/api/search/_score.d.mts +6 -1
  74. package/api/search/_score.mjs +15 -3
  75. package/api/search/search-index.mjs +7 -1
  76. package/api/search/search.d.mts +1 -1
  77. package/api/theme/_adapter.mjs +12 -1
  78. package/api/theme/build/build.d.mts +122 -1
  79. package/api/theme/build/build.mjs +412 -84
  80. package/api/theme/build/core-interception.d.mts +10 -0
  81. package/api/theme/build/core-interception.mjs +10 -0
  82. package/api/theme/build/font-warning.d.mts +23 -3
  83. package/api/theme/build/font-warning.mjs +54 -5
  84. package/api/theme/build/icon-imports.mjs +25 -2
  85. package/api/theme/theme.type.d.mts +10 -0
  86. package/api/theme/theme.type.mjs +7 -1
  87. package/api/theme-edit/_adapter.d.mts +103 -3
  88. package/api/theme-edit/_adapter.mjs +961 -82
  89. package/api/theme-edit/_catalog.mjs +19 -4
  90. package/api/theme-edit/_check.d.mts +63 -24
  91. package/api/theme-edit/_check.mjs +2467 -362
  92. package/api/theme-edit/_color.d.mts +10 -0
  93. package/api/theme-edit/_color.mjs +49 -1
  94. package/api/theme-edit/_compiler.mjs +89 -6
  95. package/api/theme-edit/_context.d.mts +3 -3
  96. package/api/theme-edit/_context.mjs +165 -54
  97. package/api/theme-edit/_css.d.mts +14 -0
  98. package/api/theme-edit/_css.mjs +46 -1
  99. package/api/theme-edit/_edit.d.mts +31 -4
  100. package/api/theme-edit/_edit.mjs +2433 -204
  101. package/api/theme-edit/_how-commands.d.mts +72 -1
  102. package/api/theme-edit/_how-commands.mjs +759 -9
  103. package/api/theme-edit/_how-question.d.mts +82 -5
  104. package/api/theme-edit/_how-question.mjs +6473 -553
  105. package/api/theme-edit/_how.d.mts +2 -1
  106. package/api/theme-edit/_how.mjs +237 -41
  107. package/api/theme-edit/_marks.d.mts +31 -5
  108. package/api/theme-edit/_marks.mjs +57 -5
  109. package/api/theme-edit/_name-rule.d.mts +11 -0
  110. package/api/theme-edit/_name-rule.mjs +12 -0
  111. package/api/theme-edit/_normal.d.mts +292 -0
  112. package/api/theme-edit/_normal.mjs +1454 -0
  113. package/api/theme-edit/_palette.mjs +10 -4
  114. package/api/theme-edit/_part-words.d.mts +31 -0
  115. package/api/theme-edit/_part-words.mjs +126 -0
  116. package/api/theme-edit/_parts.d.mts +18 -1
  117. package/api/theme-edit/_parts.mjs +246 -23
  118. package/api/theme-edit/_preview-app.d.mts +7 -1
  119. package/api/theme-edit/_preview-app.mjs +776 -187
  120. package/api/theme-edit/_preview.d.mts +100 -14
  121. package/api/theme-edit/_preview.mjs +582 -139
  122. package/api/theme-edit/_project.d.mts +4 -0
  123. package/api/theme-edit/_project.mjs +3 -1
  124. package/api/theme-edit/_settings.d.mts +417 -42
  125. package/api/theme-edit/_settings.mjs +3262 -424
  126. package/api/theme-edit/_tables.d.mts +15 -0
  127. package/api/theme-edit/_tables.mjs +63 -1
  128. package/api/theme-edit/_vet.d.mts +20 -0
  129. package/api/theme-edit/_vet.mjs +47 -2
  130. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  131. package/api/theme-edit/theme-edit.type.mjs +4 -1
  132. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  133. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  134. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  135. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  136. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  137. package/api/upgrade/run/run.mjs +4 -3
  138. package/assets/codemods/integration-discovery.mjs +2 -1
  139. package/assets/codemods/run-codemod.mjs +87 -7
  140. package/assets/codemods/transforms/next/index.mjs +11 -1
  141. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  142. package/assets/component-list.generated.json +1 -0
  143. package/assets/docs/author-a-theme.doc.mjs +1 -0
  144. package/assets/docs/theme.doc.dense.mjs +2 -2
  145. package/assets/docs/theme.doc.mjs +1 -1
  146. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  147. package/assets/docs/tree/checks.doc.mjs +1 -1
  148. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  149. package/assets/docs/tree/render-pages.doc.mjs +44 -3
  150. package/assets/docs/tree/single-component.doc.mjs +4 -0
  151. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  152. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  153. package/assets/docs/use-a-theme.doc.mjs +1 -1
  154. package/assets/docs.generated.json +2 -2
  155. package/assets/search-catalog.generated.json +2 -0
  156. package/assets/self-audit.generated.json +1 -1
  157. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  158. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  159. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  160. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  161. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  162. package/assets/templates/components.generated.json +1 -1
  163. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  164. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  165. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  166. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  167. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  168. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  169. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  170. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  171. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  172. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  173. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  174. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  175. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  176. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  177. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  178. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  179. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  180. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  181. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  182. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  183. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  184. package/assets/templates/pages/ide/page.tsx +24 -2
  185. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  186. package/assets/templates/pages/library/template.doc.mjs +4 -1
  187. package/assets/templates/pages/login/template.doc.mjs +2 -1
  188. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  189. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  190. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  191. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  192. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  193. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  194. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  195. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  196. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  197. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  198. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  199. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  200. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  201. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  202. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  203. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  204. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  205. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  206. package/assets/theme.template.ts +6 -0
  207. package/authoring/debug/parse.d.mts +3 -3
  208. package/authoring/doctypes/_schema.d.mts +3 -3
  209. package/authoring/doctypes/command/command.doc.mjs +1 -1
  210. package/authoring/doctypes/component/categories.d.mts +37 -0
  211. package/authoring/doctypes/component/categories.mjs +54 -0
  212. package/authoring/doctypes/template/template.doc.mjs +1 -1
  213. package/authoring/doctypes/template/type.ts +9 -0
  214. package/authoring/example/example.doc.d.mts +12 -0
  215. package/authoring/example/example.doc.mjs +69 -0
  216. package/authoring/example/preview.d.mts +92 -0
  217. package/authoring/example/preview.mjs +994 -0
  218. package/authoring/example/type.ts +102 -0
  219. package/authoring/index.d.mts +1 -0
  220. package/authoring/index.d.ts +12 -0
  221. package/authoring/index.mjs +3 -1
  222. package/clients/cli/bin/astryx.mjs +6 -9
  223. package/clients/cli/build-id.generated.json +1 -1
  224. package/clients/cli/commands/component.doc.mjs +1 -1
  225. package/clients/cli/commands/component.mjs +22 -3
  226. package/clients/cli/commands/docs.doc.mjs +7 -1
  227. package/clients/cli/commands/docs.mjs +3 -1
  228. package/clients/cli/commands/doctor.mjs +32 -14
  229. package/clients/cli/commands/experimental/render.mjs +42 -1
  230. package/clients/cli/commands/experimental/theme.mjs +358 -63
  231. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  232. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  233. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  234. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  235. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -1
  236. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  237. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  238. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  239. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  240. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  241. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  242. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  243. package/clients/cli/commands/search.doc.mjs +2 -1
  244. package/clients/cli/commands/search.mjs +6 -1
  245. package/clients/cli/commands/template.mjs +4 -2
  246. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  247. package/clients/cli/commands/theme.doc.mjs +1 -1
  248. package/clients/cli/commands/theme.mjs +317 -47
  249. package/clients/cli/commands/upgrade.mjs +42 -7
  250. package/clients/cli/index.mjs +1 -1
  251. package/clients/cli/lib/cli-error.mjs +2 -1
  252. package/clients/cli/lib/component-format.mjs +205 -98
  253. package/clients/cli/lib/hook-format.mjs +9 -19
  254. package/clients/cli/lib/json-shim.mjs +92 -21
  255. package/clients/cli/lib/manifest.mjs +3 -2
  256. package/clients/cli/manifest.generated.json +1 -1
  257. package/foundation/agent-docs/agent-docs.mjs +1 -1
  258. package/foundation/config/theme-state.d.mts +13 -1
  259. package/foundation/config/theme-state.mjs +47 -7
  260. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  261. package/foundation/discovery/component-discovery.d.mts +11 -0
  262. package/foundation/discovery/component-discovery.mjs +56 -8
  263. package/foundation/discovery/component-replacement.mjs +130 -1
  264. package/foundation/discovery/copied-passages.mjs +2 -1
  265. package/foundation/discovery/doc-types.mjs +4 -3
  266. package/foundation/discovery/entry-name-files.d.mts +43 -0
  267. package/foundation/discovery/entry-name-files.mjs +264 -0
  268. package/foundation/discovery/hook-discovery.d.mts +8 -2
  269. package/foundation/discovery/hook-discovery.mjs +22 -8
  270. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  271. package/foundation/discovery/icon-set-checks.mjs +2 -1
  272. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  273. package/foundation/discovery/integration-doc-files.mjs +2 -1
  274. package/foundation/discovery/package-exports.d.mts +10 -0
  275. package/foundation/discovery/package-exports.mjs +56 -3
  276. package/foundation/discovery/prop-drift.mjs +9 -9
  277. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  278. package/foundation/discovery/runner-allowlist.mjs +2 -0
  279. package/foundation/discovery/stored-component-list.d.mts +43 -0
  280. package/foundation/discovery/stored-component-list.mjs +90 -0
  281. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  282. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  283. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  284. package/foundation/discovery/stored-self-audit.mjs +38 -18
  285. package/foundation/discovery/template-adapter.d.mts +53 -1
  286. package/foundation/discovery/template-adapter.mjs +176 -12
  287. package/foundation/discovery/template-icons.mjs +2 -1
  288. package/foundation/discovery/theme-discovery.mjs +31 -4
  289. package/foundation/discovery/theme-imports.d.mts +14 -0
  290. package/foundation/discovery/theme-imports.mjs +43 -1
  291. package/foundation/discovery/theming-targets.mjs +3 -2
  292. package/foundation/doc-compiler/import.mjs +7 -1
  293. package/foundation/doc-compiler/inputs.mjs +3 -2
  294. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  295. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  296. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  297. package/foundation/env/semver.mjs +3 -1
  298. package/foundation/fonts/font-stylesheet.d.mts +31 -0
  299. package/foundation/fonts/font-stylesheet.mjs +115 -0
  300. package/foundation/fs/cache-eviction.d.mts +21 -0
  301. package/foundation/fs/cache-eviction.mjs +73 -0
  302. package/foundation/fs/exact-codec.d.mts +12 -2
  303. package/foundation/fs/exact-codec.mjs +23 -6
  304. package/foundation/fs/file-protection.mjs +4 -3
  305. package/foundation/fs/gather-cache.d.mts +62 -4
  306. package/foundation/fs/gather-cache.mjs +512 -91
  307. package/foundation/fs/jiti-cache.d.mts +19 -1
  308. package/foundation/fs/jiti-cache.mjs +130 -6
  309. package/foundation/fs/kept-tree.d.mts +60 -0
  310. package/foundation/fs/kept-tree.mjs +154 -0
  311. package/foundation/fs/listing-cache.d.mts +7 -0
  312. package/foundation/fs/listing-cache.mjs +10 -0
  313. package/foundation/fs/module-loader.d.mts +24 -2
  314. package/foundation/fs/module-loader.mjs +94 -21
  315. package/foundation/fs/paths.d.mts +18 -0
  316. package/foundation/fs/paths.mjs +15 -2
  317. package/foundation/fs/read-record.d.mts +9 -0
  318. package/foundation/fs/read-record.mjs +19 -11
  319. package/foundation/fs/stop-cleanup.d.mts +12 -0
  320. package/foundation/fs/stop-cleanup.mjs +66 -0
  321. package/foundation/identity/provider-identity.d.mts +6 -0
  322. package/foundation/identity/provider-identity.mjs +10 -1
  323. package/foundation/integrations/contribution-inventory.mjs +4 -3
  324. package/foundation/integrations/example-code.d.mts +63 -0
  325. package/foundation/integrations/example-code.mjs +416 -0
  326. package/foundation/integrations/public-imports.d.mts +9 -0
  327. package/foundation/integrations/public-imports.mjs +3 -2
  328. package/foundation/integrations/validate-contributions.mjs +17 -45
  329. package/foundation/render/embedded-files.d.mts +6 -0
  330. package/foundation/render/embedded-files.mjs +25 -5
  331. package/foundation/render/embedded-imports.d.mts +39 -7
  332. package/foundation/render/embedded-imports.mjs +66 -27
  333. package/foundation/render/file-header.d.mts +66 -0
  334. package/foundation/render/file-header.mjs +118 -0
  335. package/foundation/render/host-answer.d.mts +18 -0
  336. package/foundation/render/host-answer.mjs +46 -0
  337. package/foundation/render/host-exit.d.mts +1 -0
  338. package/foundation/render/host-exit.mjs +6 -1
  339. package/foundation/render/html-reader.d.mts +55 -2
  340. package/foundation/render/html-reader.mjs +145 -26
  341. package/foundation/render/markup-edits.d.mts +57 -0
  342. package/foundation/render/markup-edits.mjs +182 -0
  343. package/foundation/render/page-host.mjs +29 -12
  344. package/foundation/render/page-worker.mjs +121 -13
  345. package/foundation/render/picture-chrome.d.mts +4 -0
  346. package/foundation/render/picture-chrome.mjs +185 -0
  347. package/foundation/render/picture-playwright.d.mts +4 -0
  348. package/foundation/render/picture-playwright.mjs +34 -0
  349. package/foundation/render/rebuild.mjs +2 -1
  350. package/foundation/render/render-page.d.mts +35 -3
  351. package/foundation/render/render-page.mjs +641 -96
  352. package/foundation/render/source-block.d.mts +85 -6
  353. package/foundation/render/source-block.mjs +211 -20
  354. package/foundation/render/ts-paths.d.mts +69 -6
  355. package/foundation/render/ts-paths.mjs +326 -40
  356. package/foundation/response/error-codes.d.mts +3 -1
  357. package/foundation/response/error-codes.d.ts +1 -0
  358. package/foundation/response/error-codes.doc.mjs +12 -1
  359. package/foundation/response/error-codes.mjs +11 -1
  360. package/foundation/response/response-types.doc.mjs +2 -2
  361. package/foundation/text/compare-text.d.mts +14 -0
  362. package/foundation/text/compare-text.mjs +68 -0
  363. package/foundation/text/string-utils.d.mts +3 -2
  364. package/foundation/text/string-utils.mjs +18 -4
  365. package/foundation/text/suggest-order.d.mts +9 -0
  366. package/foundation/text/suggest-order.mjs +15 -1
  367. package/foundation/xle/expand.mjs +2 -1
  368. package/host/index.mjs +8 -6
  369. package/package.json +7 -6
@@ -17,22 +17,36 @@
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
- import {assetDataUri, isAssetBytes, isAssetPath, RenderAssetError} from './assets.mjs';
26
+ import {
27
+ assetDataUri,
28
+ isAssetBytes,
29
+ isAssetPath,
30
+ MAX_ASSET_BYTES,
31
+ RenderAssetError,
32
+ } from './assets.mjs';
25
33
  import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';
26
- import {sourceBlock} from './source-block.mjs';
34
+ import {asParsed, formatFor, sha256, sourceBlock} from './source-block.mjs';
27
35
  import {embeddedPathProblem} from './embedded-files.mjs';
28
- import {resolveServed} from './served-packages.mjs';
36
+ import {scanHtml} from './html-reader.mjs';
37
+ import {removeOnStop} from '../fs/stop-cleanup.mjs';
38
+ import {aliasOnly, assetRefsOf} from './embedded-imports.mjs';
39
+ import {isServedPackage, resolveServed} from './served-packages.mjs';
29
40
  import {CHART_CSS} from './charts.mjs';
30
41
  import {HOST_EXIT} from './host-exit.mjs';
42
+ import {endNote, headerNote} from './file-header.mjs';
43
+ import {textRuns} from './markup-edits.mjs';
44
+ import {findNodeModulesPackage, isInside} from '../fs/paths.mjs';
31
45
 
32
46
  /** How long one page may take to render before it is stopped. */
33
47
  export const RENDER_TIMEOUT_MS = 60_000;
34
48
 
35
- export {PAGE_EXTENSIONS} from './embedded-files.mjs';
49
+ export {MODULE_EXTENSIONS, PAGE_EXTENSIONS} from './embedded-files.mjs';
36
50
 
37
51
  /**
38
52
  * @typedef {object} RenderWarning
@@ -68,23 +82,88 @@ export class RenderError extends Error {
68
82
  }
69
83
 
70
84
  /**
71
- * The nearest folder at or above `dir` with a package.json, else `dir`.
85
+ * The nearest folder at or above `dir` with a package.json, or null outside
86
+ * a project.
72
87
  * @param {string} dir
88
+ * @returns {string | null}
73
89
  */
74
- function projectRootOf(dir) {
75
- let d = dir;
76
- for (;;) {
90
+ function projectOf(dir) {
91
+ for (let d = dir; ; d = path.dirname(d)) {
77
92
  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;
93
+ if (path.dirname(d) === d) return null;
81
94
  }
82
95
  }
83
96
 
97
+ /**
98
+ * Whether a path names a file. A name the system cannot look up (a segment
99
+ * too long, a folder it may not read) names none.
100
+ * @param {string} file
101
+ */
102
+ function isFileAt(file) {
103
+ try {
104
+ return fs.statSync(file).isFile();
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * The first bytes of a file, enough to tell its format.
112
+ * @param {string} file
113
+ */
114
+ function headOf(file) {
115
+ const fd = fs.openSync(file, 'r');
116
+ try {
117
+ const head = Buffer.alloc(4096);
118
+ return head.subarray(0, fs.readSync(fd, head, 0, head.length, 0));
119
+ } finally {
120
+ fs.closeSync(fd);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * The folder whose modules the page carries: its project's. Outside a
126
+ * project, the current folder when it holds the page, so a page with
127
+ * neighbours above its own folder (as a restore lays them out) carries them;
128
+ * else the page's folder.
129
+ * @param {string} dir
130
+ * @param {string} [cwd]
131
+ */
132
+ function carryScopeOf(dir, cwd) {
133
+ const project = projectOf(dir);
134
+ if (project) return project;
135
+ return cwd && (dir === cwd || isInside(dir, cwd)) ? cwd : dir;
136
+ }
137
+
84
138
  /** @param {string} s */
85
139
  const escapeHtml = s =>
86
140
  s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
87
141
 
142
+ /**
143
+ * The attributes a page's root Theme puts on `<html>` in a browser, for the
144
+ * static page: Core's root provider sets `data-astryx-theme` (and
145
+ * `data-theme` for a one-mode page) on the document element once it runs,
146
+ * so root-scoped tokens (the focus ring's color) resolve against the theme.
147
+ * A page runs no script, so they are written here: from the outermost
148
+ * element the theme marks, the root Theme's own.
149
+ * @param {string} markup
150
+ */
151
+ function rootThemeAttrs(markup) {
152
+ for (const t of scanHtml(markup)) {
153
+ if (t.kind !== 'start') continue;
154
+ const attrs = new Map(t.attrs);
155
+ if (!attrs.has('data-astryx-theme')) continue;
156
+ return ['data-astryx-theme', 'data-theme']
157
+ .filter(a => attrs.has(a))
158
+ .map(
159
+ a =>
160
+ ` ${a}="${escapeHtml(String(attrs.get(a))).replace(/"/g, '&quot;')}"`,
161
+ )
162
+ .join('');
163
+ }
164
+ return '';
165
+ }
166
+
88
167
  /** @param {string} s */
89
168
  const decodeAttr = s =>
90
169
  s
@@ -101,7 +180,10 @@ const decodeAttr = s =>
101
180
  * @returns {{url: string, layer: string | null, supports: string | null, media: string} | null}
102
181
  */
103
182
  function importParams(params) {
104
- const m = /^\s*(?:url\(\s*(['"]?)([\s\S]*?)\1\s*\)|(['"])([\s\S]*?)\3)\s*([\s\S]*)$/.exec(params);
183
+ const m =
184
+ /^\s*(?:url\(\s*(['"]?)([\s\S]*?)\1\s*\)|(['"])([\s\S]*?)\3)\s*([\s\S]*)$/.exec(
185
+ params,
186
+ );
105
187
  if (!m) return null;
106
188
  let rest = m[5];
107
189
  /** @type {string | null} */
@@ -113,7 +195,9 @@ function importParams(params) {
113
195
  }
114
196
  /** @type {string | null} */
115
197
  let supports = null;
116
- const sup = /^supports\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)\s*/i.exec(rest);
198
+ const sup = /^supports\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)\s*/i.exec(
199
+ rest,
200
+ );
117
201
  if (sup) {
118
202
  supports = sup[1];
119
203
  rest = rest.slice(sup[0].length);
@@ -194,7 +278,10 @@ function expandImports(file, css, ctx) {
194
278
  if (fromPackage) ctx.packageSheets.push(url.replace(/^~/, ''));
195
279
  else ctx.carried.add(target);
196
280
  const from = target;
197
- let inner = expandImports(from, fs.readFileSync(from, 'utf8'), {...ctx, seen});
281
+ let inner = expandImports(from, fs.readFileSync(from, 'utf8'), {
282
+ ...ctx,
283
+ seen,
284
+ });
198
285
  // Keep the imported sheet's relative url()s pointing at the same files.
199
286
  inner = inner.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (u, q, r) => {
200
287
  if (/^(data:|blob:|#|\/|[a-z]+:)/i.test(r)) return u;
@@ -205,13 +292,17 @@ function expandImports(file, css, ctx) {
205
292
  return `url(${q}${rebased.startsWith('.') ? rebased : `./${rebased}`}${q})`;
206
293
  });
207
294
  // The import's conditions still scope what it brings in.
208
- if (parsed.supports) inner = `@supports (${parsed.supports.replace(/^\((.*)\)$/s, '$1')}){${inner}}`;
295
+ if (parsed.supports)
296
+ inner = `@supports (${parsed.supports.replace(/^\((.*)\)$/s, '$1')}){${inner}}`;
209
297
  if (parsed.media) inner = `@media ${parsed.media}{${inner}}`;
210
- if (parsed.layer !== null) inner = `@layer${parsed.layer ? ` ${parsed.layer}` : ''}{${inner}}`;
298
+ if (parsed.layer !== null)
299
+ inner = `@layer${parsed.layer ? ` ${parsed.layer}` : ''}{${inner}}`;
211
300
  try {
212
301
  rule.replaceWith(postcss.parse(inner, {from}).nodes);
213
302
  } catch (e) {
214
- const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
303
+ const reason =
304
+ /** @type {any} */ (e)?.reason ??
305
+ (e instanceof Error ? e.message : String(e));
215
306
  throw new RenderError(
216
307
  'ERR_RENDER_COMPILE',
217
308
  `${path.basename(from)}, imported by ${path.basename(file)}, is not valid CSS: ${reason}`,
@@ -224,7 +315,14 @@ function expandImports(file, css, ctx) {
224
315
  /** @typedef {{dir: string, integrations: readonly string[]}} ServedSet */
225
316
 
226
317
  /** Signals that Node itself or a native module raises when it fails. */
227
- const CRASH_SIGNALS = new Set(['SIGSEGV', 'SIGBUS', 'SIGILL', 'SIGFPE', 'SIGABRT', 'SIGTRAP']);
318
+ const CRASH_SIGNALS = new Set([
319
+ 'SIGSEGV',
320
+ 'SIGBUS',
321
+ 'SIGILL',
322
+ 'SIGFPE',
323
+ 'SIGABRT',
324
+ 'SIGTRAP',
325
+ ]);
228
326
 
229
327
  /**
230
328
  * How a native crash ended a process, or null when it was not one. On
@@ -235,7 +333,8 @@ const CRASH_SIGNALS = new Set(['SIGSEGV', 'SIGBUS', 'SIGILL', 'SIGFPE', 'SIGABRT
235
333
  */
236
334
  function crashOf(code, signal) {
237
335
  if (signal) return CRASH_SIGNALS.has(signal) ? signal : null;
238
- if (code !== null && code >>> 0 >= 0xc0000000) return `0x${(code >>> 0).toString(16).toUpperCase()}`;
336
+ if (code !== null && code >>> 0 >= 0xc0000000)
337
+ return `0x${(code >>> 0).toString(16).toUpperCase()}`;
239
338
  return null;
240
339
  }
241
340
 
@@ -246,7 +345,10 @@ function crashOf(code, signal) {
246
345
  function segmenterCrashes() {
247
346
  const probe = spawnSync(
248
347
  process.execPath,
249
- ['-e', "[...new Intl.Segmenter('en', {granularity: 'grapheme'}).segment('a b')]"],
348
+ [
349
+ '-e',
350
+ "[...new Intl.Segmenter('en', {granularity: 'grapheme'}).segment('a b')]",
351
+ ],
250
352
  {stdio: 'ignore', timeout: 10_000},
251
353
  );
252
354
  return crashOf(probe.status, probe.signal) !== null;
@@ -261,12 +363,25 @@ function segmenterCrashes() {
261
363
  */
262
364
  function crashError(how, {crashed, withoutSegmenter}) {
263
365
  const node = `Node ${process.version} (${process.execPath})`;
264
- const detail = {signal: how, node: process.version, nodePath: process.execPath};
366
+ const detail = {
367
+ signal: how,
368
+ node: process.version,
369
+ nodePath: process.execPath,
370
+ };
265
371
  if (!crashed) {
266
- const memory = how === 'SIGKILL' ? ' The system stops a process this way when the machine runs out of memory.' : '';
267
- return new RenderError('ERR_RENDER_FAILED', `${node} was stopped by a signal (${how}) while it rendered the page.${memory}`, detail);
372
+ const memory =
373
+ how === 'SIGKILL'
374
+ ? ' The system stops a process this way when the machine runs out of memory.'
375
+ : '';
376
+ return new RenderError(
377
+ 'ERR_RENDER_FAILED',
378
+ `${node} was stopped by a signal (${how}) while it rendered the page.${memory}`,
379
+ detail,
380
+ );
268
381
  }
269
- const cause = withoutSegmenter ? ' It crashed again with Intl.Segmenter removed, so the fault is elsewhere in this Node or in a native module.' : '';
382
+ const cause = withoutSegmenter
383
+ ? ' It crashed again with Intl.Segmenter removed, so the fault is elsewhere in this Node or in a native module.'
384
+ : '';
270
385
  return new RenderError(
271
386
  'ERR_RENDER_FAILED',
272
387
  `${node} crashed (${how}) while it rendered the page. A fault in Node or in a native module causes this, not the page's code.${cause} Render with an official Node.js build of another version.`,
@@ -279,14 +394,36 @@ function crashError(how, {crashed, withoutSegmenter}) {
279
394
  * reported last, how long it ran, the memory left, and its last stderr line.
280
395
  * @param {any} message the host's {hostExit, reason, stage, elapsedMs, rssMb, freeMb, stderrTail}
281
396
  */
282
- function noAnswerError({hostExit, reason, stage, elapsedMs, rssMb, freeMb, stderrTail}) {
283
- const detail = {reason, exit: hostExit, stage, elapsedMs, rssMb, freeMb, ...(stderrTail ? {stderrTail} : {})};
397
+ function noAnswerError({
398
+ hostExit,
399
+ reason,
400
+ stage,
401
+ elapsedMs,
402
+ rssMb,
403
+ freeMb,
404
+ stderrTail,
405
+ }) {
406
+ const detail = {
407
+ reason,
408
+ exit: hostExit,
409
+ stage,
410
+ elapsedMs,
411
+ rssMb,
412
+ freeMb,
413
+ ...(stderrTail ? {stderrTail} : {}),
414
+ };
284
415
  const where = stage ? ` while ${stage}` : '';
285
416
  const seconds = Math.round((elapsedMs ?? 0) / 1000);
286
417
  if (reason === 'host-timeout') {
287
- return new RenderError('ERR_RENDER_TIMEOUT', `The page's process stopped at its own time limit${where}, after ${seconds} seconds, before this process read an answer.`, detail);
418
+ return new RenderError(
419
+ 'ERR_RENDER_TIMEOUT',
420
+ `The page's process stopped at its own time limit${where}, after ${seconds} seconds, before this process read an answer.`,
421
+ detail,
422
+ );
288
423
  }
289
- const last = stderrTail ? ` Its last output: ${String(stderrTail).split('\n').at(-1)}` : '';
424
+ const last = stderrTail
425
+ ? ` Its last output: ${String(stderrTail).split('\n').at(-1)}`
426
+ : '';
290
427
  return new RenderError(
291
428
  'ERR_RENDER_FAILED',
292
429
  `The page stopped rendering without an answer (exit ${hostExit})${where}, after ${seconds} seconds, with ${freeMb} MB of memory free.${last}`,
@@ -297,39 +434,173 @@ function noAnswerError({hostExit, reason, stage, elapsedMs, rssMb, freeMb, stder
297
434
  /** The error for a host process that ended, without a signal, before it answered. */
298
435
  function hostEndError(/** @type {number | null} */ code) {
299
436
  if (code === HOST_EXIT.disconnected) {
300
- return new RenderError('ERR_RENDER_FAILED', "The page's process lost its channel to this process and stopped without an answer.", {reason: 'disconnected', exit: code});
437
+ return new RenderError(
438
+ 'ERR_RENDER_FAILED',
439
+ "The page's process lost its channel to this process and stopped without an answer.",
440
+ {reason: 'disconnected', exit: code},
441
+ );
301
442
  }
302
443
  if (code === HOST_EXIT.noChannel) {
303
- return new RenderError('ERR_RENDER_FAILED', "The page's process had no channel left to send its answer on.", {reason: 'no-channel', exit: code});
444
+ return new RenderError(
445
+ 'ERR_RENDER_FAILED',
446
+ "The page's process had no channel left to send its answer on.",
447
+ {reason: 'no-channel', exit: code},
448
+ );
304
449
  }
305
450
  if (code === HOST_EXIT.timeout) {
306
- 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});
451
+ return new RenderError(
452
+ 'ERR_RENDER_TIMEOUT',
453
+ "The page's process stopped at its own time limit before this process read an answer.",
454
+ {reason: 'host-timeout', exit: code},
455
+ );
456
+ }
457
+ if (code === HOST_EXIT.sendFailed) {
458
+ return new RenderError(
459
+ 'ERR_RENDER_FAILED',
460
+ "The page's process could not send its answer to this process.",
461
+ {reason: 'send-failed', exit: code},
462
+ );
463
+ }
464
+ return new RenderError(
465
+ 'ERR_RENDER_FAILED',
466
+ `The page's process ended without an answer (exit ${code}).`,
467
+ {reason: 'host-ended', exit: code},
468
+ );
469
+ }
470
+
471
+ /**
472
+ * The error for a host that ended with no answer reaching this process, from
473
+ * the state it left in its per-run file: an answer it sent that never
474
+ * arrived, or the stage it ended in.
475
+ * @param {number | null} code
476
+ * @param {string | undefined} stateFile
477
+ */
478
+ function noMessageError(code, stateFile) {
479
+ if (code !== 0 && code !== null && Object.values(HOST_EXIT).includes(code))
480
+ return hostEndError(code);
481
+ /** @type {any} */
482
+ let saved = null;
483
+ try {
484
+ saved = stateFile ? JSON.parse(fs.readFileSync(stateFile, 'utf8')) : null;
485
+ } catch {
486
+ // No readable state: fall back to the bare message below.
487
+ }
488
+ if (!saved) return hostEndError(code);
489
+ const detail = {
490
+ exit: code,
491
+ stage: saved.stage,
492
+ elapsedMs: saved.elapsedMs,
493
+ rssMb: saved.rssMb,
494
+ freeMb: saved.freeMb,
495
+ ...(saved.stderrTail ? {stderrTail: saved.stderrTail} : {}),
496
+ };
497
+ if (saved.answered === 'sent') {
498
+ return new RenderError(
499
+ 'ERR_RENDER_FAILED',
500
+ `The page's process sent its answer, but this process did not receive it (exit ${code}).`,
501
+ {reason: 'answer-lost', ...detail},
502
+ );
503
+ }
504
+ if (saved.answered === 'sending') {
505
+ return new RenderError(
506
+ 'ERR_RENDER_FAILED',
507
+ `The page's process ended while it sent its answer (exit ${code}).`,
508
+ {reason: 'ended-while-sending', ...detail},
509
+ );
307
510
  }
308
- return new RenderError('ERR_RENDER_FAILED', `The page's process ended without an answer (exit ${code}).`, {reason: 'host-ended', exit: code});
511
+ const seconds = Math.round((saved.elapsedMs ?? 0) / 1000);
512
+ const last = saved.stderrTail
513
+ ? ` Its last output: ${String(saved.stderrTail).split('\n').at(-1)}`
514
+ : '';
515
+ return new RenderError(
516
+ 'ERR_RENDER_FAILED',
517
+ `The page's process ended without an answer (exit ${code}) while ${saved.stage}, after ${seconds} seconds, with ${saved.freeMb} MB of memory free.${last}`,
518
+ {reason: 'host-ended', ...detail},
519
+ );
309
520
  }
310
521
 
311
522
  /**
312
523
  * Run the page in a host process (page-host.mjs), stopping it after
313
524
  * `timeoutMs`. The host runs the page in a worker thread, and it exits when
314
525
  * this process goes away.
315
- * @param {{entry: string, root: string, served: ServedSet | null, withoutSegmenter: boolean}} input
526
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null, withoutSegmenter: boolean}} input
316
527
  * @param {number} timeoutMs
317
528
  * @returns {Promise<any>} the page's answer, or `{crashed: how}` when a
318
529
  * native crash ended the host
319
530
  */
320
531
  function runWorker(input, timeoutMs) {
321
- return new Promise((resolve, reject) => {
532
+ return withHostStateFile(stateFile => {
322
533
  const data = {
323
534
  ...input,
324
- served: input.served ? {dir: input.served.dir, integrations: [...input.served.integrations]} : null,
535
+ served: input.served
536
+ ? {dir: input.served.dir, integrations: [...input.served.integrations]}
537
+ : null,
325
538
  timeoutMs,
539
+ stateFile,
326
540
  };
327
- const host = fork(fileURLToPath(new URL('./page-host.mjs', import.meta.url)), [JSON.stringify(data)], {
328
- // Never the CLI's own flags (such as --input-type).
329
- execArgv: [],
330
- stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
331
- serialization: 'advanced',
541
+ const host = fork(
542
+ fileURLToPath(new URL('./page-host.mjs', import.meta.url)),
543
+ [JSON.stringify(data)],
544
+ {
545
+ // Never the CLI's own flags (such as --input-type).
546
+ execArgv: [],
547
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
548
+ serialization: 'advanced',
549
+ },
550
+ );
551
+ return awaitHost(host, {
552
+ timeoutMs,
553
+ withoutSegmenter: input.withoutSegmenter,
554
+ stateFile,
332
555
  });
556
+ });
557
+ }
558
+
559
+ /**
560
+ * Run `use` with a state file for one host in a new folder under the system's
561
+ * temporary folder, never in the project, and remove the folder after. The
562
+ * state file only explains a failure: without a temporary folder, `use` gets
563
+ * none and the render runs without it.
564
+ * @template T
565
+ * @param {(stateFile: string | undefined) => Promise<T>} use
566
+ * @param {{makeTempDir?: (prefix: string) => string}} [options]
567
+ * @returns {Promise<T>}
568
+ */
569
+ export async function withHostStateFile(
570
+ use,
571
+ {makeTempDir = prefix => fs.mkdtempSync(prefix)} = {},
572
+ ) {
573
+ /** @type {string} */
574
+ let dir;
575
+ try {
576
+ dir = makeTempDir(path.join(os.tmpdir(), 'astryx-render-'));
577
+ } catch {
578
+ // No temporary folder (missing or read-only): render without the state file.
579
+ return use(undefined);
580
+ }
581
+ // A stop while the page renders removes the folder too.
582
+ const untrack = removeOnStop(dir);
583
+ try {
584
+ return await use(path.join(dir, 'host-state.json'));
585
+ } finally {
586
+ untrack();
587
+ try {
588
+ fs.rmSync(dir, {recursive: true, force: true, maxRetries: 3});
589
+ } catch {
590
+ // Best effort: a removal that fails (a file still held open) never
591
+ // replaces the render's own result.
592
+ }
593
+ }
594
+ }
595
+
596
+ /**
597
+ * The page's answer from its host process, or the reason it has none.
598
+ * @param {import('node:child_process').ChildProcess} host
599
+ * @param {{timeoutMs: number, withoutSegmenter: boolean, stateFile?: string}} options
600
+ * @returns {Promise<any>}
601
+ */
602
+ export function awaitHost(host, {timeoutMs, withoutSegmenter, stateFile}) {
603
+ return new Promise((resolve, reject) => {
333
604
  let settled = false;
334
605
  /** @param {() => void} settle */
335
606
  const finish = settle => {
@@ -356,8 +627,14 @@ function runWorker(input, timeoutMs) {
356
627
  const text = String(message.hostError);
357
628
  reject(
358
629
  /ERR_WORKER_OUT_OF_MEMORY|heap out of memory/.test(text)
359
- ? new RenderError('ERR_RENDER_FAILED', 'The page ran out of memory while rendering.')
360
- : new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${text.split('\n')[0]}`),
630
+ ? new RenderError(
631
+ 'ERR_RENDER_FAILED',
632
+ 'The page ran out of memory while rendering.',
633
+ )
634
+ : new RenderError(
635
+ 'ERR_RENDER_FAILED',
636
+ `The page could not be rendered: ${text.split('\n')[0]}`,
637
+ ),
361
638
  );
362
639
  } else if (message?.hostExit !== undefined) {
363
640
  reject(noAnswerError(message));
@@ -367,14 +644,24 @@ function runWorker(input, timeoutMs) {
367
644
  });
368
645
  });
369
646
  host.once('error', error => {
370
- finish(() => reject(new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`)));
647
+ finish(() =>
648
+ reject(
649
+ new RenderError(
650
+ 'ERR_RENDER_FAILED',
651
+ `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`,
652
+ ),
653
+ ),
654
+ );
371
655
  });
372
- host.once('exit', (code, signal) => {
656
+ // 'close' comes after the IPC channel drains, so an answer the host sent
657
+ // just before it exited still wins; 'exit' can come first under load.
658
+ host.once('close', (code, signal) => {
373
659
  finish(() => {
374
660
  const crash = crashOf(code, signal);
375
661
  if (crash) resolve({crashed: crash});
376
- else if (signal) reject(crashError(signal, {crashed: false, withoutSegmenter: input.withoutSegmenter}));
377
- else reject(hostEndError(code));
662
+ else if (signal)
663
+ reject(crashError(signal, {crashed: false, withoutSegmenter}));
664
+ else reject(noMessageError(code, stateFile));
378
665
  });
379
666
  });
380
667
  });
@@ -383,7 +670,7 @@ function runWorker(input, timeoutMs) {
383
670
  /**
384
671
  * Run the page. When this Node crashes in Intl.Segmenter, run it once more
385
672
  * without Intl.Segmenter and say so in a warning.
386
- * @param {{entry: string, root: string, served: ServedSet | null}} input
673
+ * @param {{entry: string, root: string, scope: string, served: ServedSet | null}} input
387
674
  * @param {number} timeoutMs
388
675
  * @param {RenderWarning[]} warnings
389
676
  */
@@ -391,9 +678,14 @@ async function runPage(input, timeoutMs, warnings) {
391
678
  const started = Date.now();
392
679
  const first = await runWorker({...input, withoutSegmenter: false}, timeoutMs);
393
680
  if (!first.crashed) return first;
394
- if (!segmenterCrashes()) throw crashError(first.crashed, {crashed: true, withoutSegmenter: false});
395
- const again = await runWorker({...input, withoutSegmenter: true}, Math.max(1000, timeoutMs - (Date.now() - started)));
396
- if (again.crashed) throw crashError(again.crashed, {crashed: true, withoutSegmenter: true});
681
+ if (!segmenterCrashes())
682
+ throw crashError(first.crashed, {crashed: true, withoutSegmenter: false});
683
+ const again = await runWorker(
684
+ {...input, withoutSegmenter: true},
685
+ Math.max(1000, timeoutMs - (Date.now() - started)),
686
+ );
687
+ if (again.crashed)
688
+ throw crashError(again.crashed, {crashed: true, withoutSegmenter: true});
397
689
  warnings.push(segmenterWarning());
398
690
  return again;
399
691
  }
@@ -421,7 +713,8 @@ function inlineAssets(text, kind, ctx) {
421
713
  const resolveRef = ref => {
422
714
  const clean = decodeAttr(ref).trim().split(/[?#]/)[0];
423
715
  if (!clean) return null;
424
- if (/^(data:|blob:|#|about:|mailto:|tel:|javascript:)/i.test(clean)) return null;
716
+ if (/^(data:|blob:|#|about:|mailto:|tel:|javascript:)/i.test(clean))
717
+ return null;
425
718
  if (/^(https?:)?\/\//i.test(clean)) {
426
719
  const key = `remote:${clean}`;
427
720
  if (!ctx.counted.has(key)) {
@@ -484,6 +777,31 @@ function inlineAssets(text, kind, ctx) {
484
777
  });
485
778
  }
486
779
 
780
+ /**
781
+ * The version of a package the page rendered with: the package set's copy
782
+ * when the page took it from there, else the copy Node's resolver finds from
783
+ * the page's folder.
784
+ * @param {string} name
785
+ * @param {string} dir the page's folder
786
+ * @param {Map<string, string>} setDirs the packages the page took from the package set: their folders
787
+ * @returns {string | null}
788
+ */
789
+ function installedVersion(name, dir, setDirs) {
790
+ const packageDir =
791
+ setDirs.get(name) ?? findNodeModulesPackage(dir, name)?.packageDir;
792
+ if (!packageDir) return null;
793
+ try {
794
+ const pkg = JSON.parse(
795
+ fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'),
796
+ );
797
+ return pkg?.name === name && typeof pkg.version === 'string'
798
+ ? pkg.version
799
+ : null;
800
+ } catch {
801
+ return null;
802
+ }
803
+ }
804
+
487
805
  /** The light and dark switch every rendered page carries. */
488
806
  const SCHEME_CSS =
489
807
  ':root{color-scheme:light dark}:root[data-theme="light"]{color-scheme:light}:root[data-theme="dark"]{color-scheme:dark}';
@@ -491,20 +809,37 @@ const SCHEME_CSS =
491
809
  /**
492
810
  * Render a page module to one self-contained HTML file.
493
811
  * @param {string} entry absolute path of the page module
494
- * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null}} [options]
812
+ * @param {{title?: string, timeoutMs?: number, version?: string, served?: ServedSet | null, output?: string, cwd?: string}} [options]
495
813
  * `served`: the Core of the package set the CLI runs from, for the packages
496
- * the page's folder has no copy of
814
+ * the page's folder has no copy of; `output`: the file the HTML goes to;
815
+ * `cwd`: the current folder, whose files are the page's own outside a
816
+ * project.
817
+ * With `output`, the file describes itself: notes at its top and end name
818
+ * what made it and the commands that give the page back and render it
819
+ * again, and its embedded source records the CLI version, the packages
820
+ * the page rendered with, and the markup as rendered.
497
821
  * @returns {Promise<RenderedPage>}
498
822
  */
499
823
  export async function renderPage(entry, options = {}) {
500
824
  const dir = path.dirname(entry);
501
- const root = projectRootOf(dir);
825
+ // The project's folder, else the page's: where its tsconfig.json and
826
+ // public/ images are read.
827
+ const root = projectOf(dir) ?? dir;
828
+ const scope = carryScopeOf(dir, options.cwd);
502
829
  const served = options.served ?? null;
503
830
  /** @type {RenderWarning[]} */
504
831
  const warnings = [];
505
- const message = await runPage({entry, root, served}, options.timeoutMs ?? RENDER_TIMEOUT_MS, warnings);
832
+ const message = await runPage(
833
+ {entry, root, scope, served},
834
+ options.timeoutMs ?? RENDER_TIMEOUT_MS,
835
+ warnings,
836
+ );
506
837
  if (!message.ok) {
507
- throw new RenderError(message.error.code, message.error.message, message.error.detail);
838
+ throw new RenderError(
839
+ message.error.code,
840
+ message.error.message,
841
+ message.error.detail,
842
+ );
508
843
  }
509
844
  /** @type {string} */
510
845
  let markup = message.markup;
@@ -533,7 +868,9 @@ export async function renderPage(entry, options = {}) {
533
868
  const hasCore = addSheet('@astryxdesign/core/reset.css');
534
869
  if (hasCore) addSheet('@astryxdesign/core/astryx.css');
535
870
  // Package stylesheets the page imports itself, such as a theme's.
536
- for (const {spec, from} of /** @type {{spec: string, from: string}[]} */ (message.packageCss ?? [])) {
871
+ for (const {spec, from} of /** @type {{spec: string, from: string}[]} */ (
872
+ message.packageCss ?? []
873
+ )) {
537
874
  if (sheets.includes(spec)) continue;
538
875
  const file = resolveServed(spec, from, served);
539
876
  try {
@@ -563,7 +900,13 @@ export async function renderPage(entry, options = {}) {
563
900
  });
564
901
  }
565
902
 
566
- const ctx = {dir, root, warnings, counted: new Set(), localAssets: /** @type {Set<string>} */ (new Set())};
903
+ const ctx = {
904
+ dir,
905
+ root,
906
+ warnings,
907
+ counted: new Set(),
908
+ localAssets: /** @type {Set<string>} */ (new Set()),
909
+ };
567
910
  /** Stylesheets pulled in by another's `@import`. @type {Set<string>} */
568
911
  const carriedCss = new Set();
569
912
  try {
@@ -580,7 +923,9 @@ export async function renderPage(entry, options = {}) {
580
923
  'The page renders a <script> element. A sandboxed viewer blocks it, and anywhere else it runs when the file is opened; remove it from the page.',
581
924
  });
582
925
  }
583
- for (const m of markup.matchAll(/<(link|iframe|object|embed)\b[^>]*?\s(?:href|src|data)="([^"]*)"/gi)) {
926
+ for (const m of markup.matchAll(
927
+ /<(link|iframe|object|embed)\b[^>]*?\s(?:href|src|data)="([^"]*)"/gi,
928
+ )) {
584
929
  if (/^(data:|#)/i.test(m[2])) continue;
585
930
  warnings.push({
586
931
  code: 'remote-asset',
@@ -589,7 +934,8 @@ export async function renderPage(entry, options = {}) {
589
934
  }
590
935
  } catch (e) {
591
936
  const err = /** @type {any} */ (e);
592
- if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
937
+ if (err instanceof RenderAssetError)
938
+ throw new RenderError(err.code, err.message, err.detail);
593
939
  throw e;
594
940
  }
595
941
  const used = classesIn(markup);
@@ -604,11 +950,22 @@ export async function renderPage(entry, options = {}) {
604
950
  /** A stylesheet's rules cut to the page, with its own imports inlined. @param {string} file @param {string} text */
605
951
  const sheet = (file, text) => {
606
952
  try {
607
- const own = expandImports(file, text, {warnings, carried: carriedCss, included, packageSheets, served});
608
- return inlineAssets(cutCss(own, used), 'css', {...ctx, dir: path.dirname(file)});
953
+ const own = expandImports(file, text, {
954
+ warnings,
955
+ carried: carriedCss,
956
+ included,
957
+ packageSheets,
958
+ served,
959
+ });
960
+ return inlineAssets(cutCss(own, used), 'css', {
961
+ ...ctx,
962
+ dir: path.dirname(file),
963
+ });
609
964
  } catch (e) {
610
965
  if (e instanceof RenderAssetError || e instanceof RenderError) throw e;
611
- const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
966
+ const reason =
967
+ /** @type {any} */ (e)?.reason ??
968
+ (e instanceof Error ? e.message : String(e));
612
969
  throw new RenderError(
613
970
  'ERR_RENDER_COMPILE',
614
971
  `${path.relative(dir, file).split(path.sep).join('/')} is not valid CSS: ${reason}`,
@@ -618,14 +975,21 @@ export async function renderPage(entry, options = {}) {
618
975
  sheetText.forEach((text, i) => {
619
976
  css += sheet(sheetFiles[i], text);
620
977
  });
621
- for (const {file, css: text} of /** @type {{file: string, css: string}[]} */ (message.importedCss ?? [])) {
978
+ for (const {
979
+ file,
980
+ css: text,
981
+ } of /** @type {{file: string, css: string}[]} */ (
982
+ message.importedCss ?? []
983
+ )) {
622
984
  css += sheet(file, text);
623
985
  }
624
- for (const spec of packageSheets) if (!sheets.includes(spec)) sheets.push(spec);
986
+ for (const spec of packageSheets)
987
+ if (!sheets.includes(spec)) sheets.push(spec);
625
988
  if (message.css) css += inlineAssets(message.css, 'css', ctx);
626
989
  } catch (e) {
627
990
  const err = /** @type {any} */ (e);
628
- if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
991
+ if (err instanceof RenderAssetError)
992
+ throw new RenderError(err.code, err.message, err.detail);
629
993
  throw e;
630
994
  }
631
995
  // Keep inlined CSS from ending its own <style> element.
@@ -645,7 +1009,9 @@ export async function renderPage(entry, options = {}) {
645
1009
  for (const t of /** @type {any[]} */ (message.texts ?? [])) {
646
1010
  if (t.hidden || t.text.length < 2 || plainText.includes(t.text)) continue;
647
1011
  // The code around it ran: other text from the same function rendered.
648
- const around = /** @type {string[]} */ (message.fnTexts?.[t.fn] ?? []).filter(o => o !== t.text);
1012
+ const around = /** @type {string[]} */ (
1013
+ message.fnTexts?.[t.fn] ?? []
1014
+ ).filter(o => o !== t.text);
649
1015
  if (!around.some(o => plainText.includes(o))) continue;
650
1016
  warnings.push({
651
1017
  code: 'dropped-children',
@@ -655,8 +1021,13 @@ export async function renderPage(entry, options = {}) {
655
1021
  // A chart the render did not draw is an empty box: a ResponsiveContainer
656
1022
  // holds only its sizing box, and a chart of fixed size an empty wrapper.
657
1023
  const blankCharts =
658
- (markup.match(/<div class="recharts-responsive-container[" ][^>]*><div[^>]*><\/div><\/div>/g) ?? []).length +
659
- (markup.match(/<div\b[^>]*\bclass="recharts-wrapper"[^>]*><\/div>/g) ?? []).length +
1024
+ (
1025
+ markup.match(
1026
+ /<div class="recharts-responsive-container[" ][^>]*><div[^>]*><\/div><\/div>/g,
1027
+ ) ?? []
1028
+ ).length +
1029
+ (markup.match(/<div\b[^>]*\bclass="recharts-wrapper"[^>]*><\/div>/g) ?? [])
1030
+ .length +
660
1031
  (message.chartsFailed ?? 0);
661
1032
  if (blankCharts > 0) {
662
1033
  warnings.push({
@@ -667,8 +1038,10 @@ export async function renderPage(entry, options = {}) {
667
1038
  if (message.chartsAlone) {
668
1039
  /** @type {Record<string, string>} */
669
1040
  const causes = {
670
- changed: 'The page changed its charts once its effects ran (their data or props, or which charts it shows)',
671
- rerendered: 'A component that makes a chart rendered again once the page\'s effects ran',
1041
+ changed:
1042
+ 'The page changed its charts once its effects ran (their data or props, or which charts it shows)',
1043
+ rerendered:
1044
+ "A component that makes a chart rendered again once the page's effects ran",
672
1045
  error: 'The page could not be drawn again without a browser',
673
1046
  };
674
1047
  const why = causes[message.chartsAlone] ?? causes.error;
@@ -683,7 +1056,9 @@ export async function renderPage(entry, options = {}) {
683
1056
  message: `The page imports ${sheet}, a Sass or Less stylesheet, which a render does not compile, so its styles are missing.`,
684
1057
  });
685
1058
  }
686
- for (const log of /** @type {{level: string, text: string}[]} */ (message.logs ?? []).slice(0, 5)) {
1059
+ for (const log of /** @type {{level: string, text: string}[]} */ (
1060
+ message.logs ?? []
1061
+ ).slice(0, 5)) {
687
1062
  warnings.push({
688
1063
  code: 'page-output',
689
1064
  message: `The page printed while rendering (${log.level}): ${log.text.split('\n')[0].slice(0, 200)}`,
@@ -696,30 +1071,113 @@ export async function renderPage(entry, options = {}) {
696
1071
  // (`<img src="./logo.png">`, `url(./bg.png)`) are carried too, so the page
697
1072
  // comes back with them; a package's own files are not.
698
1073
  for (const sheet of carriedCss) {
699
- const rel = path.relative(root, sheet);
700
- if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
1074
+ if (
1075
+ !isInside(sheet, scope) ||
1076
+ path.relative(scope, sheet).split(path.sep).includes('node_modules')
1077
+ )
1078
+ continue;
701
1079
  if (!files.includes(sheet)) files.push(sheet);
702
1080
  }
703
- for (const asset of ctx.localAssets) {
704
- const rel = path.relative(root, asset);
705
- if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
706
- if (files.includes(asset)) continue;
707
- // Carried only when its bytes are a known image, font or media format,
708
- // the same test --reverse applies, so the file always comes back.
709
- if (!isAssetBytes(fs.readFileSync(asset))) {
1081
+ /** Assets named in a warning already, so each is named once. @type {Set<string>} */
1082
+ const notCarried = new Set();
1083
+ /**
1084
+ * Carry an image, font or media file of the project's own. It is carried
1085
+ * only when its bytes are a known image, font or media format, the same
1086
+ * test --reverse applies, so the file always comes back.
1087
+ * @param {string} asset absolute
1088
+ * @param {string} how how the page uses it, for the warning
1089
+ */
1090
+ const carryAsset = (asset, how) => {
1091
+ if (
1092
+ !isInside(asset, scope) ||
1093
+ path.relative(scope, asset).split(path.sep).includes('node_modules')
1094
+ )
1095
+ return;
1096
+ if (files.includes(asset) || notCarried.has(asset)) return;
1097
+ /** @param {string} why */
1098
+ const leaveOut = why => {
1099
+ notCarried.add(asset);
710
1100
  warnings.push({
711
1101
  code: 'not-embedded',
712
- message: `${path.relative(dir, asset).split(path.sep).join('/')} is shown inline but not carried in the file: its bytes are not a known image, font or media format, so --reverse cannot give it back.`,
1102
+ message: `${path.relative(dir, asset).split(path.sep).join('/')} is ${how} but not carried in the file: ${why}, so --reverse cannot give it back.`,
713
1103
  });
714
- continue;
1104
+ };
1105
+ /** @type {Buffer} */
1106
+ let head;
1107
+ try {
1108
+ // The same limit as a file the page shows, which a render inlines.
1109
+ if (fs.statSync(asset).size > MAX_ASSET_BYTES) {
1110
+ leaveOut(
1111
+ `it is larger than ${MAX_ASSET_BYTES / 1048576} MB, the most a rendered page carries of one file`,
1112
+ );
1113
+ return;
1114
+ }
1115
+ head = headOf(asset);
1116
+ } catch (e) {
1117
+ leaveOut(
1118
+ `it cannot be read (${/** @type {NodeJS.ErrnoException} */ (e).code ?? 'an error from the file system'})`,
1119
+ );
1120
+ return;
1121
+ }
1122
+ if (!isAssetBytes(head)) {
1123
+ leaveOut('its bytes are not a known image, font or media format');
1124
+ return;
715
1125
  }
716
1126
  files.push(asset);
1127
+ };
1128
+ for (const asset of ctx.localAssets) carryAsset(asset, 'shown inline');
1129
+ // A carried module or stylesheet can name an image, font or media file by
1130
+ // a relative path. --reverse expects each such file back, also when this
1131
+ // render does not show it, when it lies inside the folder that holds the
1132
+ // carried files (a name that climbs out of it is not the page's file).
1133
+ let named = dir;
1134
+ for (const f of files) {
1135
+ while (!isInside(f, named)) named = path.dirname(named);
1136
+ }
1137
+ const carriedText = files.filter(
1138
+ f =>
1139
+ /\.(?:[cm]?[jt]sx?|css)$/i.test(f) &&
1140
+ (f === entry ||
1141
+ !embeddedPathProblem(
1142
+ path.relative(named, f).split(path.sep).join('/'),
1143
+ )),
1144
+ );
1145
+ for (const file of carriedText) {
1146
+ let text;
1147
+ try {
1148
+ text = fs.readFileSync(file, 'utf8');
1149
+ } catch {
1150
+ continue;
1151
+ }
1152
+ for (const ref of assetRefsOf(text, file)) {
1153
+ const asset = path.resolve(path.dirname(file), ref);
1154
+ if (!isInside(asset, named)) continue;
1155
+ if (isFileAt(asset)) {
1156
+ carryAsset(
1157
+ asset,
1158
+ `named in ${path.relative(dir, file).split(path.sep).join('/')}`,
1159
+ );
1160
+ }
1161
+ }
717
1162
  }
718
1163
  // Paths are kept relative to the folder that holds every file: the page's
719
- // folder, or an ancestor when the page imports from above it.
1164
+ // folder, or an ancestor when the page imports from above it, but never one
1165
+ // from which the page's own path holds a name a reverse refuses (a
1166
+ // dot-folder): a file above that stays out of the file, and is named.
720
1167
  let base = dir;
721
1168
  for (const f of files) {
722
- while (path.relative(base, f).startsWith('..')) base = path.dirname(base);
1169
+ while (!isInside(f, base)) {
1170
+ const up = path.dirname(base);
1171
+ if (
1172
+ up === base ||
1173
+ embeddedPathProblem(
1174
+ path.relative(up, entry).split(path.sep).join('/'),
1175
+ {page: true},
1176
+ )
1177
+ )
1178
+ break;
1179
+ base = up;
1180
+ }
723
1181
  }
724
1182
  // Page first, so the reader knows which file is the page. Only files a
725
1183
  // rendered page may carry are embedded (see embedded-files.mjs).
@@ -737,16 +1195,101 @@ export async function renderPage(entry, options = {}) {
737
1195
  }
738
1196
  embedded.push({path: rel, bytes: fs.readFileSync(f)});
739
1197
  }
740
- const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(markup)?.[1]?.replace(/<[^>]*>/g, '').trim();
741
- 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`;
1198
+ const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i
1199
+ .exec(markup)?.[1]
1200
+ ?.replace(/<[^>]*>/g, '')
1201
+ .trim();
1202
+ const title =
1203
+ options.title ??
1204
+ (heading
1205
+ ? decodeAttr(heading)
1206
+ : path.basename(entry).replace(/\.[^.]+$/, ''));
1207
+ const generator = `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">`;
1208
+ const style = `<style>${SCHEME_CSS}${markup.includes('class="recharts-responsive-container"') ? CHART_CSS : ''}${css}</style>`;
1209
+ let html;
1210
+ if (options.output) {
1211
+ // The charset and generator metas come first: a browser reads the
1212
+ // charset only from the first 1024 bytes, and a CLI decides whether a
1213
+ // render wrote a file from its first 4096.
1214
+ const setDirs = new Map(
1215
+ /** @type {{name: string, dir: string}[]} */ (message.fromSet ?? []).map(
1216
+ p => [p.name, p.dir],
1217
+ ),
1218
+ );
1219
+ const names = new Set([
1220
+ ...(message.packages ?? []),
1221
+ ...setDirs.keys(),
1222
+ 'react',
1223
+ 'react-dom',
1224
+ ]);
1225
+ if (hasCore) names.add('@astryxdesign/core');
1226
+ /** @type {Record<string, string>} */
1227
+ const packages = {};
1228
+ for (const name of [...names].sort()) {
1229
+ if (name.startsWith('node:') || builtinModules.includes(name)) continue;
1230
+ const version = installedVersion(name, dir, setDirs);
1231
+ if (version) packages[name] = version;
1232
+ }
1233
+ const file = path.basename(options.output);
1234
+ const facts = {
1235
+ cli: options.version ?? null,
1236
+ format: formatFor(embedded),
1237
+ file,
1238
+ page: projectOf(dir)
1239
+ ? path.relative(root, entry).split(path.sep).join('/')
1240
+ : embedded[0].path,
1241
+ restored: `${file.replace(/\.[^.]+$/, '')}-restored/${embedded[0].path}`,
1242
+ files: embedded.map(f => f.path),
1243
+ packages,
1244
+ install: Object.entries(packages)
1245
+ .filter(([name]) => !isServedPackage(name, []))
1246
+ .map(([name, version]) => `${name}@${version}`),
1247
+ ...(options.title === undefined ? {} : {title: options.title}),
1248
+ };
1249
+ // The file each alias import named, for the files the page carries, so a
1250
+ // reverse where no alias names it still finds the file.
1251
+ const carried = new Map(
1252
+ embedded.map(f => [path.resolve(base, f.path), f.path]),
1253
+ );
1254
+ /** @type {Record<string, string>} */
1255
+ const aliases = {};
1256
+ for (const {
1257
+ spec,
1258
+ file: named,
1259
+ } of /** @type {{spec: string, file: string}[]} */ (
1260
+ message.aliasImports ?? []
1261
+ ).sort((a, b) => (a.spec < b.spec ? -1 : a.spec > b.spec ? 1 : 0))) {
1262
+ const rel = carried.get(path.resolve(named));
1263
+ if (rel && aliasOnly(spec)) aliases[spec] = rel;
1264
+ }
1265
+ const record = {
1266
+ ...(facts.cli ? {cli: facts.cli} : {}),
1267
+ page: facts.page,
1268
+ ...(options.title === undefined ? {} : {title: options.title}),
1269
+ packages,
1270
+ ...(Object.keys(aliases).length > 0 ? {aliases} : {}),
1271
+ markup: {
1272
+ sha256: sha256(asParsed(markup)),
1273
+ style: sha256(asParsed(style)),
1274
+ text: Buffer.from(
1275
+ JSON.stringify({title, runs: textRuns(markup)}),
1276
+ ).toString('base64'),
1277
+ },
1278
+ };
1279
+ html =
1280
+ `<!doctype html><html lang="en"${rootThemeAttrs(markup)}><head><meta charset="utf-8">${generator}\n${headerNote(facts)}\n` +
1281
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
1282
+ '<meta name="color-scheme" content="light dark">' +
1283
+ `<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
1284
+ `${sourceBlock(path.basename(entry), embedded, record)}\n${endNote(facts)}\n</body></html>\n`;
1285
+ } else {
1286
+ html =
1287
+ `<!doctype html><html lang="en"${rootThemeAttrs(markup)}><head><meta charset="utf-8">` +
1288
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
1289
+ '<meta name="color-scheme" content="light dark">' +
1290
+ `${generator}<title>${escapeHtml(title)}</title>${style}</head><body>${markup}` +
1291
+ `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
1292
+ }
750
1293
  return {
751
1294
  html,
752
1295
  files: embedded.map(f => f.path),
@@ -755,7 +1298,9 @@ export async function renderPage(entry, options = {}) {
755
1298
  cssBytes: Buffer.byteLength(css),
756
1299
  markupBytes: Buffer.byteLength(markup),
757
1300
  images: new Set([
758
- ...[...ctx.counted].filter(k => k.startsWith('file:')).map(k => k.slice(5)),
1301
+ ...[...ctx.counted]
1302
+ .filter(k => k.startsWith('file:'))
1303
+ .map(k => k.slice(5)),
759
1304
  ...(message.assets ?? []),
760
1305
  ]).size,
761
1306
  warnings,