@astryxdesign/cli 0.7.4 → 0.7.5-canary.0026f37

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 (235) hide show
  1. package/README.md +18 -18
  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/assets/codemods/transforms/v0.7.0/__tests__/validate-data-token-ownership.test.mjs +123 -70
  69. package/assets/codemods/transforms/v0.7.0/validate-data-token-ownership.mjs +19 -77
  70. package/assets/discover/official-packages.json +4 -0
  71. package/assets/docs/tree/icon-definitions.doc.mjs +2 -2
  72. package/assets/docs/tree/icon-set-files.doc.mjs +1 -1
  73. package/assets/docs/tree/icon-sets.doc.mjs +50 -20
  74. package/assets/docs/tree/render-pages.doc.mjs +94 -0
  75. package/assets/icons/definitions/activity.doc.mjs +1 -1
  76. package/assets/icons/definitions/alignCenter.doc.mjs +9 -0
  77. package/assets/icons/definitions/alignEnd.doc.mjs +10 -0
  78. package/assets/icons/definitions/alignStart.doc.mjs +10 -0
  79. package/assets/icons/definitions/archive.doc.mjs +1 -1
  80. package/assets/icons/definitions/arrowsUpDown.doc.mjs +1 -1
  81. package/assets/icons/definitions/attach.doc.mjs +1 -1
  82. package/assets/icons/definitions/audio.doc.mjs +1 -1
  83. package/assets/icons/definitions/cart.doc.mjs +1 -1
  84. package/assets/icons/definitions/checkDouble.doc.mjs +1 -1
  85. package/assets/icons/definitions/chevronsLeft.doc.mjs +1 -1
  86. package/assets/icons/definitions/chevronsRight.doc.mjs +1 -1
  87. package/assets/icons/definitions/close.doc.mjs +1 -1
  88. package/assets/icons/definitions/collapse.doc.mjs +1 -1
  89. package/assets/icons/definitions/compose.doc.mjs +1 -1
  90. package/assets/icons/definitions/conversation.doc.mjs +1 -1
  91. package/assets/icons/definitions/copy.doc.mjs +1 -1
  92. package/assets/icons/definitions/cpu.doc.mjs +9 -0
  93. package/assets/icons/definitions/database.doc.mjs +1 -1
  94. package/assets/icons/definitions/desktop.doc.mjs +1 -1
  95. package/assets/icons/definitions/discount.doc.mjs +1 -1
  96. package/assets/icons/definitions/download.doc.mjs +1 -1
  97. package/assets/icons/definitions/emoji.doc.mjs +1 -1
  98. package/assets/icons/definitions/error.doc.mjs +1 -1
  99. package/assets/icons/definitions/expand.doc.mjs +1 -1
  100. package/assets/icons/definitions/experiment.doc.mjs +1 -1
  101. package/assets/icons/definitions/externalLink.doc.mjs +7 -1
  102. package/assets/icons/definitions/eyeSlash.doc.mjs +1 -1
  103. package/assets/icons/definitions/flipHorizontal.doc.mjs +9 -0
  104. package/assets/icons/definitions/flipVertical.doc.mjs +9 -0
  105. package/assets/icons/definitions/folderAdd.doc.mjs +1 -1
  106. package/assets/icons/definitions/gitBranch.doc.mjs +9 -0
  107. package/assets/icons/definitions/gitFork.doc.mjs +9 -0
  108. package/assets/icons/definitions/info.doc.mjs +1 -1
  109. package/assets/icons/definitions/location.doc.mjs +1 -1
  110. package/assets/icons/definitions/mention.doc.mjs +1 -1
  111. package/assets/icons/definitions/menu.doc.mjs +1 -1
  112. package/assets/icons/definitions/microphone.doc.mjs +1 -1
  113. package/assets/icons/definitions/mobile.doc.mjs +1 -1
  114. package/assets/icons/definitions/money.doc.mjs +1 -1
  115. package/assets/icons/definitions/moreHorizontal.doc.mjs +1 -1
  116. package/assets/icons/definitions/notificationActive.doc.mjs +1 -1
  117. package/assets/icons/definitions/notificationOff.doc.mjs +1 -1
  118. package/assets/icons/definitions/panelLeft.doc.mjs +10 -0
  119. package/assets/icons/definitions/panelRight.doc.mjs +10 -0
  120. package/assets/icons/definitions/raiseHand.doc.mjs +1 -1
  121. package/assets/icons/definitions/redo.doc.mjs +1 -1
  122. package/assets/icons/definitions/refresh.doc.mjs +1 -1
  123. package/assets/icons/definitions/rotate.doc.mjs +9 -0
  124. package/assets/icons/definitions/scale.doc.mjs +10 -0
  125. package/assets/icons/definitions/search.doc.mjs +1 -1
  126. package/assets/icons/definitions/send.doc.mjs +1 -1
  127. package/assets/icons/definitions/settings.doc.mjs +1 -1
  128. package/assets/icons/definitions/star.doc.mjs +1 -1
  129. package/assets/icons/definitions/stop.doc.mjs +1 -1
  130. package/assets/icons/definitions/success.doc.mjs +1 -1
  131. package/assets/icons/definitions/textCase.doc.mjs +9 -0
  132. package/assets/icons/definitions/thumbsDown.doc.mjs +1 -1
  133. package/assets/icons/definitions/thumbsUp.doc.mjs +1 -1
  134. package/assets/icons/definitions/trendDown.doc.mjs +7 -1
  135. package/assets/icons/definitions/trendUp.doc.mjs +1 -1
  136. package/assets/icons/definitions/undo.doc.mjs +1 -1
  137. package/assets/icons/definitions/upload.doc.mjs +1 -1
  138. package/assets/icons/definitions/userAdd.doc.mjs +1 -1
  139. package/assets/icons/definitions/warning.doc.mjs +1 -1
  140. package/assets/templates/blocks/components/Tokenizer/TokenizerClear.tsx +15 -14
  141. package/assets/templates/blocks/components/Tokenizer/TokenizerCreatable.tsx +30 -30
  142. package/assets/templates/blocks/components/Tokenizer/TokenizerEndContent.tsx +15 -14
  143. package/assets/templates/blocks/components/Tokenizer/TokenizerIcon.tsx +15 -14
  144. package/assets/templates/blocks/components/Tokenizer/TokenizerMaxEntries.tsx +17 -16
  145. package/assets/templates/blocks/components/Tokenizer/TokenizerOverflow.tsx +29 -29
  146. package/assets/templates/blocks/components/Tokenizer/TokenizerShowcase.tsx +9 -8
  147. package/assets/templates/blocks/components/Tokenizer/TokenizerStates.tsx +39 -41
  148. package/assets/templates/pages/canvas-editor/template.doc.mjs +9 -0
  149. package/assets/templates/pages/form-wizard-inline/template.doc.mjs +6 -1
  150. package/assets/templates/pages/table-comparison/template.doc.mjs +1 -0
  151. package/assets/templates/pages/table-tree/template.doc.mjs +3 -0
  152. package/authoring/debug/parse.d.mts +2 -2
  153. package/authoring/doctypes/icon-definition/icon-definition.doc.mjs +4 -4
  154. package/authoring/doctypes/icon-set/icon-set-data.doc.mjs +6 -0
  155. package/authoring/doctypes/icon-set/parse.d.mts +1 -0
  156. package/authoring/doctypes/icon-set/parse.mjs +1 -0
  157. package/authoring/doctypes/icon-set/type.ts +5 -0
  158. package/authoring/doctypes/template/template.doc.mjs +1 -1
  159. package/authoring/doctypes/template/type.ts +2 -1
  160. package/clients/cli/commands/doctor.mjs +16 -17
  161. package/clients/cli/commands/experimental/icon.mjs +167 -35
  162. package/clients/cli/commands/experimental/index.mjs +2 -0
  163. package/clients/cli/commands/experimental/render.mjs +113 -0
  164. package/clients/cli/commands/experimental-icon-add.doc.mjs +14 -4
  165. package/clients/cli/commands/experimental-icon-map.doc.mjs +12 -2
  166. package/clients/cli/commands/experimental-icon-new-definition.doc.mjs +1 -1
  167. package/clients/cli/commands/experimental-icon-new-set.doc.mjs +28 -1
  168. package/clients/cli/commands/experimental-icon.doc.mjs +18 -2
  169. package/clients/cli/commands/experimental-render.doc.mjs +60 -0
  170. package/clients/cli/commands/experimental.doc.mjs +4 -2
  171. package/clients/cli/commands/icon-authoring.test.mjs +1823 -13
  172. package/clients/cli/commands/icon-options-wiring.test.mjs +158 -0
  173. package/clients/cli/commands/icon.test.mjs +1 -1
  174. package/clients/cli/commands/template.mjs +4 -1
  175. package/clients/cli/commands/text-json-parity.test.mjs +46 -0
  176. package/clients/cli/index.mjs +1 -0
  177. package/foundation/discovery/component-discovery.d.mts +2 -1
  178. package/foundation/discovery/component-discovery.export-names.test.mjs +41 -0
  179. package/foundation/discovery/component-discovery.mjs +13 -7
  180. package/foundation/discovery/icon-set-checks.d.mts +43 -9
  181. package/foundation/discovery/icon-set-checks.mjs +296 -21
  182. package/foundation/discovery/icon-set-checks.test.mjs +125 -12
  183. package/foundation/discovery/icon-set-writer.d.mts +192 -3
  184. package/foundation/discovery/icon-set-writer.mjs +608 -34
  185. package/foundation/discovery/icon-set-writer.test.mjs +26 -0
  186. package/foundation/discovery/module-exports.mjs +82 -25
  187. package/foundation/discovery/module-exports.test.mjs +38 -1
  188. package/foundation/discovery/package-exports.d.mts +13 -0
  189. package/foundation/discovery/package-exports.mjs +40 -1
  190. package/foundation/discovery/template-icons.d.mts +6 -0
  191. package/foundation/discovery/template-icons.mjs +98 -10
  192. package/foundation/discovery/template-icons.test.mjs +103 -0
  193. package/foundation/doc-compiler/doc-loads.test.mjs +20 -5
  194. package/foundation/doc-compiler/import.mjs +81 -8
  195. package/foundation/doc-compiler/read.d.mts +4 -3
  196. package/foundation/doc-compiler/read.mjs +15 -10
  197. package/foundation/doc-compiler/read.test.mjs +59 -1
  198. package/foundation/doc-compiler/tree.mjs +3 -1
  199. package/foundation/fs/module-loader.d.mts +3 -2
  200. package/foundation/fs/module-loader.mjs +3 -2
  201. package/foundation/fs/publish-file-eperm-mutation.test.mjs +2 -0
  202. package/foundation/fs/read-record.d.mts +27 -0
  203. package/foundation/fs/read-record.mjs +83 -15
  204. package/foundation/fs/read-record.test.mjs +88 -1
  205. package/foundation/render/assets.d.mts +31 -0
  206. package/foundation/render/assets.mjs +102 -0
  207. package/foundation/render/component-map.d.mts +52 -0
  208. package/foundation/render/component-map.mjs +141 -0
  209. package/foundation/render/css-cut.d.mts +29 -0
  210. package/foundation/render/css-cut.mjs +144 -0
  211. package/foundation/render/embedded-files.d.mts +28 -0
  212. package/foundation/render/embedded-files.mjs +108 -0
  213. package/foundation/render/embedded-imports.d.mts +61 -0
  214. package/foundation/render/embedded-imports.mjs +315 -0
  215. package/foundation/render/html-reader.d.mts +37 -0
  216. package/foundation/render/html-reader.mjs +121 -0
  217. package/foundation/render/page-worker.d.mts +7 -0
  218. package/foundation/render/page-worker.mjs +519 -0
  219. package/foundation/render/rebuild.d.mts +19 -0
  220. package/foundation/render/rebuild.mjs +269 -0
  221. package/foundation/render/render-page.d.mts +85 -0
  222. package/foundation/render/render-page.mjs +612 -0
  223. package/foundation/render/render.test.mjs +117 -0
  224. package/foundation/render/source-block.d.mts +52 -0
  225. package/foundation/render/source-block.mjs +106 -0
  226. package/foundation/response/error-codes.d.mts +10 -1
  227. package/foundation/response/error-codes.doc.mjs +56 -0
  228. package/foundation/response/error-codes.mjs +61 -0
  229. package/foundation/response/response-types.doc.mjs +38 -1
  230. package/foundation/text/string-utils.mjs +33 -0
  231. package/foundation/text/string-utils.test.mjs +17 -0
  232. package/foundation/text/suggest-order.d.mts +17 -3
  233. package/foundation/text/suggest-order.mjs +58 -13
  234. package/foundation/text/suggest-order.test.mjs +53 -0
  235. package/package.json +14 -9
