@astryxdesign/cli 0.7.16 → 0.7.17-canary.g9a957aa

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/README.md +12 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +47 -9
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +32 -0
  14. package/api/build/kit/words.mjs +49 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +48 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +491 -186
  34. package/api/render/render.doc.mjs +10 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +38 -0
  46. package/api/theme/build/build.mjs +144 -24
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +35 -0
  50. package/api/theme-edit/_adapter.mjs +477 -41
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1077 -200
  53. package/api/theme-edit/_compiler.mjs +9 -0
  54. package/api/theme-edit/_context.mjs +60 -3
  55. package/api/theme-edit/_css.mjs +21 -1
  56. package/api/theme-edit/_edit.d.mts +22 -0
  57. package/api/theme-edit/_edit.mjs +932 -82
  58. package/api/theme-edit/_how-commands.d.mts +49 -0
  59. package/api/theme-edit/_how-commands.mjs +386 -1
  60. package/api/theme-edit/_how-question.d.mts +56 -0
  61. package/api/theme-edit/_how-question.mjs +3509 -168
  62. package/api/theme-edit/_how.mjs +104 -4
  63. package/api/theme-edit/_marks.d.mts +31 -5
  64. package/api/theme-edit/_marks.mjs +57 -5
  65. package/api/theme-edit/_normal.d.mts +137 -0
  66. package/api/theme-edit/_normal.mjs +612 -0
  67. package/api/theme-edit/_palette.mjs +10 -4
  68. package/api/theme-edit/_parts.d.mts +4 -0
  69. package/api/theme-edit/_parts.mjs +28 -2
  70. package/api/theme-edit/_preview-app.d.mts +7 -1
  71. package/api/theme-edit/_preview-app.mjs +191 -15
  72. package/api/theme-edit/_preview.d.mts +64 -8
  73. package/api/theme-edit/_preview.mjs +401 -83
  74. package/api/theme-edit/_settings.d.mts +139 -5
  75. package/api/theme-edit/_settings.mjs +1659 -112
  76. package/api/theme-edit/_tables.mjs +17 -1
  77. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  78. package/api/theme-edit/theme-edit.type.mjs +4 -1
  79. package/api/theme-edit/themeEditPreviewApp.doc.mjs +2 -2
  80. package/assets/codemods/run-codemod.mjs +73 -6
  81. package/assets/codemods/transforms/next/index.mjs +11 -1
  82. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  83. package/assets/docs/author-a-theme.doc.mjs +1 -0
  84. package/assets/docs/theme.doc.dense.mjs +2 -2
  85. package/assets/docs/theme.doc.mjs +1 -1
  86. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  87. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  88. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  89. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  90. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  91. package/assets/docs/use-a-theme.doc.mjs +1 -1
  92. package/assets/docs.generated.json +2 -2
  93. package/assets/self-audit.generated.json +1 -1
  94. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  95. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  96. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  97. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  98. package/assets/templates/components.generated.json +1 -1
  99. package/assets/templates/pages/ai-chat/template.doc.mjs +8 -4
  100. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  101. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  102. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  103. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  104. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  105. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  106. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  107. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  108. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  110. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  111. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  112. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  113. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  114. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  115. package/assets/templates/pages/editor/template.doc.mjs +1 -7
  116. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  117. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  118. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  119. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  120. package/assets/templates/pages/ide/page.tsx +24 -2
  121. package/assets/templates/pages/library/template.doc.mjs +4 -1
  122. package/assets/templates/pages/login/template.doc.mjs +2 -1
  123. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  124. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  125. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  126. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  127. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  128. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  129. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  130. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  131. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  132. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  133. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  134. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  135. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  136. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  137. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  138. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  139. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -1
  140. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  141. package/authoring/debug/parse.d.mts +3 -3
  142. package/authoring/doctypes/_schema.d.mts +3 -3
  143. package/authoring/doctypes/command/command.doc.mjs +1 -1
  144. package/authoring/doctypes/template/template.doc.mjs +1 -1
  145. package/authoring/doctypes/template/type.ts +9 -0
  146. package/clients/cli/bin/astryx.mjs +6 -9
  147. package/clients/cli/build-id.generated.json +1 -1
  148. package/clients/cli/commands/component.doc.mjs +1 -1
  149. package/clients/cli/commands/component.mjs +20 -2
  150. package/clients/cli/commands/docs.doc.mjs +7 -1
  151. package/clients/cli/commands/docs.mjs +3 -1
  152. package/clients/cli/commands/doctor.mjs +22 -14
  153. package/clients/cli/commands/experimental/render.mjs +32 -1
  154. package/clients/cli/commands/experimental/theme.mjs +27 -2
  155. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  156. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  157. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  158. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  159. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  160. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  161. package/clients/cli/commands/search.doc.mjs +2 -1
  162. package/clients/cli/commands/search.mjs +6 -1
  163. package/clients/cli/commands/template.mjs +4 -2
  164. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  165. package/clients/cli/commands/theme.doc.mjs +1 -1
  166. package/clients/cli/commands/theme.mjs +138 -3
  167. package/clients/cli/commands/upgrade.mjs +42 -7
  168. package/clients/cli/index.mjs +1 -1
  169. package/clients/cli/lib/component-format.mjs +205 -98
  170. package/clients/cli/lib/hook-format.mjs +9 -19
  171. package/clients/cli/manifest.generated.json +1 -1
  172. package/foundation/agent-docs/agent-docs.mjs +1 -1
  173. package/foundation/config/theme-state.d.mts +13 -1
  174. package/foundation/config/theme-state.mjs +47 -7
  175. package/foundation/discovery/component-discovery.d.mts +11 -0
  176. package/foundation/discovery/component-discovery.mjs +27 -2
  177. package/foundation/discovery/component-replacement.mjs +130 -1
  178. package/foundation/discovery/entry-name-files.d.mts +43 -0
  179. package/foundation/discovery/entry-name-files.mjs +264 -0
  180. package/foundation/discovery/hook-discovery.d.mts +8 -2
  181. package/foundation/discovery/hook-discovery.mjs +20 -7
  182. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  183. package/foundation/discovery/runner-allowlist.mjs +2 -0
  184. package/foundation/discovery/template-adapter.d.mts +52 -0
  185. package/foundation/discovery/template-adapter.mjs +169 -0
  186. package/foundation/discovery/theme-imports.d.mts +14 -0
  187. package/foundation/discovery/theme-imports.mjs +43 -1
  188. package/foundation/doc-compiler/import.mjs +7 -1
  189. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  190. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  191. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  192. package/foundation/fs/cache-eviction.d.mts +21 -0
  193. package/foundation/fs/cache-eviction.mjs +73 -0
  194. package/foundation/fs/gather-cache.d.mts +25 -4
  195. package/foundation/fs/gather-cache.mjs +138 -52
  196. package/foundation/fs/jiti-cache.d.mts +19 -1
  197. package/foundation/fs/jiti-cache.mjs +130 -6
  198. package/foundation/fs/kept-tree.d.mts +60 -0
  199. package/foundation/fs/kept-tree.mjs +154 -0
  200. package/foundation/fs/module-loader.d.mts +18 -2
  201. package/foundation/fs/module-loader.mjs +92 -20
  202. package/foundation/identity/provider-identity.d.mts +6 -0
  203. package/foundation/identity/provider-identity.mjs +10 -1
  204. package/foundation/render/file-header.d.mts +66 -0
  205. package/foundation/render/file-header.mjs +118 -0
  206. package/foundation/render/host-answer.d.mts +18 -0
  207. package/foundation/render/host-answer.mjs +46 -0
  208. package/foundation/render/host-exit.d.mts +1 -0
  209. package/foundation/render/host-exit.mjs +6 -1
  210. package/foundation/render/html-reader.d.mts +55 -2
  211. package/foundation/render/html-reader.mjs +145 -26
  212. package/foundation/render/markup-edits.d.mts +57 -0
  213. package/foundation/render/markup-edits.mjs +182 -0
  214. package/foundation/render/page-host.mjs +29 -12
  215. package/foundation/render/page-worker.mjs +79 -10
  216. package/foundation/render/render-page.d.mts +34 -2
  217. package/foundation/render/render-page.mjs +210 -29
  218. package/foundation/render/source-block.d.mts +73 -6
  219. package/foundation/render/source-block.mjs +170 -19
  220. package/foundation/render/ts-paths.d.mts +4 -1
  221. package/foundation/render/ts-paths.mjs +7 -3
  222. package/foundation/response/error-codes.d.mts +2 -1
  223. package/foundation/response/error-codes.doc.mjs +7 -1
  224. package/foundation/response/error-codes.mjs +7 -0
  225. package/foundation/text/string-utils.d.mts +3 -2
  226. package/foundation/text/string-utils.mjs +16 -3
  227. package/foundation/text/suggest-order.d.mts +9 -0
  228. package/foundation/text/suggest-order.mjs +13 -0
  229. package/package.json +6 -6
