@astryxdesign/cli 0.7.4 → 0.7.5-canary.04434e7

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 (259) hide show
  1. package/README.md +19 -19
  2. package/api/component/_adapter.mjs +16 -1
  3. package/api/component/component.test.mjs +31 -0
  4. package/api/discover/_adapter.d.mts +1 -1
  5. package/api/docs/_adapter.d.mts +5 -2
  6. package/api/docs/_adapter.mjs +24 -16
  7. package/api/docs/docs.test.mjs +18 -0
  8. package/api/docs/integrationDocs.test.mjs +2 -2
  9. package/api/experimental.d.mts +5 -0
  10. package/api/experimental.mjs +15 -0
  11. package/api/hook/list/list.d.mts +1 -1
  12. package/api/icon/_adapter.d.mts +3 -2
  13. package/api/icon/_adapter.mjs +16 -3
  14. package/api/icon/_authoring.d.mts +5 -1
  15. package/api/icon/_authoring.mjs +478 -63
  16. package/api/icon/_options.d.mts +11 -0
  17. package/api/icon/_options.mjs +39 -4
  18. package/api/icon/_records.d.mts +19 -0
  19. package/api/icon/_records.mjs +25 -0
  20. package/api/icon/add/add.d.mts +3 -3
  21. package/api/icon/add/add.mjs +227 -14
  22. package/api/icon/all-or-nothing.test.mjs +283 -0
  23. package/api/icon/detail/detail.mjs +2 -13
  24. package/api/icon/error-codes.test.mjs +14 -7
  25. package/api/icon/icon.d.mts +2 -2
  26. package/api/icon/icon.doc.mjs +30 -2
  27. package/api/icon/icon.mjs +57 -8
  28. package/api/icon/icon.test.mjs +133 -1
  29. package/api/icon/icon.type.d.mts +126 -1
  30. package/api/icon/icon.type.mjs +67 -3
  31. package/api/icon/iconAdd.doc.mjs +22 -6
  32. package/api/icon/iconMap.doc.mjs +24 -8
  33. package/api/icon/iconNewDefinition.doc.mjs +2 -2
  34. package/api/icon/iconNewSet.doc.mjs +30 -2
  35. package/api/icon/iconUse.doc.mjs +4 -1
  36. package/api/icon/map/map.d.mts +4 -4
  37. package/api/icon/map/map.mjs +134 -9
  38. package/api/icon/new-definition/new-definition.mjs +6 -2
  39. package/api/icon/new-set/new-set.mjs +2 -2
  40. package/api/icon/new-set/new-set.test.mjs +60 -10
  41. package/api/icon/option-pairs.test.mjs +368 -0
  42. package/api/icon/search/search.d.mts +10 -0
  43. package/api/icon/search/search.mjs +55 -14
  44. package/api/icon/use/use.mjs +2 -13
  45. package/api/integration/add-helpers.d.mts +15 -1
  46. package/api/integration/add-helpers.mjs +1 -1
  47. package/api/integration/pack-check.lifecycle-output.test.mjs +24 -1
  48. package/api/integration/pack-check.mjs +10 -4
  49. package/api/integration/pack-check.test.mjs +5 -1
  50. package/api/integration/validate-integration.type.d.mts +3 -2
  51. package/api/integration/validate-integration.type.mjs +3 -2
  52. package/api/render/_adapter.d.mts +28 -0
  53. package/api/render/_adapter.mjs +540 -0
  54. package/api/render/render.d.mts +15 -0
  55. package/api/render/render.doc.d.mts +9 -0
  56. package/api/render/render.doc.mjs +112 -0
  57. package/api/render/render.mjs +113 -0
  58. package/api/render/render.test.mjs +1155 -0
  59. package/api/render/render.type.d.mts +74 -0
  60. package/api/render/render.type.mjs +64 -0
  61. package/api/search/_adapter.test.mjs +21 -2
  62. package/api/search/_result.d.mts +5 -5
  63. package/api/search/search.d.mts +1 -1
  64. package/api/template/template.mjs +3 -1
  65. package/api/template/template.type.d.mts +2 -1
  66. package/api/template/template.type.mjs +1 -1
  67. package/api/template/unknown-name.test.mjs +63 -0
  68. package/api/upgrade/run/failure-receipt.test.mjs +155 -0
  69. package/api/upgrade/run/run.mjs +170 -8
  70. package/api/upgrade/upgrade.doc.mjs +4 -4
  71. package/api/upgrade/upgrade.mjs +19 -4
  72. package/api/upgrade/upgrade.type.d.mts +12 -1
  73. package/api/upgrade/upgrade.type.mjs +16 -3
  74. package/assets/codemods/__tests__/runner.symlinks.test.mjs +205 -0
  75. package/assets/codemods/integration-runner.mjs +1 -1
  76. package/assets/codemods/run-codemod.mjs +17 -3
  77. package/assets/codemods/runner.mjs +81 -8
  78. package/assets/codemods/transform-prop.mjs +99 -49
  79. package/assets/codemods/transform-prop.test.mjs +36 -1
  80. package/assets/codemods/transforms/v0.7.0/__tests__/migrate-deprecated-theme-surface.test.mjs +207 -6
  81. package/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  82. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface-v0.6-data.mjs +6 -1
  83. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +200 -32
  84. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  85. package/assets/discover/official-packages.json +4 -0
  86. package/assets/docs/tree/icon-definitions.doc.mjs +2 -2
  87. package/assets/docs/tree/icon-set-files.doc.mjs +1 -1
  88. package/assets/docs/tree/icon-sets.doc.mjs +50 -20
  89. package/assets/docs/tree/render-pages.doc.mjs +94 -0
  90. package/assets/docs/tree/styling-advanced.doc.mjs +1 -1
  91. package/assets/icons/definitions/activity.doc.mjs +1 -1
  92. package/assets/icons/definitions/alignCenter.doc.mjs +9 -0
  93. package/assets/icons/definitions/alignEnd.doc.mjs +10 -0
  94. package/assets/icons/definitions/alignStart.doc.mjs +10 -0
  95. package/assets/icons/definitions/archive.doc.mjs +1 -1
  96. package/assets/icons/definitions/arrowsUpDown.doc.mjs +1 -1
  97. package/assets/icons/definitions/attach.doc.mjs +1 -1
  98. package/assets/icons/definitions/audio.doc.mjs +1 -1
  99. package/assets/icons/definitions/cart.doc.mjs +1 -1
  100. package/assets/icons/definitions/checkDouble.doc.mjs +1 -1
  101. package/assets/icons/definitions/chevronsLeft.doc.mjs +1 -1
  102. package/assets/icons/definitions/chevronsRight.doc.mjs +1 -1
  103. package/assets/icons/definitions/close.doc.mjs +1 -1
  104. package/assets/icons/definitions/collapse.doc.mjs +1 -1
  105. package/assets/icons/definitions/compose.doc.mjs +1 -1
  106. package/assets/icons/definitions/conversation.doc.mjs +1 -1
  107. package/assets/icons/definitions/copy.doc.mjs +1 -1
  108. package/assets/icons/definitions/cpu.doc.mjs +9 -0
  109. package/assets/icons/definitions/database.doc.mjs +1 -1
  110. package/assets/icons/definitions/desktop.doc.mjs +1 -1
  111. package/assets/icons/definitions/discount.doc.mjs +1 -1
  112. package/assets/icons/definitions/download.doc.mjs +1 -1
  113. package/assets/icons/definitions/emoji.doc.mjs +1 -1
  114. package/assets/icons/definitions/error.doc.mjs +1 -1
  115. package/assets/icons/definitions/expand.doc.mjs +1 -1
  116. package/assets/icons/definitions/experiment.doc.mjs +1 -1
  117. package/assets/icons/definitions/externalLink.doc.mjs +7 -1
  118. package/assets/icons/definitions/eyeSlash.doc.mjs +1 -1
  119. package/assets/icons/definitions/flipHorizontal.doc.mjs +9 -0
  120. package/assets/icons/definitions/flipVertical.doc.mjs +9 -0
  121. package/assets/icons/definitions/folderAdd.doc.mjs +1 -1
  122. package/assets/icons/definitions/gitBranch.doc.mjs +9 -0
  123. package/assets/icons/definitions/gitFork.doc.mjs +9 -0
  124. package/assets/icons/definitions/info.doc.mjs +1 -1
  125. package/assets/icons/definitions/location.doc.mjs +1 -1
  126. package/assets/icons/definitions/mention.doc.mjs +1 -1
  127. package/assets/icons/definitions/menu.doc.mjs +1 -1
  128. package/assets/icons/definitions/microphone.doc.mjs +1 -1
  129. package/assets/icons/definitions/mobile.doc.mjs +1 -1
  130. package/assets/icons/definitions/money.doc.mjs +1 -1
  131. package/assets/icons/definitions/moreHorizontal.doc.mjs +1 -1
  132. package/assets/icons/definitions/notificationActive.doc.mjs +1 -1
  133. package/assets/icons/definitions/notificationOff.doc.mjs +1 -1
  134. package/assets/icons/definitions/panelLeft.doc.mjs +10 -0
  135. package/assets/icons/definitions/panelRight.doc.mjs +10 -0
  136. package/assets/icons/definitions/raiseHand.doc.mjs +1 -1
  137. package/assets/icons/definitions/redo.doc.mjs +1 -1
  138. package/assets/icons/definitions/refresh.doc.mjs +1 -1
  139. package/assets/icons/definitions/rotate.doc.mjs +9 -0
  140. package/assets/icons/definitions/scale.doc.mjs +10 -0
  141. package/assets/icons/definitions/search.doc.mjs +1 -1
  142. package/assets/icons/definitions/send.doc.mjs +1 -1
  143. package/assets/icons/definitions/settings.doc.mjs +1 -1
  144. package/assets/icons/definitions/star.doc.mjs +1 -1
  145. package/assets/icons/definitions/stop.doc.mjs +1 -1
  146. package/assets/icons/definitions/success.doc.mjs +1 -1
  147. package/assets/icons/definitions/textCase.doc.mjs +9 -0
  148. package/assets/icons/definitions/thumbsDown.doc.mjs +1 -1
  149. package/assets/icons/definitions/thumbsUp.doc.mjs +1 -1
  150. package/assets/icons/definitions/trendDown.doc.mjs +7 -1
  151. package/assets/icons/definitions/trendUp.doc.mjs +1 -1
  152. package/assets/icons/definitions/undo.doc.mjs +1 -1
  153. package/assets/icons/definitions/upload.doc.mjs +1 -1
  154. package/assets/icons/definitions/userAdd.doc.mjs +1 -1
  155. package/assets/icons/definitions/warning.doc.mjs +1 -1
  156. package/assets/templates/blocks/components/Tokenizer/TokenizerClear.tsx +15 -14
  157. package/assets/templates/blocks/components/Tokenizer/TokenizerCreatable.tsx +30 -30
  158. package/assets/templates/blocks/components/Tokenizer/TokenizerEndContent.tsx +15 -14
  159. package/assets/templates/blocks/components/Tokenizer/TokenizerIcon.tsx +15 -14
  160. package/assets/templates/blocks/components/Tokenizer/TokenizerMaxEntries.tsx +17 -16
  161. package/assets/templates/blocks/components/Tokenizer/TokenizerOverflow.tsx +29 -29
  162. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +9 -8
  163. package/assets/templates/blocks/components/Tokenizer/TokenizerStates.tsx +39 -41
  164. package/assets/templates/pages/canvas-editor/template.doc.mjs +9 -0
  165. package/assets/templates/pages/form-wizard-inline/template.doc.mjs +6 -1
  166. package/assets/templates/pages/table-comparison/template.doc.mjs +1 -0
  167. package/assets/templates/pages/table-tree/template.doc.mjs +3 -0
  168. package/authoring/debug/parse.d.mts +2 -2
  169. package/authoring/doctypes/icon-definition/icon-definition.doc.mjs +4 -4
  170. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +6 -0
  171. package/authoring/doctypes/icon-set/parse.d.mts +1 -0
  172. package/authoring/doctypes/icon-set/parse.mjs +1 -0
  173. package/authoring/doctypes/icon-set/type.ts +5 -0
  174. package/authoring/doctypes/template/template.doc.mjs +1 -1
  175. package/authoring/doctypes/template/type.ts +2 -1
  176. package/clients/cli/commands/doctor.mjs +16 -17
  177. package/clients/cli/commands/experimental/icon.mjs +167 -35
  178. package/clients/cli/commands/experimental/index.mjs +2 -0
  179. package/clients/cli/commands/experimental/render.mjs +113 -0
  180. package/clients/cli/commands/experimental-icon-add.doc.mjs +14 -4
  181. package/clients/cli/commands/experimental-icon-map.doc.mjs +12 -2
  182. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +1 -1
  183. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +28 -1
  184. package/clients/cli/commands/experimental-icon.doc.mjs +18 -2
  185. package/clients/cli/commands/experimental-render.doc.mjs +60 -0
  186. package/clients/cli/commands/experimental.doc.mjs +4 -2
  187. package/clients/cli/commands/icon-authoring.test.mjs +1823 -13
  188. package/clients/cli/commands/icon-options-wiring.test.mjs +158 -0
  189. package/clients/cli/commands/icon.test.mjs +1 -1
  190. package/clients/cli/commands/template.mjs +4 -1
  191. package/clients/cli/commands/text-json-parity.test.mjs +46 -0
  192. package/clients/cli/commands/upgrade.doc.mjs +17 -0
  193. package/clients/cli/commands/upgrade.file-protection.test.mjs +29 -0
  194. package/clients/cli/commands/upgrade.flag-help.test.mjs +37 -0
  195. package/clients/cli/commands/upgrade.integration-policy.test.mjs +103 -0
  196. package/clients/cli/commands/upgrade.mjs +9 -2
  197. package/clients/cli/index.mjs +1 -0
  198. package/foundation/discovery/component-discovery.d.mts +2 -1
  199. package/foundation/discovery/component-discovery.export-names.test.mjs +41 -0
  200. package/foundation/discovery/component-discovery.mjs +13 -7
  201. package/foundation/discovery/icon-set-checks.d.mts +43 -9
  202. package/foundation/discovery/icon-set-checks.mjs +296 -21
  203. package/foundation/discovery/icon-set-checks.test.mjs +125 -12
  204. package/foundation/discovery/icon-set-writer.d.mts +192 -3
  205. package/foundation/discovery/icon-set-writer.mjs +608 -34
  206. package/foundation/discovery/icon-set-writer.test.mjs +26 -0
  207. package/foundation/discovery/module-exports.mjs +82 -25
  208. package/foundation/discovery/module-exports.test.mjs +38 -1
  209. package/foundation/discovery/package-exports.d.mts +13 -0
  210. package/foundation/discovery/package-exports.mjs +40 -1
  211. package/foundation/discovery/template-icons.d.mts +6 -0
  212. package/foundation/discovery/template-icons.mjs +98 -10
  213. package/foundation/discovery/template-icons.test.mjs +103 -0
  214. package/foundation/doc-compiler/doc-loads.test.mjs +20 -5
  215. package/foundation/doc-compiler/import.mjs +81 -8
  216. package/foundation/doc-compiler/read.d.mts +4 -3
  217. package/foundation/doc-compiler/read.mjs +15 -10
  218. package/foundation/doc-compiler/read.test.mjs +59 -1
  219. package/foundation/doc-compiler/tree.mjs +3 -1
  220. package/foundation/fs/module-loader.d.mts +3 -2
  221. package/foundation/fs/module-loader.mjs +3 -2
  222. package/foundation/fs/publish-file-eperm-mutation.test.mjs +2 -0
  223. package/foundation/fs/read-record.d.mts +27 -0
  224. package/foundation/fs/read-record.mjs +83 -15
  225. package/foundation/fs/read-record.test.mjs +88 -1
  226. package/foundation/render/assets.d.mts +31 -0
  227. package/foundation/render/assets.mjs +102 -0
  228. package/foundation/render/component-map.d.mts +52 -0
  229. package/foundation/render/component-map.mjs +141 -0
  230. package/foundation/render/css-cut.d.mts +29 -0
  231. package/foundation/render/css-cut.mjs +144 -0
  232. package/foundation/render/embedded-files.d.mts +28 -0
  233. package/foundation/render/embedded-files.mjs +108 -0
  234. package/foundation/render/embedded-imports.d.mts +61 -0
  235. package/foundation/render/embedded-imports.mjs +315 -0
  236. package/foundation/render/html-reader.d.mts +37 -0
  237. package/foundation/render/html-reader.mjs +121 -0
  238. package/foundation/render/page-worker.d.mts +7 -0
  239. package/foundation/render/page-worker.mjs +519 -0
  240. package/foundation/render/rebuild.d.mts +19 -0
  241. package/foundation/render/rebuild.mjs +269 -0
  242. package/foundation/render/render-page.d.mts +85 -0
  243. package/foundation/render/render-page.mjs +612 -0
  244. package/foundation/render/render.test.mjs +117 -0
  245. package/foundation/render/source-block.d.mts +52 -0
  246. package/foundation/render/source-block.mjs +106 -0
  247. package/foundation/response/base.d.ts +7 -0
  248. package/foundation/response/error-codes.d.mts +10 -1
  249. package/foundation/response/error-codes.doc.mjs +59 -2
  250. package/foundation/response/error-codes.mjs +62 -1
  251. package/foundation/response/json.d.mts +10 -3
  252. package/foundation/response/json.mjs +16 -4
  253. package/foundation/response/response-types.doc.mjs +38 -1
  254. package/foundation/text/string-utils.mjs +33 -0
  255. package/foundation/text/string-utils.test.mjs +17 -0
  256. package/foundation/text/suggest-order.d.mts +17 -3
  257. package/foundation/text/suggest-order.mjs +58 -13
  258. package/foundation/text/suggest-order.test.mjs +53 -0
  259. package/package.json +14 -9