@@ -0,0 +1,28 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Render a page module to one HTML file and write it.
6
+ * @param {{cwd: string, input: string, output: string, title?: string}} args absolute paths
7
+ * @returns {Promise<import('./render.type.mjs').RenderPageResponse['data']>}
8
+ */
9
+ export function renderToFile({ cwd, input, output, title }: {
10
+ cwd: string;
11
+ input: string;
12
+ output: string;
13
+ title?: string;
14
+ }): Promise<import("./render.type.mjs").RenderPageResponse["data"]>;
15
+ /**
16
+ * Turn a rendered HTML file back into a page module.
17
+ * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
18
+ * @returns {import('./render.type.mjs').RenderReverseResponse['data']}
19
+ */
20
+ export function reverseToFile({ cwd, input, output, overwrite }: {
21
+ cwd: string;
22
+ input: string;
23
+ output: string | undefined;
24
+ overwrite: boolean;
25
+ }): import("./render.type.mjs").RenderReverseResponse["data"];
26
+ import { PAGE_EXTENSIONS } from '../../foundation/render/render-page.mjs';
27
+ import { embeddedPathProblem } from '../../foundation/render/embedded-files.mjs';
28
+ export { PAGE_EXTENSIONS, embeddedPathProblem };
@@ -0,0 +1,540 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file The `render` subject's adapter: its only access to the environment.
5
+ * It reads the page or rendered file, runs the renderer, and writes results.
6
+ *
7
+ * @position api/render — adapter for api/render/render.mjs
8
+ */
9
+
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import {createRequire} from 'node:module';
13
+ import {AstryxError} from '../error.mjs';
14
+ import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
15
+ import {
16
+ PAGE_EXTENSIONS,
17
+ RenderError,
18
+ renderPage,
19
+ } from '../../foundation/render/render-page.mjs';
20
+ import {readSourceBlock} from '../../foundation/render/source-block.mjs';
21
+ import {embeddedPathProblem, runnerPicksUp} from '../../foundation/render/embedded-files.mjs';
22
+ import {isAssetBytes, isAssetPath} from '../../foundation/render/assets.mjs';
23
+ import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
24
+ import {reachableFiles, receivingAliases} from '../../foundation/render/embedded-imports.mjs';
25
+ import {isAstryxMarkup} from '../../foundation/render/html-reader.mjs';
26
+ import {rebuildPage} from '../../foundation/render/rebuild.mjs';
27
+ import {cliVersion} from '../../foundation/integrations/cli-peer-version.mjs';
28
+ import {assertWithin, PathSafetyError} from '../../foundation/fs/path-safety.mjs';
29
+
30
+ export {PAGE_EXTENSIONS, embeddedPathProblem};
31
+
32
+ /** @param {string} cwd @param {string} file */
33
+ const shown = (cwd, file) => {
34
+ const rel = path.relative(cwd, file);
35
+ return rel && !rel.startsWith('..') && !path.isAbsolute(rel)
36
+ ? rel.split(path.sep).join('/')
37
+ : file;
38
+ };
39
+
40
+ /**
41
+ * Read a file the caller named, or throw ERR_FILE_NOT_FOUND.
42
+ * @param {string} file absolute
43
+ * @param {string} cwd
44
+ * @returns {Buffer}
45
+ */
46
+ function readInput(file, cwd) {
47
+ try {
48
+ if (!fs.statSync(file).isFile()) throw new Error('not a file');
49
+ return fs.readFileSync(file);
50
+ } catch {
51
+ throw new AstryxError(
52
+ `${shown(cwd, file)} does not exist`,
53
+ [],
54
+ ERROR_CODES.ERR_FILE_NOT_FOUND,
55
+ );
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Whether @astryxdesign/core resolves from a folder (or the nearest existing
61
+ * folder above it).
62
+ * @param {string} dir
63
+ */
64
+ function resolvesCore(dir) {
65
+ let d = dir;
66
+ while (!fs.existsSync(d) && path.dirname(d) !== d) d = path.dirname(d);
67
+ try {
68
+ createRequire(path.join(d, 'noop.js')).resolve('@astryxdesign/core');
69
+ return true;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Refuse a write outside the current folder, symlinks followed (cli-surface
77
+ * INV10).
78
+ * @param {string} file absolute
79
+ * @param {string} cwd
80
+ * @param {string} what
81
+ * @returns {string}
82
+ */
83
+ function confined(file, cwd, what) {
84
+ try {
85
+ return assertWithin(file, cwd, {allowAbsolute: true, label: what});
86
+ } catch (e) {
87
+ if (e instanceof PathSafetyError) {
88
+ throw new AstryxError(
89
+ `${what} ${shown(cwd, file)} is outside the current folder; nothing was written. Write inside the folder you run the command from.`,
90
+ [],
91
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
92
+ );
93
+ }
94
+ throw e;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Refuse, before anything is written, a write that reaches through a
100
+ * symbolic link, and the replacement of an existing file the project
101
+ * protects (generated, vendored, ignored, a dependency or version-control
102
+ * metadata; spec:AST-040 FR2), even with --overwrite.
103
+ * @param {string[]} files absolute
104
+ * @param {string} cwd
105
+ */
106
+ function refuseProtected(files, cwd) {
107
+ for (const file of files) {
108
+ let current = cwd;
109
+ for (const part of path.relative(cwd, file).split(path.sep)) {
110
+ current = path.join(current, part);
111
+ let stat;
112
+ try {
113
+ stat = fs.lstatSync(current);
114
+ } catch {
115
+ break;
116
+ }
117
+ if (stat.isSymbolicLink()) {
118
+ throw new AstryxError(
119
+ `${shown(cwd, file)} is reached through a symbolic link (${shown(cwd, current)}); nothing was written.`,
120
+ [],
121
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
122
+ );
123
+ }
124
+ }
125
+ }
126
+ const existing = files.filter(file => fs.existsSync(file));
127
+ if (existing.length === 0) return;
128
+ /** @type {ReturnType<typeof createFileProtectionResolver>} */
129
+ let resolver;
130
+ try {
131
+ resolver = createFileProtectionResolver(cwd);
132
+ } catch (e) {
133
+ throw new AstryxError(
134
+ `Could not read this project's file protection (${e instanceof Error ? e.message : String(e)}), so no existing file is replaced; nothing was written.`,
135
+ [],
136
+ ERROR_CODES.ERR_FILE_EXISTS,
137
+ );
138
+ }
139
+ const blocked = existing.flatMap(file => {
140
+ const protection = resolver.classify(file)[0];
141
+ return protection ? [`${shown(cwd, file)} (${protection.declaration})`] : [];
142
+ });
143
+ if (blocked.length > 0) {
144
+ throw new AstryxError(
145
+ `${blocked.join(', ')} ${blocked.length === 1 ? 'is' : 'are'} protected, so never replaced, even with --overwrite; nothing was written. Choose another --out.`,
146
+ [],
147
+ ERROR_CODES.ERR_FILE_EXISTS,
148
+ );
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Write several files all or nothing: each goes to a temporary file beside
154
+ * its target first, and only when every one is written are they moved into
155
+ * place. On a failure, the temporary files and the folders this made are
156
+ * removed, so nothing is left behind.
157
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets
158
+ * @param {string} cwd
159
+ */
160
+ function writeAll(writes, cwd) {
161
+ /** @type {string[]} */
162
+ const madeDirs = [];
163
+ /** @type {{temp: string, file: string}[]} */
164
+ const staged = [];
165
+ const undo = () => {
166
+ for (const {temp} of staged) fs.rmSync(temp, {force: true});
167
+ for (const dir of madeDirs.reverse()) {
168
+ try {
169
+ fs.rmdirSync(dir);
170
+ } catch {
171
+ // Not empty or already gone: leave it.
172
+ }
173
+ }
174
+ };
175
+ let current = '';
176
+ try {
177
+ for (const w of writes) {
178
+ current = w.file;
179
+ /** @type {string[]} */
180
+ const missing = [];
181
+ for (let d = path.dirname(w.file); !fs.existsSync(d); d = path.dirname(d)) missing.unshift(d);
182
+ for (const d of missing) {
183
+ fs.mkdirSync(d);
184
+ madeDirs.push(d);
185
+ }
186
+ const temp = `${w.file}.astryx-${process.pid}.tmp`;
187
+ fs.writeFileSync(temp, w.bytes, {flag: 'wx'});
188
+ staged.push({temp, file: w.file});
189
+ }
190
+ for (const {temp, file} of staged) {
191
+ current = file;
192
+ fs.renameSync(temp, file);
193
+ }
194
+ } catch (e) {
195
+ undo();
196
+ throw new AstryxError(
197
+ `Could not write ${shown(cwd, current)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
198
+ [],
199
+ ERROR_CODES.ERR_WRITE_FAILED,
200
+ );
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Write one file, creating its folder.
206
+ * @param {string} file absolute
207
+ * @param {string | Buffer} content
208
+ * @param {string} cwd
209
+ */
210
+ function writeOutput(file, content, cwd) {
211
+ try {
212
+ fs.mkdirSync(path.dirname(file), {recursive: true});
213
+ fs.writeFileSync(file, content);
214
+ } catch (e) {
215
+ throw new AstryxError(
216
+ `Could not write ${shown(cwd, file)}: ${/** @type {Error} */ (e).message}`,
217
+ [],
218
+ ERROR_CODES.ERR_WRITE_FAILED,
219
+ );
220
+ }
221
+ }
222
+
223
+ /** @param {unknown} e */
224
+ function asAstryxError(e) {
225
+ if (e instanceof RenderError) {
226
+ const code = /** @type {import('../../foundation/response/error-codes.mjs').ErrorCode} */ (e.code);
227
+ /** @type {{name: string, reason: string}[]} */
228
+ const suggestions = [];
229
+ if (e.code === 'ERR_RENDER_MISSING_DEPENDENCY' && typeof e.detail?.package === 'string') {
230
+ suggestions.push({name: `npm install ${e.detail.package}`, reason: 'install the package the page imports'});
231
+ }
232
+ return new AstryxError(e.message, suggestions, code);
233
+ }
234
+ const err = /** @type {any} */ (e);
235
+ if (typeof err?.code === 'string' && err.code.startsWith('ERR_RENDER_')) {
236
+ return new AstryxError(err.message, [], err.code);
237
+ }
238
+ return e;
239
+ }
240
+
241
+ /**
242
+ * Render a page module to one HTML file and write it.
243
+ * @param {{cwd: string, input: string, output: string, title?: string}} args absolute paths
244
+ * @returns {Promise<import('./render.type.mjs').RenderPageResponse['data']>}
245
+ */
246
+ export async function renderToFile({cwd, input, output, title}) {
247
+ readInput(input, cwd);
248
+ confined(output, cwd, 'The output');
249
+ /** @type {import('../../foundation/render/render-page.mjs').RenderedPage} */
250
+ let page;
251
+ try {
252
+ page = await renderPage(input, {title, version: cliVersion()});
253
+ } catch (e) {
254
+ throw asAstryxError(e);
255
+ }
256
+ refuseProtected([output], cwd);
257
+ // An existing file is replaced only when a render wrote it.
258
+ if (
259
+ fs.existsSync(output) &&
260
+ fs.statSync(output).isFile() &&
261
+ !/<meta name="generator" content="Astryx[ "]/.test(fs.readFileSync(output, 'utf8').slice(0, 4096))
262
+ ) {
263
+ throw new AstryxError(
264
+ `${shown(cwd, output)} already exists and was not written by a render, so it is not replaced; nothing was written. Choose another --out.`,
265
+ [],
266
+ ERROR_CODES.ERR_FILE_EXISTS,
267
+ );
268
+ }
269
+ writeOutput(output, page.html, cwd);
270
+ return {
271
+ input: shown(cwd, input),
272
+ output: shown(cwd, output),
273
+ bytes: Buffer.byteLength(page.html),
274
+ files: page.files,
275
+ stylesheets: page.stylesheets,
276
+ classes: page.classes,
277
+ cssBytes: page.cssBytes,
278
+ images: page.images,
279
+ warnings: page.warnings,
280
+ };
281
+ }
282
+
283
+ /**
284
+ * Refuse files a test, story or benchmark runner would run where they land,
285
+ * judged from the repository root (every folder above the file up to it),
286
+ * else the topmost folder with a package.json, else the current folder.
287
+ * @param {string[]} files absolute
288
+ * @param {string} cwd
289
+ * @param {string} input
290
+ */
291
+ function refuseRunnable(files, cwd, input) {
292
+ /** @param {string} marker */
293
+ const nearest = marker => {
294
+ for (let d = cwd; ; d = path.dirname(d)) {
295
+ if (fs.existsSync(path.join(d, marker))) return d;
296
+ if (path.dirname(d) === d) return null;
297
+ }
298
+ };
299
+ let topPackage = null;
300
+ for (let d = cwd; ; d = path.dirname(d)) {
301
+ if (fs.existsSync(path.join(d, 'package.json'))) topPackage = d;
302
+ if (path.dirname(d) === d) break;
303
+ }
304
+ const projectRoot = nearest('.git') ?? topPackage ?? cwd;
305
+ const runnable = files
306
+ .map(file => path.relative(projectRoot, file).split(path.sep))
307
+ .filter(segments => runnerPicksUp(segments))
308
+ .map(segments => segments.join('/'));
309
+ if (runnable.length > 0) {
310
+ throw new AstryxError(
311
+ `${shown(cwd, input)} would write ${runnable.join(', ')} (from the project root), where a test, story or benchmark runner would run it; nothing was written. Restore it somewhere else with --out.`,
312
+ [],
313
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
314
+ );
315
+ }
316
+ }
317
+
318
+ /**
319
+ * The new folder a restore without --out writes into: beside the HTML file,
320
+ * named after it (`report.html` gives `report-restored/`, then
321
+ * `report-restored-2/` when that exists).
322
+ * @param {string} input absolute
323
+ */
324
+ function restoreFolder(input) {
325
+ const stem = path.basename(input).replace(/\.[^.]+$/, '');
326
+ let folder = path.join(path.dirname(input), `${stem}-restored`);
327
+ for (let n = 2; fs.existsSync(folder); n++) folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
328
+ return folder;
329
+ }
330
+
331
+ /**
332
+ * Turn a rendered HTML file back into a page module.
333
+ * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
334
+ * @returns {import('./render.type.mjs').RenderReverseResponse['data']}
335
+ */
336
+ export function reverseToFile({cwd, input, output, overwrite}) {
337
+ const html = readInput(input, cwd).toString('utf8');
338
+ const block = readSourceBlock(html);
339
+ /** @param {string[]} files */
340
+ const refuseExisting = files => {
341
+ if (overwrite) return;
342
+ const existing = files.filter(file => fs.existsSync(file));
343
+ if (existing.length > 0) {
344
+ throw new AstryxError(
345
+ `${existing.map(file => shown(cwd, file)).join(', ')} already exist${existing.length === 1 ? 's' : ''}; nothing was written. Pass --overwrite to replace ${existing.length === 1 ? 'it' : 'them'}.`,
346
+ [],
347
+ ERROR_CODES.ERR_FILE_EXISTS,
348
+ );
349
+ }
350
+ };
351
+ /** A page is never written as a configuration, test, spec or story file. @param {string} file */
352
+ const refuseConfigTarget = file => {
353
+ const rel = path.relative(cwd, file).split(path.sep).join('/');
354
+ const where = rel.startsWith('..') || path.isAbsolute(rel) ? path.basename(file) : rel;
355
+ // Where the page lands must be a page module, and a name no tool takes
356
+ // as its own (configuration, a runner's file): the same rules as any
357
+ // file a restore writes.
358
+ const problem = embeddedPathProblem(where, {page: true}) ?? embeddedPathProblem(where);
359
+ if (problem) {
360
+ throw new AstryxError(
361
+ `${shown(cwd, file)} is not a page module file name a reverse writes (${problem.reason}); nothing was written.`,
362
+ [],
363
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
364
+ );
365
+ }
366
+ };
367
+ if (block.found && 'damaged' in block) {
368
+ throw new AstryxError(
369
+ `${shown(cwd, input)} carries an Astryx page source, but ${block.damaged}, so it cannot be given back exactly.`,
370
+ [],
371
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
372
+ );
373
+ }
374
+ if (block.found) {
375
+ const {source} = block;
376
+ // A file someone sends is untrusted: it may carry only what a render
377
+ // embeds (the page, and the stylesheets, JSON and images it imports).
378
+ source.files.forEach((f, i) => {
379
+ const problem = embeddedPathProblem(f.path, {page: i === 0});
380
+ if (problem) {
381
+ throw new AstryxError(
382
+ `${shown(cwd, input)} carries ${problem.reason}, which a render never embeds; nothing was written.`,
383
+ [],
384
+ ERROR_CODES[problem.code],
385
+ );
386
+ }
387
+ });
388
+ // Without --out, the page and the files it imports come back into a new
389
+ // folder beside the HTML file, named after it (`report.html` gives
390
+ // `report-restored/`), with the layout they were rendered in. Nothing in
391
+ // the received file decides where in your project anything goes.
392
+ const requested = output ?? path.join(restoreFolder(input), ...source.files[0].path.split('/'));
393
+ refuseConfigTarget(requested);
394
+ const seen = new Set();
395
+ for (const f of source.files) {
396
+ const key = f.path.toLowerCase();
397
+ if (seen.has(key)) {
398
+ throw new AstryxError(
399
+ `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
400
+ [],
401
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
402
+ );
403
+ }
404
+ seen.add(key);
405
+ }
406
+ // Modules, stylesheets and JSON are written only when the page reaches
407
+ // them through its own imports: one it never imports is not part of it,
408
+ // whatever its name.
409
+ const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(path.dirname(requested))});
410
+ // A carried image, font or media file needs no import to be part of the
411
+ // page (it may be named in markup, a stylesheet, JSON or a computed
412
+ // path): the render's own list is the authority, so it is kept when its
413
+ // bytes are a known image, font or media format (any, whatever the
414
+ // extension), and goes where the layout puts it.
415
+ for (const f of source.files) {
416
+ if (reached.has(f.path) || !isAssetPath(f.path)) continue;
417
+ if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
418
+ }
419
+ const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
420
+ if (stray.length > 0) {
421
+ throw new AstryxError(
422
+ `${shown(cwd, input)} carries ${stray.length === 1 ? 'a file' : 'files'} the page does not import, or that is not the image, font or media file its name says (${stray.join(', ')}), which a render never embeds; nothing was written. A file reached through a path alias needs the same alias in this project's tsconfig.json or jsconfig.json.`,
423
+ [],
424
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
425
+ );
426
+ }
427
+ // Each file the page reaches by a relative import goes where that import
428
+ // finds it from the page's new folder, so every relative import still
429
+ // resolves wherever the page lands; a file reached through an alias goes
430
+ // where this project's alias points. Every file but the page must land
431
+ // in a folder this restore creates: a received file never adds a file to
432
+ // a folder that already exists (a server hook at the project root, a
433
+ // middleware module), so a page with neighbours comes back into a new
434
+ // folder.
435
+ const entryDir = path.posix.dirname(source.files[0].path);
436
+ const anchor = path.dirname(requested);
437
+ /** @param {string} p */
438
+ const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
439
+ // A file beside the page or elsewhere goes only into a folder this
440
+ // restore creates: never into a folder that already exists.
441
+ // The one folder every file but the page must land in: the topmost
442
+ // folder on the page's path that this restore creates. When the page's
443
+ // folder already exists there is none, so a page with neighbours comes
444
+ // back only into a new folder.
445
+ /** @type {string | null} */
446
+ let home = null;
447
+ for (let d = anchor; !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) home = d;
448
+ const within = (/** @type {string} */ file) => {
449
+ if (!home) return false;
450
+ const rel = path.relative(home, file);
451
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
452
+ };
453
+ const target = path.join(anchor, path.basename(requested));
454
+ /** @type {{file: string, bytes: Buffer}[]} */
455
+ const writes = [];
456
+ const placed = new Set();
457
+ /** @type {string[]} */
458
+ const outside = [];
459
+ /** @type {string[]} */
460
+ const aliasedOutside = [];
461
+ source.files.forEach((f, i) => {
462
+ const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
463
+ const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
464
+ for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
465
+ if (placed.has(file)) continue;
466
+ placed.add(file);
467
+ if (i > 0 && !within(file)) (aliased ? aliasedOutside : outside).push(file);
468
+ writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
469
+ }
470
+ });
471
+ if (aliasedOutside.length > 0) {
472
+ throw new AstryxError(
473
+ `${shown(cwd, input)} imports ${aliasedOutside.map(file => shown(cwd, file)).join(', ')} through a path alias that points outside the folder the restore creates; nothing was written. A received page never adds files to your existing folders: change those imports to relative ones before rendering, or restore it in a project whose alias points somewhere new.`,
474
+ [],
475
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
476
+ );
477
+ }
478
+ if (outside.length > 0) {
479
+ const top = entryDir === '.' ? '' : `${entryDir}/`;
480
+ let fresh = 'restored';
481
+ for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
482
+ const suggestion = `--out ${fresh}/${top}${path.basename(requested)}`;
483
+ throw new AstryxError(
484
+ `${shown(cwd, input)} would add ${outside.map(file => shown(cwd, file)).join(', ')} outside the folder the restore creates; nothing was written. A received page writes the files it imports only inside one new folder: restore it into one, such as ${suggestion}.`,
485
+ [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
486
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
487
+ );
488
+ }
489
+ writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
490
+ refuseRunnable(writes.map(w => w.file), cwd, input);
491
+ refuseExisting(writes.map(w => w.file));
492
+ refuseProtected(writes.map(w => w.file), cwd);
493
+ writeAll(writes, cwd);
494
+ return {
495
+ input: shown(cwd, input),
496
+ mode: 'embedded',
497
+ output: shown(cwd, target),
498
+ files: writes.map(w => shown(cwd, w.file)),
499
+ // The page is byte for byte the one rendered; an import it makes that
500
+ // the file does not carry (a file a render never embeds) is named.
501
+ exact: missing.length === 0,
502
+ ...(missing.length > 0 ? {missing} : {}),
503
+ };
504
+ }
505
+ if (!isAstryxMarkup(html)) {
506
+ throw new AstryxError(
507
+ `${shown(cwd, input)} is not an Astryx page: it has no embedded source and no Astryx components to rebuild from. To start an Astryx page like it, run astryx build "<what the page is>".`,
508
+ [
509
+ {
510
+ name: 'astryx build "<what the page is>"',
511
+ reason: 'start an Astryx page from a description of it instead',
512
+ },
513
+ ],
514
+ ERROR_CODES.ERR_RENDER_NOT_ASTRYX,
515
+ );
516
+ }
517
+ const target = output ?? path.join(restoreFolder(input), 'page.tsx');
518
+ refuseConfigTarget(target);
519
+ confined(target, cwd, 'The page');
520
+ refuseRunnable([target], cwd, input);
521
+ refuseExisting([target]);
522
+ // Components resolve from where the page will live, then from the HTML
523
+ // file's folder, then from the current folder.
524
+ const from =
525
+ [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
526
+ const rebuilt = rebuildPage(html, from);
527
+ refuseProtected([target], cwd);
528
+ writeOutput(target, rebuilt.source, cwd);
529
+ return {
530
+ input: shown(cwd, input),
531
+ mode: 'rebuilt',
532
+ output: shown(cwd, target),
533
+ files: [shown(cwd, target)],
534
+ exact: false,
535
+ components: rebuilt.components,
536
+ elements: rebuilt.elements,
537
+ unknown: rebuilt.unknown,
538
+ omitted: rebuilt.omitted,
539
+ };
540
+ }
@@ -0,0 +1,15 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * Render a page module to one self-contained HTML file, or turn a rendered
6
+ * file back into a page module.
7
+ *
8
+ * Experimental (spec:AST-017 FR27): may change or be removed in a patch
9
+ * release.
10
+ * @experimental
11
+ * @param {string} file the page module, or with `reverse` the HTML file
12
+ * @param {import('./render.type.mjs').RenderOptions} [options]
13
+ * @returns {Promise<import('./render.type.mjs').RenderPageResponse | import('./render.type.mjs').RenderReverseResponse>}
14
+ */
15
+ export function render(file: string, options?: import("./render.type.mjs").RenderOptions): Promise<import("./render.type.mjs").RenderPageResponse | import("./render.type.mjs").RenderReverseResponse>;
@@ -0,0 +1,9 @@
1
+ // @generated by scripts/sync-api-types.mjs from the JSDoc in api/**/*.mjs.
2
+ // DO NOT EDIT — run `pnpm sync:api-types` to regenerate.
3
+
4
+ /**
5
+ * @file FunctionDoc for `render()` / `astryx experimental render`.
6
+ * @position packages/cli/api/render — function documentation
7
+ */
8
+ /** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
9
+ export const doc: import("@astryxdesign/cli/authoring").FunctionDoc;