@@ -8,7 +8,9 @@
8
8
  */
9
9
 
10
10
  import * as fs from 'node:fs';
11
+ import * as os from 'node:os';
11
12
  import * as path from 'node:path';
13
+ import {randomUUID} from 'node:crypto';
12
14
  import {createRequire} from 'node:module';
13
15
  import {AstryxError} from '../error.mjs';
14
16
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -17,10 +19,25 @@ import {
17
19
  RenderError,
18
20
  renderPage,
19
21
  } from '../../foundation/render/render-page.mjs';
20
- import {readSourceBlock} from '../../foundation/render/source-block.mjs';
22
+ import {
23
+ RENDER_FORMAT,
24
+ asParsed,
25
+ readSourceBlock,
26
+ recordedText,
27
+ renderedHeadOf,
28
+ renderedMarkupOf,
29
+ sha256,
30
+ } from '../../foundation/render/source-block.mjs';
31
+ import {decode} from '../../foundation/render/html-reader.mjs';
32
+ import {clip, locate, textEdits, textRuns} from '../../foundation/render/markup-edits.mjs';
33
+ import {isPackageName} from '../../foundation/identity/provider-identity.mjs';
34
+ import {cliCommand} from '../../foundation/render/file-header.mjs';
35
+ import {shellArg} from '../../foundation/text/shell-arg.mjs';
36
+ import {isValidSemver} from '../../foundation/env/semver.mjs';
21
37
  import {embeddedPathProblem, runnerPicksUp} from '../../foundation/render/embedded-files.mjs';
22
38
  import {isAssetBytes, isAssetPath} from '../../foundation/render/assets.mjs';
23
39
  import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
40
+ import {publishNewFile} from '../../foundation/fs/publish-file.mjs';
24
41
  import {reachableFiles, receivingAliases} from '../../foundation/render/embedded-imports.mjs';
25
42
  import {isAstryxMarkup} from '../../foundation/render/html-reader.mjs';
26
43
  import {rebuildPage} from '../../foundation/render/rebuild.mjs';
@@ -28,6 +45,7 @@ import {cliVersion} from '../../foundation/integrations/cli-peer-version.mjs';
28
45
  import {assertWithin, PathSafetyError} from '../../foundation/fs/path-safety.mjs';
29
46
  import {requireCoreDir} from '../../foundation/fs/paths.mjs';
30
47
  import {runChoice} from '../../foundation/release/run-context.mjs';
48
+ import {isAlive, pidSpace} from '../../foundation/release/cache.mjs';
31
49
  import {isServedPackage} from '../../foundation/render/served-packages.mjs';
32
50
  import {hostedRun, recordResolved} from '../../foundation/runtime/package-root.mjs';
33
51
 
@@ -99,15 +117,29 @@ function confined(file, cwd, what) {
99
117
  }
100
118
  }
101
119
 