@@ -0,0 +1,612 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file `astryx experimental render`, forward: one page module to ONE
5
+ * self-contained static HTML file. The page renders on the server with the
6
+ * project's own React and Astryx components; its own StyleX compiles in
7
+ * memory; Core's stylesheets are cut to the rules the markup uses; local
8
+ * images become data: URIs; and the page's source rides along so
9
+ * `--reverse` can give it back exactly.
10
+ *
11
+ * The file needs no network and runs no script, so it works inside a
12
+ * sandboxed frame with a strict content security policy. Its colors follow
13
+ * `color-scheme` (and a `data-theme` of `light` or `dark` on the root), since
14
+ * Astryx tokens use light-dark().
15
+ *
16
+ * @position foundation/render — called by the render subject's adapter
17
+ */
18
+
19
+ import * as fs from 'node:fs';
20
+ import * as path from 'node:path';
21
+ import {createRequire} from 'node:module';
22
+ import {Worker} from 'node:worker_threads';
23
+ import postcss from 'postcss';
24
+ import {assetDataUri, isAssetBytes, isAssetPath, RenderAssetError} from './assets.mjs';
25
+ import {classesIn, cutCss, layerOrderOf} from './css-cut.mjs';
26
+ import {sourceBlock} from './source-block.mjs';
27
+ import {embeddedPathProblem} from './embedded-files.mjs';
28
+
29
+ /** How long one page may take to render before it is stopped. */
30
+ export const RENDER_TIMEOUT_MS = 60_000;
31
+
32
+ export {PAGE_EXTENSIONS} from './embedded-files.mjs';
33
+
34
+ /**
35
+ * @typedef {object} RenderWarning
36
+ * @property {'dropped-children' | 'remote-asset' | 'missing-asset' | 'page-output' | 'page-script' | 'no-astryx-styles' | 'chart-size' | 'not-embedded'} code - What kind of problem.
37
+ * @property {string} message - What happened and what to do, in one sentence.
38
+ */
39
+
40
+ /**
41
+ * @typedef {object} RenderedPage
42
+ * @property {string} html - The whole file.
43
+ * @property {string[]} files - Local files the page loaded, relative to the folder that holds them all (the page's folder unless it imports from above it); the page first. Each is embedded.
44
+ * @property {string[]} stylesheets - The packages' stylesheets that were cut and inlined.
45
+ * @property {number} classes - Distinct class names in the markup.
46
+ * @property {number} cssBytes - Bytes of inlined CSS.
47
+ * @property {number} markupBytes - Bytes of rendered markup.
48
+ * @property {number} images - Local files inlined as data: URIs.
49
+ * @property {RenderWarning[]} warnings
50
+ */
51
+
52
+ /** An error carrying a render error code. */
53
+ export class RenderError extends Error {
54
+ /**
55
+ * @param {string} code
56
+ * @param {string} message
57
+ * @param {Record<string, unknown>} [detail]
58
+ */
59
+ constructor(code, message, detail) {
60
+ super(message);
61
+ this.code = code;
62
+ this.detail = detail;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The nearest folder at or above `dir` with a package.json, else `dir`.
68
+ * @param {string} dir
69
+ */
70
+ function projectRootOf(dir) {
71
+ let d = dir;
72
+ for (;;) {
73
+ if (fs.existsSync(path.join(d, 'package.json'))) return d;
74
+ const up = path.dirname(d);
75
+ if (up === d) return dir;
76
+ d = up;
77
+ }
78
+ }
79
+
80
+ /** @param {string} s */
81
+ const escapeHtml = s =>
82
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
83
+
84
+ /** @param {string} s */
85
+ const decodeAttr = s =>
86
+ s
87
+ .replace(/&quot;/g, '"')
88
+ .replace(/&#x27;|&#39;/g, "'")
89
+ .replace(/&lt;/g, '<')
90
+ .replace(/&gt;/g, '>')
91
+ .replace(/&amp;/g, '&');
92
+
93
+ /**
94
+ * An `@import` rule's parts: what it loads, and the layer, supports() and
95
+ * media conditions that scope it.
96
+ * @param {string} params
97
+ * @returns {{url: string, layer: string | null, supports: string | null, media: string} | null}
98
+ */
99
+ function importParams(params) {
100
+ const m = /^\s*(?:url\(\s*(['"]?)([\s\S]*?)\1\s*\)|(['"])([\s\S]*?)\3)\s*([\s\S]*)$/.exec(params);
101
+ if (!m) return null;
102
+ let rest = m[5];
103
+ /** @type {string | null} */
104
+ let layer = null;
105
+ const lay = /^layer(?:\(\s*([^)]*?)\s*\))?(?=\s|$)\s*/i.exec(rest);
106
+ if (lay) {
107
+ layer = lay[1] ?? '';
108
+ rest = rest.slice(lay[0].length);
109
+ }
110
+ /** @type {string | null} */
111
+ let supports = null;
112
+ const sup = /^supports\(((?:[^()]|\((?:[^()]|\([^()]*\))*\))*)\)\s*/i.exec(rest);
113
+ if (sup) {
114
+ supports = sup[1];
115
+ rest = rest.slice(sup[0].length);
116
+ }
117
+ return {url: m[2] ?? m[4] ?? '', layer, supports, media: rest.trim()};
118
+ }
119
+
120
+ /**
121
+ * Inline a stylesheet's own `@import`s, so a stylesheet pulled in that way is
122
+ * part of the file: a relative one from the importing sheet's folder
123
+ * (carried when it is the project's own), a package one (`@scope/pkg/x.css`)
124
+ * by Node resolution from the importing sheet. Each keeps its `layer()`,
125
+ * `supports()` and media conditions, and relative url()s in it are rewritten
126
+ * to stay right. A remote import is dropped with a warning (a sandboxed page
127
+ * cannot load it), a Sass or Less one is named in a warning, and cycles are
128
+ * cut.
129
+ * @param {string} file the stylesheet's own path
130
+ * @param {string} css its text
131
+ * @param {{warnings: RenderWarning[], carried: Set<string>, included: Set<string>, packageSheets: string[], seen?: Set<string>}} ctx
132
+ * `included`: stylesheet files already in the page (Core's, say), never
133
+ * inlined twice; `packageSheets`: package stylesheets this pulled in
134
+ * @returns {string}
135
+ */
136
+ function expandImports(file, css, ctx) {
137
+ if (!/@import/i.test(css)) return css;
138
+ const seen = ctx.seen ?? new Set([file]);
139
+ /** @type {import('postcss').Root} */
140
+ let root;
141
+ try {
142
+ root = postcss.parse(css, {from: file});
143
+ } catch {
144
+ return css;
145
+ }
146
+ root.walkAtRules(/^import$/i, rule => {
147
+ const parsed = importParams(rule.params);
148
+ if (!parsed || !parsed.url) return;
149
+ const {url} = parsed;
150
+ if (/^([a-z]+:)?\/\//i.test(url)) {
151
+ ctx.warnings.push({
152
+ code: 'remote-asset',
153
+ message: `${path.basename(file)} imports ${url}, which a sandboxed page cannot load, so it is left out; save it beside the stylesheet and import it instead.`,
154
+ });
155
+ rule.remove();
156
+ return;
157
+ }
158
+ if (/\.(scss|sass|less)$/i.test(url)) {
159
+ ctx.warnings.push({
160
+ code: 'missing-asset',
161
+ message: `${path.basename(file)} imports ${url}, a Sass or Less stylesheet, which a render does not compile, so its styles are missing.`,
162
+ });
163
+ rule.remove();
164
+ return;
165
+ }
166
+ const relative = path.resolve(path.dirname(file), url);
167
+ /** @type {string | null} */
168
+ let target;
169
+ let fromPackage = false;
170
+ if (/^\.{1,2}\//.test(url) || fs.existsSync(relative)) {
171
+ target = fs.existsSync(relative) ? relative : null;
172
+ } else {
173
+ try {
174
+ target = createRequire(file).resolve(url.replace(/^~/, ''));
175
+ fromPackage = true;
176
+ } catch {
177
+ target = null;
178
+ }
179
+ }
180
+ if (!target) {
181
+ ctx.warnings.push({
182
+ code: 'missing-asset',
183
+ message: `${path.basename(file)} imports ${url}, which was not found, so its styles are missing.`,
184
+ });
185
+ rule.remove();
186
+ return;
187
+ }
188
+ if (seen.has(target) || ctx.included.has(target)) {
189
+ rule.remove();
190
+ return;
191
+ }
192
+ seen.add(target);
193
+ ctx.included.add(target);
194
+ if (fromPackage) ctx.packageSheets.push(url.replace(/^~/, ''));
195
+ else ctx.carried.add(target);
196
+ const from = target;
197
+ let inner = expandImports(from, fs.readFileSync(from, 'utf8'), {...ctx, seen});
198
+ // Keep the imported sheet's relative url()s pointing at the same files.
199
+ inner = inner.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (u, q, r) => {
200
+ if (/^(data:|blob:|#|\/|[a-z]+:)/i.test(r)) return u;
201
+ const rebased = path
202
+ .relative(path.dirname(file), path.resolve(path.dirname(from), r))
203
+ .split(path.sep)
204
+ .join('/');
205
+ return `url(${q}${rebased.startsWith('.') ? rebased : `./${rebased}`}${q})`;
206
+ });
207
+ // The import's conditions still scope what it brings in.
208
+ if (parsed.supports) inner = `@supports (${parsed.supports.replace(/^\((.*)\)$/s, '$1')}){${inner}}`;
209
+ if (parsed.media) inner = `@media ${parsed.media}{${inner}}`;
210
+ if (parsed.layer !== null) inner = `@layer${parsed.layer ? ` ${parsed.layer}` : ''}{${inner}}`;
211
+ try {
212
+ rule.replaceWith(postcss.parse(inner, {from}).nodes);
213
+ } catch (e) {
214
+ const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
215
+ throw new RenderError(
216
+ 'ERR_RENDER_COMPILE',
217
+ `${path.basename(from)}, imported by ${path.basename(file)}, is not valid CSS: ${reason}`,
218
+ );
219
+ }
220
+ });
221
+ return root.toString();
222
+ }
223
+
224
+ /**
225
+ * Run the page in a worker, stopping it after `timeoutMs`.
226
+ * @param {string} entry
227
+ * @param {string} root
228
+ * @param {number} timeoutMs
229
+ * @returns {Promise<any>}
230
+ */
231
+ function runWorker(entry, root, timeoutMs) {
232
+ return new Promise((resolve, reject) => {
233
+ const worker = new Worker(new URL('./page-worker.mjs', import.meta.url), {
234
+ workerData: {entry, root},
235
+ execArgv: [],
236
+ stdout: true,
237
+ stderr: true,
238
+ resourceLimits: {maxOldGenerationSizeMb: 4096},
239
+ });
240
+ // The page's own writes to stdout/stderr never reach the CLI's output.
241
+ worker.stdout.resume();
242
+ worker.stderr.resume();
243
+ let settled = false;
244
+ const timer = setTimeout(() => {
245
+ if (settled) return;
246
+ settled = true;
247
+ void worker.terminate();
248
+ reject(
249
+ new RenderError(
250
+ 'ERR_RENDER_TIMEOUT',
251
+ `The page did not finish rendering within ${timeoutMs / 1000} seconds, so it was stopped. Look for a loop that never ends or a promise the page waits on.`,
252
+ {seconds: timeoutMs / 1000},
253
+ ),
254
+ );
255
+ }, timeoutMs);
256
+ worker.once('message', message => {
257
+ if (settled) return;
258
+ settled = true;
259
+ clearTimeout(timer);
260
+ void worker.terminate();
261
+ resolve(message);
262
+ });
263
+ worker.once('error', (/** @type {any} */ error) => {
264
+ if (settled) return;
265
+ settled = true;
266
+ clearTimeout(timer);
267
+ const out =
268
+ /ERR_WORKER_OUT_OF_MEMORY|heap out of memory/.test(String(error?.message ?? error))
269
+ ? new RenderError('ERR_RENDER_FAILED', 'The page ran out of memory while rendering.')
270
+ : new RenderError('ERR_RENDER_FAILED', `The page could not be rendered: ${String(error?.message ?? error).split('\n')[0]}`);
271
+ reject(out);
272
+ });
273
+ worker.once('exit', code => {
274
+ if (settled) return;
275
+ settled = true;
276
+ clearTimeout(timer);
277
+ reject(new RenderError('ERR_RENDER_FAILED', `The page stopped rendering without an answer (exit ${code}).`));
278
+ });
279
+ });
280
+ }
281
+
282
+ /**
283
+ * Inline local images (src, srcset, poster and CSS url()) as data: URIs. A
284
+ * link (`href`) loads nothing, so it is left alone.
285
+ * @param {string} text markup or CSS
286
+ * @param {'html' | 'css'} kind
287
+ * @param {{dir: string, root: string, warnings: RenderWarning[], counted: Set<string>, localAssets: Set<string>}} ctx
288
+ */
289
+ function inlineAssets(text, kind, ctx) {
290
+ /** @param {string} ref */
291
+ const resolveRef = ref => {
292
+ const clean = decodeAttr(ref).trim().split(/[?#]/)[0];
293
+ if (!clean) return null;
294
+ if (/^(data:|blob:|#|about:|mailto:|tel:|javascript:)/i.test(clean)) return null;
295
+ if (/^(https?:)?\/\//i.test(clean)) {
296
+ const key = `remote:${clean}`;
297
+ if (!ctx.counted.has(key)) {
298
+ ctx.counted.add(key);
299
+ ctx.warnings.push({
300
+ code: 'remote-asset',
301
+ message: `${clean} is loaded from the network, which a sandboxed page cannot reach; save it beside the page and import it instead.`,
302
+ });
303
+ }
304
+ return null;
305
+ }
306
+ if (!isAssetPath(clean)) return null;
307
+ const candidates = clean.startsWith('/')
308
+ ? [path.join(ctx.root, 'public', clean), path.join(ctx.root, clean)]
309
+ : [path.resolve(ctx.dir, clean)];
310
+ const found = candidates.find(c => fs.existsSync(c));
311
+ if (!found) {
312
+ const key = `missing:${clean}`;
313
+ if (!ctx.counted.has(key)) {
314
+ ctx.counted.add(key);
315
+ ctx.warnings.push({
316
+ code: 'missing-asset',
317
+ message: `${clean} was not found next to the page, so it is left as is and will not show.`,
318
+ });
319
+ }
320
+ return null;
321
+ }
322
+ ctx.counted.add(`file:${found}`);
323
+ // A relative path names a file that is part of the page: carry it.
324
+ if (!clean.startsWith('/')) ctx.localAssets.add(found);
325
+ return assetDataUri(found);
326
+ };
327
+ /** @param {string} value */
328
+ const urls = value =>
329
+ value.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g, (whole, q, ref) => {
330
+ const uri = resolveRef(ref);
331
+ return uri ? `url("${uri}")` : whole;
332
+ });
333
+ if (kind === 'css') return urls(text);
334
+ return text
335
+ .replace(/\s(src|poster)="([^"]*)"/g, (whole, attr, ref) => {
336
+ const uri = resolveRef(ref);
337
+ return uri ? ` ${attr}="${uri}"` : whole;
338
+ })
339
+ .replace(/\ssrcset="([^"]*)"/g, (whole, set) => {
340
+ const parts = decodeAttr(set)
341
+ .split(',')
342
+ .map(part => {
343
+ const [ref, ...rest] = part.trim().split(/\s+/);
344
+ const uri = ref ? resolveRef(ref) : null;
345
+ return [uri ?? ref, ...rest].join(' ');
346
+ });
347
+ return ` srcset="${parts.join(', ').replace(/"/g, '&quot;')}"`;
348
+ })
349
+ .replace(/\sstyle="([^"]*)"/g, (whole, style) => {
350
+ // The attribute holds escaped text: rewrite the CSS it means, then
351
+ // escape it again, so a data: URI's quotes cannot end the attribute.
352
+ const css = urls(decodeAttr(style));
353
+ return ` style="${css.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}"`;
354
+ });
355
+ }
356
+
357
+ /** The light and dark switch every rendered page carries. */
358
+ const SCHEME_CSS =
359
+ ':root{color-scheme:light dark}:root[data-theme="light"]{color-scheme:light}:root[data-theme="dark"]{color-scheme:dark}';
360
+
361
+ /**
362
+ * Render a page module to one self-contained HTML file.
363
+ * @param {string} entry absolute path of the page module
364
+ * @param {{title?: string, timeoutMs?: number, version?: string}} [options]
365
+ * @returns {Promise<RenderedPage>}
366
+ */
367
+ export async function renderPage(entry, options = {}) {
368
+ const dir = path.dirname(entry);
369
+ const root = projectRootOf(dir);
370
+ const message = await runWorker(entry, root, options.timeoutMs ?? RENDER_TIMEOUT_MS);
371
+ /** @type {RenderWarning[]} */
372
+ const warnings = [];
373
+ if (!message.ok) {
374
+ throw new RenderError(message.error.code, message.error.message, message.error.detail);
375
+ }
376
+ /** @type {string} */
377
+ let markup = message.markup;
378
+
379
+ // Stylesheets: Core's reset and components, plus each official package's
380
+ // own stylesheet the page imports from.
381
+ const req = createRequire(entry);
382
+ /** @type {string[]} */
383
+ const sheets = [];
384
+ /** @type {string[]} */
385
+ const sheetText = [];
386
+ /** Each stylesheet's own file, so its url()s resolve from its folder. @type {string[]} */
387
+ const sheetFiles = [];
388
+ /** @param {string} spec */
389
+ const addSheet = spec => {
390
+ try {
391
+ const file = req.resolve(spec);
392
+ sheets.push(spec);
393
+ sheetText.push(fs.readFileSync(file, 'utf8'));
394
+ sheetFiles.push(file);
395
+ return true;
396
+ } catch {
397
+ return false;
398
+ }
399
+ };
400
+ const hasCore = addSheet('@astryxdesign/core/reset.css');
401
+ if (hasCore) addSheet('@astryxdesign/core/astryx.css');
402
+ // Package stylesheets the page imports itself, such as a theme's.
403
+ for (const {spec, from} of /** @type {{spec: string, from: string}[]} */ (message.packageCss ?? [])) {
404
+ if (sheets.includes(spec)) continue;
405
+ try {
406
+ const file = createRequire(from).resolve(spec);
407
+ sheets.push(spec);
408
+ sheetText.push(fs.readFileSync(file, 'utf8'));
409
+ sheetFiles.push(file);
410
+ } catch {
411
+ warnings.push({
412
+ code: 'missing-asset',
413
+ message: `The page imports the stylesheet ${spec}, which could not be found, so its styles are missing.`,
414
+ });
415
+ }
416
+ }
417
+ for (const pkg of /** @type {string[]} */ (message.packages ?? [])) {
418
+ const m = /^@astryxdesign\/([a-z0-9-]+)$/.exec(pkg);
419
+ if (!m || m[1] === 'core') continue;
420
+ addSheet(`${pkg}/${m[1]}.css`);
421
+ }
422
+ if (!hasCore) {
423
+ warnings.push({
424
+ code: 'no-astryx-styles',
425
+ message:
426
+ '@astryxdesign/core is not installed where the page is, so the page has no Astryx styles; install it, or render from inside the project.',
427
+ });
428
+ }
429
+
430
+ const ctx = {dir, root, warnings, counted: new Set(), localAssets: /** @type {Set<string>} */ (new Set())};
431
+ /** Stylesheets pulled in by another's `@import`. @type {Set<string>} */
432
+ const carriedCss = new Set();
433
+ try {
434
+ markup = inlineAssets(markup, 'html', ctx);
435
+ // React adds `<link rel="preload">` hints for images it renders; in one
436
+ // static file they only fetch from the network, so they go.
437
+ markup = markup.replace(/<link rel="preload"[^>]*\/?>/g, '');
438
+ // What the page itself renders that would run or load something: the
439
+ // file promises neither, so say so.
440
+ if (/<script\b/i.test(markup)) {
441
+ warnings.push({
442
+ code: 'page-script',
443
+ message:
444
+ '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.',
445
+ });
446
+ }
447
+ for (const m of markup.matchAll(/<(link|iframe|object|embed)\b[^>]*?\s(?:href|src|data)="([^"]*)"/gi)) {
448
+ if (/^(data:|#)/i.test(m[2])) continue;
449
+ warnings.push({
450
+ code: 'remote-asset',
451
+ message: `The page renders a <${m[1].toLowerCase()}> that loads ${m[2]}, which a sandboxed page cannot reach and which loads from the network anywhere else; remove it from the page.`,
452
+ });
453
+ }
454
+ } catch (e) {
455
+ const err = /** @type {any} */ (e);
456
+ if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
457
+ throw e;
458
+ }
459
+ const used = classesIn(markup);
460
+ const layerOrder = sheetText.map(layerOrderOf).find(Boolean) ?? '';
461
+ let css = layerOrder;
462
+ try {
463
+ // A stylesheet's url()s are relative to the stylesheet, not the page: a
464
+ // theme's font, or an image beside an imported stylesheet.
465
+ const included = new Set(sheetFiles);
466
+ /** @type {string[]} */
467
+ const packageSheets = [];
468
+ /** A stylesheet's rules cut to the page, with its own imports inlined. @param {string} file @param {string} text */
469
+ const sheet = (file, text) => {
470
+ try {
471
+ const own = expandImports(file, text, {warnings, carried: carriedCss, included, packageSheets});
472
+ return inlineAssets(cutCss(own, used), 'css', {...ctx, dir: path.dirname(file)});
473
+ } catch (e) {
474
+ if (e instanceof RenderAssetError || e instanceof RenderError) throw e;
475
+ const reason = /** @type {any} */ (e)?.reason ?? (e instanceof Error ? e.message : String(e));
476
+ throw new RenderError(
477
+ 'ERR_RENDER_COMPILE',
478
+ `${path.relative(dir, file).split(path.sep).join('/')} is not valid CSS: ${reason}`,
479
+ );
480
+ }
481
+ };
482
+ sheetText.forEach((text, i) => {
483
+ css += sheet(sheetFiles[i], text);
484
+ });
485
+ for (const {file, css: text} of /** @type {{file: string, css: string}[]} */ (message.importedCss ?? [])) {
486
+ css += sheet(file, text);
487
+ }
488
+ for (const spec of packageSheets) if (!sheets.includes(spec)) sheets.push(spec);
489
+ if (message.css) css += inlineAssets(message.css, 'css', ctx);
490
+ } catch (e) {
491
+ const err = /** @type {any} */ (e);
492
+ if (err instanceof RenderAssetError) throw new RenderError(err.code, err.message, err.detail);
493
+ throw e;
494
+ }
495
+ // Keep inlined CSS from ending its own <style> element.
496
+ css = css.replace(/<\/style/gi, '<\\/style');
497
+
498
+ // A component that dropped the text it was given: its text is missing while
499
+ // text next to it rendered.
500
+ const plainText = markup
501
+ .replace(/<[^>]*>/g, ' ')
502
+ .replace(/&amp;/g, '&')
503
+ .replace(/&lt;/g, '<')
504
+ .replace(/&gt;/g, '>')
505
+ .replace(/&quot;/g, '"')
506
+ .replace(/&#x27;|&#39;/g, "'")
507
+ .replace(/&nbsp;/g, ' ')
508
+ .replace(/\s+/g, ' ');
509
+ for (const t of /** @type {any[]} */ (message.texts ?? [])) {
510
+ if (t.hidden || t.text.length < 2 || plainText.includes(t.text)) continue;
511
+ // The code around it ran: other text from the same function rendered.
512
+ const around = /** @type {string[]} */ (message.fnTexts?.[t.fn] ?? []).filter(o => o !== t.text);
513
+ if (!around.some(o => plainText.includes(o))) continue;
514
+ warnings.push({
515
+ code: 'dropped-children',
516
+ message: `<${t.component}> on line ${t.line} did not render the text "${t.text.length > 60 ? `${t.text.slice(0, 57)}...` : t.text}" it was given; it takes that text through a prop (often label=), so check its props.`,
517
+ });
518
+ }
519
+ for (const f of /** @type {string[]} */ (message.files ?? [])) {
520
+ const src = fs.readFileSync(f, 'utf8');
521
+ if (/\bResponsiveContainer\b/.test(src)) {
522
+ warnings.push({
523
+ code: 'chart-size',
524
+ message: `${path.basename(f)} sizes a chart with ResponsiveContainer, which has no size until a browser measures it, so the chart is empty here; give the chart a fixed width and height.`,
525
+ });
526
+ break;
527
+ }
528
+ }
529
+ for (const sheet of /** @type {string[]} */ (message.skippedCss ?? [])) {
530
+ warnings.push({
531
+ code: 'missing-asset',
532
+ message: `The page imports ${sheet}, a Sass or Less stylesheet, which a render does not compile, so its styles are missing.`,
533
+ });
534
+ }
535
+ for (const log of /** @type {{level: string, text: string}[]} */ (message.logs ?? []).slice(0, 5)) {
536
+ warnings.push({
537
+ code: 'page-output',
538
+ message: `The page printed while rendering (${log.level}): ${log.text.split('\n')[0].slice(0, 200)}`,
539
+ });
540
+ }
541
+
542
+ const files = /** @type {string[]} */ (message.files ?? [entry]);
543
+ if (!files.includes(entry)) files.unshift(entry);
544
+ // Images and fonts the page or a stylesheet names by a relative path
545
+ // (`<img src="./logo.png">`, `url(./bg.png)`) are carried too, so the page
546
+ // comes back with them; a package's own files are not.
547
+ for (const sheet of carriedCss) {
548
+ const rel = path.relative(root, sheet);
549
+ if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
550
+ if (!files.includes(sheet)) files.push(sheet);
551
+ }
552
+ for (const asset of ctx.localAssets) {
553
+ const rel = path.relative(root, asset);
554
+ if (rel.startsWith('..') || path.isAbsolute(rel) || rel.split(path.sep).includes('node_modules')) continue;
555
+ if (files.includes(asset)) continue;
556
+ // Carried only when its bytes are a known image, font or media format,
557
+ // the same test --reverse applies, so the file always comes back.
558
+ if (!isAssetBytes(fs.readFileSync(asset))) {
559
+ warnings.push({
560
+ code: 'not-embedded',
561
+ 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.`,
562
+ });
563
+ continue;
564
+ }
565
+ files.push(asset);
566
+ }
567
+ // Paths are kept relative to the folder that holds every file: the page's
568
+ // folder, or an ancestor when the page imports from above it.
569
+ let base = dir;
570
+ for (const f of files) {
571
+ while (path.relative(base, f).startsWith('..')) base = path.dirname(base);
572
+ }
573
+ // Page first, so the reader knows which file is the page. Only files a
574
+ // rendered page may carry are embedded (see embedded-files.mjs).
575
+ const ordered = [entry, ...files.filter(f => f !== entry)];
576
+ /** @type {{path: string, bytes: Buffer}[]} */
577
+ const embedded = [];
578
+ for (const f of ordered) {
579
+ const rel = path.relative(base, f).split(path.sep).join('/');
580
+ if (f !== entry && embeddedPathProblem(rel)) {
581
+ warnings.push({
582
+ code: 'not-embedded',
583
+ message: `${rel} is not carried in the file (a rendered page carries the page and the local modules, stylesheets, JSON files and images it imports, but never project or tool configuration, or a file a test, story or benchmark runner would run), so --reverse cannot give it back.`,
584
+ });
585
+ continue;
586
+ }
587
+ embedded.push({path: rel, bytes: fs.readFileSync(f)});
588
+ }
589
+ const heading = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(markup)?.[1]?.replace(/<[^>]*>/g, '').trim();
590
+ const title = options.title ?? (heading ? decodeAttr(heading) : path.basename(entry).replace(/\.[^.]+$/, ''));
591
+ const html =
592
+ '<!doctype html><html lang="en"><head><meta charset="utf-8">' +
593
+ '<meta name="viewport" content="width=device-width,initial-scale=1">' +
594
+ '<meta name="color-scheme" content="light dark">' +
595
+ `<meta name="generator" content="Astryx${options.version ? ` ${escapeHtml(options.version)}` : ''}">` +
596
+ `<title>${escapeHtml(title)}</title>` +
597
+ `<style>${SCHEME_CSS}${css}</style></head><body>${markup}` +
598
+ `${sourceBlock(path.basename(entry), embedded)}</body></html>\n`;
599
+ return {
600
+ html,
601
+ files: embedded.map(f => f.path),
602
+ stylesheets: sheets,
603
+ classes: used.size,
604
+ cssBytes: Buffer.byteLength(css),
605
+ markupBytes: Buffer.byteLength(markup),
606
+ images: new Set([
607
+ ...[...ctx.counted].filter(k => k.startsWith('file:')).map(k => k.slice(5)),
608
+ ...(message.assets ?? []),
609
+ ]).size,
610
+ warnings,
611
+ };
612
+ }