120
+ /**
121
+ * Whether a file is inside a folder (not the folder itself).
122
+ * @param {string} file absolute
123
+ * @param {string | null} folder absolute
124
+ */
125
+ const isInside = (file, folder) => {
126
+ if (!folder) return false;
127
+ const rel = path.relative(folder, file);
128
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
129
+ };
130
+
102
131
  /**
103
132
  * Refuse, before anything is written, a write that reaches through a
104
133
  * symbolic link, and the replacement of an existing file the project
105
134
  * protects (generated, vendored, ignored, a dependency or version-control
106
- * metadata; spec:AST-040 FR2), even with --overwrite.
135
+ * metadata; spec:AST-040 FR2), even with --overwrite. A file inside the new
136
+ * folder a restore creates replaces nothing: that folder takes its name in
137
+ * one step, after every check.
107
138
  * @param {string[]} files absolute
108
139
  * @param {string} cwd
140
+ * @param {string | null} [newFolder] the new folder a restore creates, if any
109
141
  */
110
- function refuseProtected(files, cwd) {
142
+ function refuseProtected(files, cwd, newFolder = null) {
111
143
  for (const file of files) {
112
144
  let current = cwd;
113
145
  for (const part of path.relative(cwd, file).split(path.sep)) {
@@ -127,7 +159,7 @@ function refuseProtected(files, cwd) {
127
159
  }
128
160
  }
129
161
  }
130
- const existing = files.filter(file => fs.existsSync(file));
162
+ const existing = files.filter(file => !isInside(file, newFolder) && fs.existsSync(file));
131
163
  if (existing.length === 0) return;
132
164
  /** @type {ReturnType<typeof createFileProtectionResolver>} */
133
165
  let resolver;
@@ -154,76 +186,204 @@ function refuseProtected(files, cwd) {
154
186
  }
155
187
 
156
188
  /**
157
- * Write several files all or nothing: each goes to a temporary file beside
158
- * its target first, and only when every one is written are they moved into
159
- * place. On a failure, the temporary files and the folders this made are
160
- * removed, so nothing is left behind.
161
- * @param {{file: string, bytes: Buffer}[]} writes absolute targets
189
+ * The process space runs here share: this computer's name and its process-ID
190
+ * namespace (a container or sandbox on one computer has its own), in which a
191
+ * process id names one process.
192
+ */
193
+ const PROCESS_SPACE = `${os.hostname()}-${/\[(\d+)\]/.exec(pidSpace() ?? '')?.[1] ?? 'x'}`;
194
+
195
+ /**
196
+ * The start of the hidden temporary names a run in this process space gives
197
+ * a file or folder beside its target, before the run's process id.
198
+ * @param {string} target absolute
199
+ */
200
+ const temporaryPrefix = target => `.${path.basename(target)}.tmp-${PROCESS_SPACE}-`;
201
+
202
+ /**
203
+ * A hidden temporary name beside a file or folder, as the CLI's other writers
204
+ * name theirs, with this process space and this process's id, so a later run
205
+ * can tell when the run that made it is gone.
206
+ * @param {string} target absolute
207
+ */
208
+ const temporaryBeside = target => path.join(path.dirname(target), `${temporaryPrefix(target)}${process.pid}-${randomUUID()}`);
209
+
210
+ /**
211
+ * Remove the temporaries that runs in this process space left beside a
212
+ * target when they stopped between their write and their rename: those whose
213
+ * process no longer runs. A temporary of a run that still runs, or of a run
214
+ * in another process space (another computer, container or sandbox, whose
215
+ * processes cannot be seen from here), stays.
216
+ * @param {string} target absolute
217
+ */
218
+ function removeStaleTemporaries(target) {
219
+ const prefix = temporaryPrefix(target);
220
+ let names;
221
+ try {
222
+ names = fs.readdirSync(path.dirname(target));
223
+ } catch {
224
+ return;
225
+ }
226
+ for (const name of names) {
227
+ if (!name.startsWith(prefix)) continue;
228
+ const pid = /^(\d+)-[0-9a-f-]{36}$/.exec(name.slice(prefix.length))?.[1];
229
+ if (pid === undefined || isAlive(Number(pid))) continue;
230
+ fs.rmSync(path.join(path.dirname(target), name), {recursive: true, force: true});
231
+ }
232
+ }
233
+
234
+ /**
235
+ * The topmost folder on the way to `file` that does not exist yet, or null
236
+ * when the file's own folder exists.
237
+ * @param {string} file absolute
238
+ * @returns {string | null}
239
+ */
240
+ function newFolderOf(file) {
241
+ /** @type {string | null} */
242
+ let top = null;
243
+ for (let d = path.dirname(file); !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) top = d;
244
+ return top;
245
+ }
246
+
247
+ /**
248
+ * Why a write failed, in terms of the target, never the hidden temporary
249
+ * file or folder beside it: the folder that would not take the temporary,
250
+ * or the error a file inside the temporary folder met.
251
+ * @param {unknown} e
252
+ * @param {string | null} temporary the temporary file or folder
253
+ * @param {string} folder the folder that holds the target
162
254
  * @param {string} cwd
163
255
  */
164
- function writeAll(writes, cwd) {
165
- /** @type {string[]} */
166
- const madeDirs = [];
167
- /** @type {{temp: string, file: string}[]} */
168
- const staged = [];
169
- const undo = () => {
170
- for (const {temp} of staged) fs.rmSync(temp, {force: true});
171
- for (const dir of madeDirs.reverse()) {
172
- try {
173
- fs.rmdirSync(dir);
174
- } catch {
175
- // Not empty or already gone: leave it.
176
- }
177
- }
178
- };
179
- let current = '';
256
+ function writeFailure(e, temporary, folder, cwd) {
257
+ const err = /** @type {NodeJS.ErrnoException} */ (e);
258
+ if (temporary && err?.path === temporary && (err.syscall === 'open' || err.syscall === 'mkdir')) {
259
+ return `${shown(cwd, folder)} does not take a new file (${err.code ?? err.message})`;
260
+ }
261
+ if (temporary && err?.path?.startsWith(temporary + path.sep)) return err.code ?? err.message;
262
+ return String(err?.message ?? e);
263
+ }
264
+
265
+ /**
266
+ * Write one file in one step: its bytes go to a temporary file beside it,
267
+ * which then takes its name. A reader, or another run at the same time, sees
268
+ * the old whole file or the new one, never part of one, and a run stopped
269
+ * part-way leaves the old file as it was; the next write to the file removes
270
+ * the temporary that run left.
271
+ * @param {string} file absolute
272
+ * @param {string | Buffer} content
273
+ * @param {string} cwd
274
+ * @param {{replace: boolean, mode?: number}} options `replace`: an existing
275
+ * file may be replaced; without it, a file that appeared since the checks
276
+ * stays. `mode`: the permission bits the file gets
277
+ */
278
+ function writeOutput(file, content, cwd, {replace, mode}) {
279
+ /** @type {string | null} */
280
+ let temporary = null;
180
281
  try {
181
- for (const w of writes) {
182
- current = w.file;
183
- /** @type {string[]} */
184
- const missing = [];
185
- for (let d = path.dirname(w.file); !fs.existsSync(d); d = path.dirname(d)) missing.unshift(d);
186
- for (const d of missing) {
187
- fs.mkdirSync(d);
188
- madeDirs.push(d);
189
- }
190
- const temp = `${w.file}.astryx-${process.pid}.tmp`;
191
- fs.writeFileSync(temp, w.bytes, {flag: 'wx'});
192
- staged.push({temp, file: w.file});
282
+ fs.mkdirSync(path.dirname(file), {recursive: true});
283
+ /** @type {fs.Stats | null} */
284
+ let existing = null;
285
+ try {
286
+ existing = fs.statSync(file);
287
+ } catch {
288
+ // No file there yet.
193
289
  }
194
- for (const {temp, file} of staged) {
195
- current = file;
196
- fs.renameSync(temp, file);
290
+ if (existing?.isDirectory()) {
291
+ throw Object.assign(new Error(`EISDIR: illegal operation on a directory, open '${file}'`), {code: 'EISDIR'});
197
292
  }
293
+ removeStaleTemporaries(file);
294
+ temporary = temporaryBeside(file);
295
+ fs.writeFileSync(temporary, content, {flag: 'wx'});
296
+ if (mode !== undefined) fs.chmodSync(temporary, mode);
297
+ if (replace) fs.renameSync(temporary, file);
298
+ else publishNewFile(temporary, file);
198
299
  } catch (e) {
199
- undo();
300
+ if (!replace && /** @type {any} */ (e)?.code === 'EEXIST') {
301
+ throw new AstryxError(
302
+ `${shown(cwd, file)} appeared while this ran; nothing was written. Pass --overwrite to replace it.`,
303
+ [],
304
+ ERROR_CODES.ERR_FILE_EXISTS,
305
+ );
306
+ }
200
307
  throw new AstryxError(
201
- `Could not write ${shown(cwd, current)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
308
+ `Could not write ${shown(cwd, file)}: ${writeFailure(e, temporary, path.dirname(file), cwd)}; nothing was written.`,
202
309
  [],
203
310
  ERROR_CODES.ERR_WRITE_FAILED,
204
311
  );
312
+ } finally {
313
+ if (temporary) fs.rmSync(temporary, {force: true});
205
314
  }
206
315
  }
207
316
 
208
317
  /**
209
- * Write one file, creating its folder.
210
- * @param {string} file absolute
211
- * @param {string | Buffer} content
318
+ * Write a new folder and every file in it, all or nothing, in one step: the
319
+ * files go into a temporary folder beside it, which then takes the folder's
320
+ * name. A run stopped part-way leaves no folder behind, so running it again
321
+ * works (and removes the temporary folder that run left), and of two runs
322
+ * that pick the same name, one gets it and the other learns that it is
323
+ * taken.
324
+ * @param {string} folder absolute; does not exist yet
325
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets inside `folder`
212
326
  * @param {string} cwd
327
+ * @returns {boolean} false when the folder appeared before this run could take its name
213
328
  */
214
- function writeOutput(file, content, cwd) {
329
+ function writeFolder(folder, writes, cwd) {
330
+ removeStaleTemporaries(folder);
331
+ const staging = temporaryBeside(folder);
332
+ let current = folder;
215
333
  try {
216
- fs.mkdirSync(path.dirname(file), {recursive: true});
217
- fs.writeFileSync(file, content);
334
+ for (const w of writes) {
335
+ current = w.file;
336
+ const staged = path.join(staging, path.relative(folder, w.file));
337
+ fs.mkdirSync(path.dirname(staged), {recursive: true});
338
+ fs.writeFileSync(staged, w.bytes, {flag: 'wx'});
339
+ }
340
+ current = folder;
341
+ try {
342
+ fs.renameSync(staging, folder);
343
+ } catch (e) {
344
+ if (fs.existsSync(folder)) return false;
345
+ throw e;
346
+ }
347
+ return true;
218
348
  } catch (e) {
219
349
  throw new AstryxError(
220
- `Could not write ${shown(cwd, file)}: ${/** @type {Error} */ (e).message}`,
350
+ `Could not write ${shown(cwd, current)}: ${writeFailure(e, staging, path.dirname(folder), cwd)}; nothing was written.`,
221
351
  [],
222
352
  ERROR_CODES.ERR_WRITE_FAILED,
223
353
  );
354
+ } finally {
355
+ fs.rmSync(staging, {recursive: true, force: true});
224
356
  }
225
357
  }
226
358
 
359
+ /**
360
+ * Write a restore's files: into the new folder that holds them all, in one
361
+ * step, or, when the page goes into a folder that exists (the only file a
362
+ * restore writes there), the page alone.
363
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets, the page first
364
+ * @param {string | null} folder the new folder that holds every file, or null
365
+ * @param {string} cwd
366
+ * @param {boolean} overwrite whether an existing page may be replaced
367
+ * @returns {boolean} false when the new folder appeared before this run could take its name
368
+ */
369
+ function writeRestore(writes, folder, cwd, overwrite) {
370
+ if (folder) return writeFolder(folder, writes, cwd);
371
+ writeOutput(writes[0].file, writes[0].bytes, cwd, {replace: overwrite});
372
+ return true;
373
+ }
374
+
375
+ /**
376
+ * The refusal for a restore whose new folder another run created first.
377
+ * @param {string} folder
378
+ * @param {string} cwd
379
+ */
380
+ const folderTaken = (folder, cwd) =>
381
+ new AstryxError(
382
+ `${shown(cwd, folder)} appeared while this restore ran; nothing was written. Restore into another folder with --out.`,
383
+ [],
384
+ ERROR_CODES.ERR_FILE_EXISTS,
385
+ );
386
+
227
387
  /** @param {unknown} e */
228
388
  function asAstryxError(e) {
229
389
  if (e instanceof RenderError) {
@@ -278,7 +438,7 @@ export async function renderToFile({cwd, input, output, title}) {
278
438
  try {
279
439
  const set = servedSet(input);
280
440
  try {
281
- page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null});
441
+ page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null, output, cwd});
282
442
  } catch (e) {
283
443
  // A page that needs the Core the CLI could not obtain says why.
284
444
  const missing = /** @type {any} */ (e)?.code === 'ERR_RENDER_MISSING_DEPENDENCY' ? /** @type {any} */ (e).detail?.package : null;
@@ -312,7 +472,21 @@ export async function renderToFile({cwd, input, output, title}) {
312
472
  ERROR_CODES.ERR_FILE_EXISTS,
313
473
  );
314
474
  }
315
- writeOutput(output, page.html, cwd);
475
+ // A render never replaces an HTML file this user cannot write, and the file
476
+ // it replaces keeps its permission bits.
477
+ const existingMode = fs.statSync(output, {throwIfNoEntry: false})?.mode;
478
+ if (existingMode !== undefined) {
479
+ try {
480
+ fs.accessSync(output, fs.constants.W_OK);
481
+ } catch (e) {
482
+ throw new AstryxError(
483
+ `Could not write ${shown(cwd, output)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
484
+ [],
485
+ ERROR_CODES.ERR_WRITE_FAILED,
486
+ );
487
+ }
488
+ }
489
+ writeOutput(output, page.html, cwd, {replace: true, ...(existingMode === undefined ? {} : {mode: existingMode & 0o7777})});
316
490
  return {
317
491
  input: shown(cwd, input),
318
492
  output: shown(cwd, output),
@@ -364,16 +538,89 @@ function refuseRunnable(files, cwd, input) {
364
538
  /**
365
539
  * The new folder a restore without --out writes into: beside the HTML file,
366
540
  * named after it (`report.html` gives `report-restored/`, then
367
- * `report-restored-2/` when that exists).
541
+ * `report-restored-2/` when that exists). A name already taken is never
542
+ * written again, so a temporary folder a stopped run left for it goes.
368
543
  * @param {string} input absolute
369
544
  */
370
545
  function restoreFolder(input) {
371
546
  const stem = path.basename(input).replace(/\.[^.]+$/, '');
372
547
  let folder = path.join(path.dirname(input), `${stem}-restored`);
373
- for (let n = 2; fs.existsSync(folder); n++) folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
548
+ for (let n = 2; fs.existsSync(folder); n++) {
549
+ removeStaleTemporaries(folder);
550
+ folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
551
+ }
374
552
  return folder;
375
553
  }
376
554
 
555
+ /**
556
+ * The version of the CLI that rendered a file: the one its embedded source
557
+ * records, else the one its generator meta names.
558
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
559
+ * @param {string} html
560
+ * @returns {string | null}
561
+ */
562
+ function renderedByOf(source, html) {
563
+ const named = source.cli ?? /<meta name="generator" content="Astryx ([^"<>]+)">/.exec(html.slice(0, 4096))?.[1];
564
+ return isValidSemver(named) ? /** @type {string} */ (named) : null;
565
+ }
566
+
567
+ /**
568
+ * The packages a file says its page rendered with, as `name@version`, when
569
+ * it records them.
570
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
571
+ * @returns {string[] | null}
572
+ */
573
+ function packagesOf(source) {
574
+ const recorded = source.packages;
575
+ if (!recorded || typeof recorded !== 'object' || Array.isArray(recorded)) return null;
576
+ return Object.entries(recorded)
577
+ .filter(([name, version]) => isPackageName(name) && isValidSemver(version))
578
+ .map(([name, version]) => `${name}@${version}`);
579
+ }
580
+
581
+ /**
582
+ * Whether someone changed the page after the render, for a file that records
583
+ * the page as rendered: each run of text that changed (the title first), and
584
+ * whether the styles changed. The restored source never takes these changes:
585
+ * it is the page as rendered.
586
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
587
+ * @param {string} html
588
+ * @param {{file: string, text: string}[]} modules the restored modules, as shown to the caller
589
+ * @returns {{edited?: boolean, stylesEdited?: boolean, edits?: import('./render.type.mjs').RenderEdit[], moreEdits?: number}}
590
+ */
591
+ function pageChanges(source, html, modules) {
592
+ const recorded = source.markup;
593
+ if (!recorded || typeof recorded.sha256 !== 'string') return {};
594
+ // The page as a browser reads it, so a copy whose line ends changed on the
595
+ // way is no edit.
596
+ const markupNow = renderedMarkupOf(html);
597
+ const now = markupNow === null ? null : asParsed(markupNow);
598
+ const head = renderedHeadOf(html);
599
+ const text = recordedText(recorded);
600
+ const titleNow = head.title === null ? null : asParsed(decode(head.title));
601
+ const titleEdited = typeof text?.title === 'string' && titleNow !== asParsed(text.title);
602
+ const stylesEdited = typeof recorded.style === 'string' ? head.style === null || sha256(asParsed(head.style)) !== recorded.style : undefined;
603
+ const markupEdited = now === null || sha256(now) !== recorded.sha256;
604
+ const styles = stylesEdited === undefined ? {} : {stylesEdited};
605
+ if (!markupEdited && !titleEdited && !stylesEdited) return {edited: false, ...styles};
606
+ const {edits, more} = markupEdited ? textEdits(text?.runs ?? [], textRuns(now ?? '')) : {edits: [], more: 0};
607
+ // A title that changed with the heading it comes from is one change, not two.
608
+ const titleEdit = {was: /** @type {string} */ (text?.title), now: titleNow};
609
+ const titleAgain = edits.some(edit => edit.was === titleEdit.was && edit.now === titleEdit.now);
610
+ const all = [...(titleEdited && !titleAgain ? [titleEdit] : []), ...edits];
611
+ return {
612
+ edited: true,
613
+ ...styles,
614
+ // Each change is found in the source by its whole text, then cut to show.
615
+ edits: all.map(edit => ({
616
+ was: edit.was === null ? null : clip(edit.was),
617
+ now: edit.now === null ? null : clip(edit.now),
618
+ ...((edit.was && locate(edit.was, modules)) || {}),
619
+ })),
620
+ ...(more > 0 ? {moreEdits: more} : {}),
621
+ };
622
+ }
623
+
377
624
  /**
378
625
  * Turn a rendered HTML file back into a page module.
379
626
  * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
@@ -382,6 +629,17 @@ function restoreFolder(input) {
382
629
  export function reverseToFile({cwd, input, output, overwrite}) {
383
630
  const html = readInput(input, cwd).toString('utf8');
384
631
  const block = readSourceBlock(html);
632
+ const rendered = /<meta name="generator" content="Astryx[ "]/.test(html);
633
+ // A merge that left conflict markers in an Astryx page holds two versions
634
+ // of it at once, the embedded source too: choosing one would choose for
635
+ // the user.
636
+ if ((block.found || rendered || isAstryxMarkup(html)) && /^<{7}(?: |$)/m.test(html) && /^>{7}(?: |$)/m.test(html)) {
637
+ throw new AstryxError(
638
+ `${shown(cwd, input)} holds unresolved merge conflict markers (<<<<<<< and >>>>>>>), so it holds two versions at once; nothing was written. Keep the whole file from one side, or render the merged page again, then run this again.`,
639
+ [],
640
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
641
+ );
642
+ }
385
643
  /** @param {string[]} files */
386
644
  const refuseExisting = files => {
387
645
  if (overwrite) return;
@@ -410,6 +668,15 @@ export function reverseToFile({cwd, input, output, overwrite}) {
410
668
  );
411
669
  }
412
670
  };
671
+ if (block.found && 'newer' in block) {
672
+ const {format, cli} = block.newer;
673
+ const command = `${cliCommand(cli ?? 'latest')} experimental render --reverse ${shellArg(shown(cwd, input))}`;
674
+ throw new AstryxError(
675
+ `${shown(cwd, input)} is in render format ${format}${cli ? `, written by @astryxdesign/cli ${cli}` : ''}, which is newer than this CLI reads (render format ${RENDER_FORMAT}, @astryxdesign/cli ${cliVersion()}); nothing was written. Give it back with ${cli ? 'the CLI that wrote it' : 'the latest CLI'}: ${command}`,
676
+ [{name: command, reason: cli ? 'give it back with the CLI version that wrote the file' : 'give it back with the latest CLI'}],
677
+ ERROR_CODES.ERR_RENDER_NEWER_FORMAT,
678
+ );
679
+ }
413
680
  if (block.found && 'damaged' in block) {
414
681
  throw new AstryxError(
415
682
  `${shown(cwd, input)} carries an Astryx page source, but ${block.damaged}, so it cannot be given back exactly.`,
@@ -431,126 +698,156 @@ export function reverseToFile({cwd, input, output, overwrite}) {
431
698
  );
432
699
  }
433
700
  });
434
- // Without --out, the page and the files it imports come back into a new
435
- // folder beside the HTML file, named after it (`report.html` gives
436
- // `report-restored/`), with the layout they were rendered in. Nothing in
437
- // the received file decides where in your project anything goes.
438
- const requested = output ?? path.join(restoreFolder(input), ...source.files[0].path.split('/'));
439
- refuseConfigTarget(requested);
440
- const seen = new Set();
441
- for (const f of source.files) {
442
- const key = f.path.toLowerCase();
443
- if (seen.has(key)) {
701
+ // A restore without --out picks the first folder name no folder has.
702
+ // When another run takes that name first, this one takes the next: each
703
+ // name it loses exists from then on, so every pass picks a new one.
704
+ for (;;) {
705
+ // Without --out, the page and the files it imports come back into a new
706
+ // folder beside the HTML file, named after it (`report.html` gives
707
+ // `report-restored/`), with the layout they were rendered in. Nothing in
708
+ // the received file decides where in your project anything goes.
709
+ const folder = output ? null : restoreFolder(input);
710
+ const requested = output ?? path.join(/** @type {string} */ (folder), ...source.files[0].path.split('/'));
711
+ refuseConfigTarget(requested);
712
+ const seen = new Set();
713
+ for (const f of source.files) {
714
+ const key = f.path.toLowerCase();
715
+ if (seen.has(key)) {
716
+ throw new AstryxError(
717
+ `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
718
+ [],
719
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
720
+ );
721
+ }
722
+ seen.add(key);
723
+ }
724
+ // Modules, stylesheets and JSON are written only when the page reaches
725
+ // them through its own imports: one it never imports is not part of it,
726
+ // whatever its name.
727
+ const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(path.dirname(requested))});
728
+ // A carried image, font or media file needs no import to be part of the
729
+ // page (it may be named in markup, a stylesheet, JSON or a computed
730
+ // path): the render's own list is the authority, so it is kept when its
731
+ // bytes are a known image, font or media format (any, whatever the
732
+ // extension), and goes where the layout puts it.
733
+ for (const f of source.files) {
734
+ if (reached.has(f.path) || !isAssetPath(f.path)) continue;
735
+ if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
736
+ }
737
+ const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
738
+ if (stray.length > 0) {
444
739
  throw new AstryxError(
445
- `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
740
+ `${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.`,
446
741
  [],
447
742
  ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
448
743
  );
449
744
  }
450
- seen.add(key);
451
- }
452
- // Modules, stylesheets and JSON are written only when the page reaches
453
- // them through its own imports: one it never imports is not part of it,
454
- // whatever its name.
455
- const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(path.dirname(requested))});
456
- // A carried image, font or media file needs no import to be part of the
457
- // page (it may be named in markup, a stylesheet, JSON or a computed
458
- // path): the render's own list is the authority, so it is kept when its
459
- // bytes are a known image, font or media format (any, whatever the
460
- // extension), and goes where the layout puts it.
461
- for (const f of source.files) {
462
- if (reached.has(f.path) || !isAssetPath(f.path)) continue;
463
- if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
464
- }
465
- const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
466
- if (stray.length > 0) {
467
- throw new AstryxError(
468
- `${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.`,
469
- [],
470
- ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
471
- );
472
- }
473
- // Each file the page reaches by a relative import goes where that import
474
- // finds it from the page's new folder, so every relative import still
475
- // resolves wherever the page lands; a file reached through an alias goes
476
- // where this project's alias points. Every file but the page must land
477
- // in a folder this restore creates: a received file never adds a file to
478
- // a folder that already exists (a server hook at the project root, a
479
- // middleware module), so a page with neighbours comes back into a new
480
- // folder.
481
- const entryDir = path.posix.dirname(source.files[0].path);
482
- const anchor = path.dirname(requested);
483
- /** @param {string} p */
484
- const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
485
- // A file beside the page or elsewhere goes only into a folder this
486
- // restore creates: never into a folder that already exists.
487
- // The one folder every file but the page must land in: the topmost
488
- // folder on the page's path that this restore creates. When the page's
489
- // folder already exists there is none, so a page with neighbours comes
490
- // back only into a new folder.
491
- /** @type {string | null} */
492
- let home = null;
493
- for (let d = anchor; !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) home = d;
494
- const within = (/** @type {string} */ file) => {
495
- if (!home) return false;
496
- const rel = path.relative(home, file);
497
- return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
498
- };
499
- const target = path.join(anchor, path.basename(requested));
500
- /** @type {{file: string, bytes: Buffer}[]} */
501
- const writes = [];
502
- const placed = new Set();
503
- /** @type {string[]} */
504
- const outside = [];
505
- /** @type {string[]} */
506
- const aliasedOutside = [];
507
- source.files.forEach((f, i) => {
508
- const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
509
- const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
510
- for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
511
- if (placed.has(file)) continue;
512
- placed.add(file);
513
- if (i > 0 && !within(file)) (aliased ? aliasedOutside : outside).push(file);
514
- writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
745
+ // Each file the page reaches by a relative import goes where that import
746
+ // finds it from the page's new folder, so every relative import still
747
+ // resolves wherever the page lands; a file reached through an alias goes
748
+ // where this project's alias points. Every file but the page must land
749
+ // in a folder this restore creates: a received file never adds a file to
750
+ // a folder that already exists (a server hook at the project root, a
751
+ // middleware module), so a page with neighbours comes back into a new
752
+ // folder.
753
+ const entryDir = path.posix.dirname(source.files[0].path);
754
+ const anchor = path.dirname(requested);
755
+ /** @param {string} p */
756
+ const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
757
+ // A file beside the page or elsewhere goes only into a folder this
758
+ // restore creates: never into a folder that already exists.
759
+ // The one folder every file but the page must land in: the topmost
760
+ // folder on the page's path that this restore creates. When the page's
761
+ // folder already exists there is none, so a page with neighbours comes
762
+ // back only into a new folder.
763
+ // Without --out, that is the folder this restore picked because no
764
+ // folder had its name: another run that takes the name first makes this
765
+ // one take the next.
766
+ const home = folder ?? newFolderOf(requested);
767
+ const within = (/** @type {string} */ file) => isInside(file, home);
768
+ const target = path.join(anchor, path.basename(requested));
769
+ /** @type {{file: string, bytes: Buffer}[]} */
770
+ const writes = [];
771
+ const placed = new Set();
772
+ /** @type {string[]} */
773
+ const outside = [];
774
+ /** @type {string[]} */
775
+ const aliasedOutside = [];
776
+ source.files.forEach((f, i) => {
777
+ const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
778
+ const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
779
+ for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
780
+ if (placed.has(file)) continue;
781
+ placed.add(file);
782
+ // Every copy but the page at its target, the page's own copy that an
783
+ // alias places included, lands in the one new folder.
784
+ if (file !== target && !within(file)) (aliased ? aliasedOutside : outside).push(file);
785
+ writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
786
+ }
787
+ });
788
+ if (aliasedOutside.length > 0) {
789
+ throw new AstryxError(
790
+ `${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.`,
791
+ [],
792
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
793
+ );
515
794
  }
516
- });
517
- if (aliasedOutside.length > 0) {
518
- throw new AstryxError(
519
- `${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.`,
520
- [],
521
- ERROR_CODES.ERR_PATH_TRAVERSAL,
522
- );
523
- }
524
- if (outside.length > 0) {
525
- const top = entryDir === '.' ? '' : `${entryDir}/`;
526
- let fresh = 'restored';
527
- for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
528
- const suggestion = `--out ${fresh}/${top}${path.basename(requested)}`;
529
- throw new AstryxError(
530
- `${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}.`,
531
- [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
532
- ERROR_CODES.ERR_PATH_TRAVERSAL,
533
- );
795
+ if (outside.length > 0) {
796
+ const top = entryDir === '.' ? '' : `${entryDir}/`;
797
+ let fresh = 'restored';
798
+ for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
799
+ const suggestion = `--out ${shellArg(`${fresh}/${top}${path.basename(requested)}`)}`;
800
+ throw new AstryxError(
801
+ `${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}.`,
802
+ [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
803
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
804
+ );
805
+ }
806
+ writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
807
+ refuseRunnable(writes.map(w => w.file), cwd, input);
808
+ refuseExisting(writes.filter(w => !isInside(w.file, home)).map(w => w.file));
809
+ refuseProtected(writes.map(w => w.file), cwd, home);
810
+ if (!writeRestore(writes, home, cwd, overwrite)) {
811
+ // Another run took the folder's name first: a restore without --out
812
+ // takes the next one.
813
+ if (output) throw folderTaken(/** @type {string} */ (home), cwd);
814
+ continue;
815
+ }
816
+ const renderedBy = renderedByOf(source, html);
817
+ const packages = packagesOf(source);
818
+ const modules = writes
819
+ .filter(w => PAGE_EXTENSIONS.includes(path.extname(w.file).toLowerCase()))
820
+ .map(w => ({file: shown(cwd, w.file), text: w.bytes.toString('utf8')}));
821
+ return {
822
+ input: shown(cwd, input),
823
+ mode: 'embedded',
824
+ output: shown(cwd, target),
825
+ files: writes.map(w => shown(cwd, w.file)),
826
+ // The page is byte for byte the one rendered; an import it makes that
827
+ // the file does not carry (a file a render never embeds) is named.
828
+ exact: missing.length === 0,
829
+ ...(missing.length > 0 ? {missing} : {}),
830
+ format: source.version,
831
+ ...(renderedBy ? {renderedBy} : {}),
832
+ ...(packages ? {packages} : {}),
833
+ ...(typeof source.title === 'string' ? {title: source.title} : {}),
834
+ ...pageChanges(source, html, modules),
835
+ };
534
836
  }
535
- writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
536
- refuseRunnable(writes.map(w => w.file), cwd, input);
537
- refuseExisting(writes.map(w => w.file));
538
- refuseProtected(writes.map(w => w.file), cwd);
539
- writeAll(writes, cwd);
540
- return {
541
- input: shown(cwd, input),
542
- mode: 'embedded',
543
- output: shown(cwd, target),
544
- files: writes.map(w => shown(cwd, w.file)),
545
- // The page is byte for byte the one rendered; an import it makes that
546
- // the file does not carry (a file a render never embeds) is named.
547
- exact: missing.length === 0,
548
- ...(missing.length > 0 ? {missing} : {}),
549
- };
837
+ }
838
+ // A render always ends its file with `</html>`. A file a render wrote that
839
+ // has none lost its end on the way, the embedded source with it: the
840
+ // markup left is only part of the page.
841
+ if (rendered && !/<\/html>/i.test(html)) {
842
+ throw new AstryxError(
843
+ `${shown(cwd, input)} is cut short: it ends before its embedded source, so the page cannot be given back; nothing was written. Get the whole file again.`,
844
+ [],
845
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
846
+ );
550
847
  }
551
848
  // A file a render wrote, whose source block was taken out on the way
552
849
  // (sanitizers and editors strip <script> elements), says so.
553
- if (!isAstryxMarkup(html) && /<meta name="generator" content="Astryx[ "]/.test(html)) {
850
+ if (!isAstryxMarkup(html) && rendered) {
554
851
  throw new AstryxError(
555
852
  `${shown(cwd, input)} was rendered by Astryx, but its embedded source was removed (a sanitizer or an editor strips <script> blocks) and it has no Astryx components to rebuild from; nothing was written. Render the page again from its source and send the new file as is.`,
556
853
  [],
@@ -569,27 +866,35 @@ export function reverseToFile({cwd, input, output, overwrite}) {
569
866
  ERROR_CODES.ERR_RENDER_NOT_ASTRYX,
570
867
  );
571
868
  }
572
- const target = output ?? path.join(restoreFolder(input), 'page.tsx');
573
- refuseConfigTarget(target);
574
- confined(target, cwd, 'The page');
575
- refuseRunnable([target], cwd, input);
576
- refuseExisting([target]);
577
- // Components resolve from where the page will live, then from the HTML
578
- // file's folder, then from the current folder.
579
- const from =
580
- [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
581
- const rebuilt = rebuildPage(html, from);
582
- refuseProtected([target], cwd);
583
- writeOutput(target, rebuilt.source, cwd);
584
- return {
585
- input: shown(cwd, input),
586
- mode: 'rebuilt',
587
- output: shown(cwd, target),
588
- files: [shown(cwd, target)],
589
- exact: false,
590
- components: rebuilt.components,
591
- elements: rebuilt.elements,
592
- unknown: rebuilt.unknown,
593
- omitted: rebuilt.omitted,
594
- };
869
+ // As above: a name another run takes first exists from then on.
870
+ for (;;) {
871
+ const folder = output ? null : restoreFolder(input);
872
+ const target = output ?? path.join(/** @type {string} */ (folder), 'page.tsx');
873
+ const home = folder ?? newFolderOf(target);
874
+ refuseConfigTarget(target);
875
+ confined(target, cwd, 'The page');
876
+ refuseRunnable([target], cwd, input);
877
+ refuseExisting(isInside(target, home) ? [] : [target]);
878
+ // Components resolve from where the page will live, then from the HTML
879
+ // file's folder, then from the current folder.
880
+ const from =
881
+ [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
882
+ const rebuilt = rebuildPage(html, from);
883
+ refuseProtected([target], cwd, home);
884
+ if (!writeRestore([{file: target, bytes: Buffer.from(rebuilt.source)}], home, cwd, overwrite)) {
885
+ if (output) throw folderTaken(/** @type {string} */ (home), cwd);
886
+ continue;
887
+ }
888
+ return {
889
+ input: shown(cwd, input),
890
+ mode: 'rebuilt',
891
+ output: shown(cwd, target),
892
+ files: [shown(cwd, target)],
893
+ exact: false,
894
+ components: rebuilt.components,
895
+ elements: rebuilt.elements,
896
+ unknown: rebuilt.unknown,
897
+ omitted: rebuilt.omitted,
898
+ };
899
+ }
595
900
  }