@astryxdesign/cli 0.7.16 → 0.7.17-canary.g0404a74

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 (529) hide show
  1. package/README.md +76 -86
  2. package/api/build/_adapter.d.mts +17 -0
  3. package/api/build/_adapter.mjs +53 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/blocks/blocks.weights.json +1 -1
  7. package/api/build/build.doc.mjs +4 -3
  8. package/api/build/build.type.d.mts +2 -2
  9. package/api/build/build.type.mjs +3 -3
  10. package/api/build/kit/kind.d.mts +2 -1
  11. package/api/build/kit/kind.mjs +199 -10
  12. package/api/build/kit/kit.mjs +6 -4
  13. package/api/build/kit/rank.d.mts +6 -4
  14. package/api/build/kit/rank.mjs +132 -28
  15. package/api/build/kit/signals.d.mts +7 -1
  16. package/api/build/kit/signals.mjs +21 -10
  17. package/api/build/kit/start.d.mts +5 -4
  18. package/api/build/kit/start.mjs +14 -9
  19. package/api/build/kit/weights.d.mts +39 -3
  20. package/api/build/kit/weights.json +1 -1
  21. package/api/build/kit/weights.mjs +351 -46
  22. package/api/build/kit/word-model.d.mts +23 -0
  23. package/api/build/kit/word-model.mjs +46 -0
  24. package/api/build/kit/words.d.mts +86 -0
  25. package/api/build/kit/words.mjs +241 -1
  26. package/api/build/tree.mjs +1 -1
  27. package/api/component/__fixtures__/resolutions/modules.txt +5 -6
  28. package/api/component/_adapter.d.mts +26 -2
  29. package/api/component/_adapter.mjs +135 -8
  30. package/api/component/component.mjs +14 -1
  31. package/api/component/list/list.d.mts +1 -1
  32. package/api/component/list/list.mjs +48 -6
  33. package/api/discover/_adapter.d.mts +11 -1
  34. package/api/discover/_adapter.mjs +95 -1
  35. package/api/discover/detail/item/item.mjs +5 -0
  36. package/api/discover/discover.mjs +12 -3
  37. package/api/discover/discover.type.d.mts +16 -3
  38. package/api/discover/discover.type.mjs +13 -3
  39. package/api/discover/search/search.mjs +3 -2
  40. package/api/docs/_adapter.d.mts +57 -2
  41. package/api/docs/_adapter.mjs +266 -33
  42. package/api/docs/_entry-names-lazily.d.mts +22 -0
  43. package/api/docs/_entry-names-lazily.mjs +25 -0
  44. package/api/docs/_entry-names.d.mts +23 -0
  45. package/api/docs/_entry-names.mjs +105 -0
  46. package/api/docs/docs.d.mts +3 -0
  47. package/api/docs/docs.doc.mjs +7 -1
  48. package/api/docs/docs.mjs +12 -0
  49. package/api/docs/docs.type.d.mts +5 -0
  50. package/api/docs/docs.type.mjs +2 -0
  51. package/api/docs/node/node.mjs +1 -1
  52. package/api/doctor/_adapter.d.mts +54 -5
  53. package/api/doctor/_adapter.mjs +162 -11
  54. package/api/doctor/built-checks.mjs +40 -14
  55. package/api/doctor/doctor.d.mts +15 -3
  56. package/api/doctor/doctor.doc.mjs +1 -1
  57. package/api/doctor/doctor.mjs +31 -7
  58. package/api/doctor/theme-checks.d.mts +35 -3
  59. package/api/doctor/theme-checks.mjs +377 -29
  60. package/api/hook/_adapter.d.mts +10 -4
  61. package/api/hook/_adapter.mjs +41 -5
  62. package/api/hook/detail/detail.mjs +5 -2
  63. package/api/hook/detail/params/params.mjs +10 -3
  64. package/api/icon/_records.mjs +2 -1
  65. package/api/index.d.mts +2 -0
  66. package/api/index.mjs +2 -0
  67. package/api/integration/_adapter.d.mts +44 -0
  68. package/api/integration/_adapter.mjs +77 -1
  69. package/api/integration/add-helpers.mjs +10 -0
  70. package/api/integration/authoring-checks.mjs +11 -8
  71. package/api/integration/example-scope.d.mts +14 -0
  72. package/api/integration/example-scope.mjs +44 -0
  73. package/api/integration/example-scope.type.d.mts +29 -0
  74. package/api/integration/example-scope.type.mjs +25 -0
  75. package/api/integration/integrationExampleScope.doc.d.mts +11 -0
  76. package/api/integration/integrationExampleScope.doc.mjs +59 -0
  77. package/api/integration/pack-check.mjs +16 -1
  78. package/api/integration/validate-integration.d.mts +18 -6
  79. package/api/integration/validate-integration.mjs +129 -15
  80. package/api/integration/validate-integration.type.d.mts +22 -0
  81. package/api/integration/validate-integration.type.mjs +2 -1
  82. package/api/integration/validateIntegration.doc.mjs +1 -1
  83. package/api/render/_adapter.mjs +591 -195
  84. package/api/render/render.doc.mjs +11 -3
  85. package/api/render/render.type.d.mts +53 -1
  86. package/api/render/render.type.mjs +32 -2
  87. package/api/search/ORDERING.md +2 -2
  88. package/api/search/_adapter.d.mts +9 -0
  89. package/api/search/_adapter.mjs +85 -0
  90. package/api/search/_candidate-score.d.mts +9 -4
  91. package/api/search/_candidate-score.mjs +133 -46
  92. package/api/search/_fit-order.mjs +3 -3
  93. package/api/search/_gather-components.d.mts +3 -2
  94. package/api/search/_gather-components.mjs +12 -3
  95. package/api/search/_lexical.d.mts +14 -0
  96. package/api/search/_lexical.mjs +93 -11
  97. package/api/search/_result.d.mts +11 -9
  98. package/api/search/_result.mjs +4 -4
  99. package/api/search/_score.d.mts +6 -1
  100. package/api/search/_score.mjs +15 -3
  101. package/api/search/search-index.mjs +7 -1
  102. package/api/search/search.d.mts +1 -1
  103. package/api/template/_adapter.d.mts +16 -0
  104. package/api/template/_adapter.mjs +39 -2
  105. package/api/template/cdn/cdn.mjs +37 -8
  106. package/api/template/copy/copy.d.mts +6 -3
  107. package/api/template/copy/copy.mjs +40 -8
  108. package/api/template/template.doc.mjs +3 -3
  109. package/api/template/template.mjs +63 -11
  110. package/api/template/template.type.d.mts +1 -0
  111. package/api/template/template.type.mjs +1 -0
  112. package/api/theme/_adapter.d.mts +12 -1
  113. package/api/theme/_adapter.mjs +132 -13
  114. package/api/theme/_app-provider.d.mts +31 -0
  115. package/api/theme/_app-provider.mjs +135 -0
  116. package/api/theme/add/add.mjs +3 -1
  117. package/api/theme/build/build.d.mts +142 -1
  118. package/api/theme/build/build.mjs +692 -284
  119. package/api/theme/build/core-interception.d.mts +10 -0
  120. package/api/theme/build/core-interception.mjs +10 -0
  121. package/api/theme/build/font-warning.d.mts +80 -5
  122. package/api/theme/build/font-warning.mjs +323 -55
  123. package/api/theme/build/icon-imports.mjs +51 -9
  124. package/api/theme/build/null-values.d.mts +28 -0
  125. package/api/theme/build/null-values.mjs +191 -0
  126. package/api/theme/list/list.mjs +17 -1
  127. package/api/theme/remove/remove.d.mts +2 -1
  128. package/api/theme/remove/remove.mjs +7 -3
  129. package/api/theme/theme.type.d.mts +78 -1
  130. package/api/theme/theme.type.mjs +38 -2
  131. package/api/theme/themeAdd.doc.mjs +1 -1
  132. package/api/theme/themeListAvailable.doc.mjs +1 -1
  133. package/api/theme/themeRemove.doc.mjs +8 -5
  134. package/api/theme-edit/_adapter.d.mts +116 -4
  135. package/api/theme-edit/_adapter.mjs +1058 -93
  136. package/api/theme-edit/_catalog.d.mts +46 -2
  137. package/api/theme-edit/_catalog.mjs +115 -14
  138. package/api/theme-edit/_check.d.mts +133 -24
  139. package/api/theme-edit/_check.mjs +3392 -531
  140. package/api/theme-edit/_color.d.mts +26 -0
  141. package/api/theme-edit/_color.mjs +92 -2
  142. package/api/theme-edit/_compiler.d.mts +5 -1
  143. package/api/theme-edit/_compiler.mjs +141 -17
  144. package/api/theme-edit/_context.d.mts +74 -6
  145. package/api/theme-edit/_context.mjs +468 -76
  146. package/api/theme-edit/_css.d.mts +21 -0
  147. package/api/theme-edit/_css.mjs +87 -14
  148. package/api/theme-edit/_edit.d.mts +74 -7
  149. package/api/theme-edit/_edit.mjs +4426 -319
  150. package/api/theme-edit/_how-commands.d.mts +76 -1
  151. package/api/theme-edit/_how-commands.mjs +793 -9
  152. package/api/theme-edit/_how-question.d.mts +97 -6
  153. package/api/theme-edit/_how-question.mjs +9184 -747
  154. package/api/theme-edit/_how.d.mts +5 -2
  155. package/api/theme-edit/_how.mjs +255 -46
  156. package/api/theme-edit/_importers.d.mts +38 -0
  157. package/api/theme-edit/_importers.mjs +188 -0
  158. package/api/theme-edit/_marks.d.mts +31 -5
  159. package/api/theme-edit/_marks.mjs +57 -5
  160. package/api/theme-edit/_name-rule.d.mts +11 -0
  161. package/api/theme-edit/_name-rule.mjs +12 -0
  162. package/api/theme-edit/_normal.d.mts +322 -0
  163. package/api/theme-edit/_normal.mjs +1630 -0
  164. package/api/theme-edit/_palette.d.mts +49 -0
  165. package/api/theme-edit/_palette.mjs +180 -38
  166. package/api/theme-edit/_part-words.d.mts +39 -0
  167. package/api/theme-edit/_part-words.mjs +152 -0
  168. package/api/theme-edit/_parts.d.mts +55 -3
  169. package/api/theme-edit/_parts.mjs +421 -36
  170. package/api/theme-edit/_preview-app.d.mts +7 -13
  171. package/api/theme-edit/_preview-app.mjs +1108 -599
  172. package/api/theme-edit/_preview.d.mts +156 -19
  173. package/api/theme-edit/_preview.mjs +809 -180
  174. package/api/theme-edit/_project.d.mts +61 -1
  175. package/api/theme-edit/_project.mjs +177 -6
  176. package/api/theme-edit/_settings.d.mts +619 -48
  177. package/api/theme-edit/_settings.mjs +4910 -617
  178. package/api/theme-edit/_tables.d.mts +41 -0
  179. package/api/theme-edit/_tables.mjs +261 -41
  180. package/api/theme-edit/_vet.d.mts +31 -0
  181. package/api/theme-edit/_vet.mjs +114 -8
  182. package/api/theme-edit/theme-edit.type.d.mts +34 -2
  183. package/api/theme-edit/theme-edit.type.mjs +18 -3
  184. package/api/theme-edit/themeEditHow.doc.mjs +1 -1
  185. package/api/theme-edit/themeEditNew.doc.d.mts +0 -1
  186. package/api/theme-edit/themeEditNew.doc.mjs +7 -4
  187. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  188. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +2 -2
  189. package/api/upgrade/run/run.mjs +4 -3
  190. package/api/upgrade/upgrade.mjs +16 -1
  191. package/assets/codemods/integration-discovery.mjs +2 -1
  192. package/assets/codemods/integration-runner.mjs +1 -1
  193. package/assets/codemods/jscodeshift.d.ts +1 -1
  194. package/assets/codemods/run-codemod.mjs +151 -18
  195. package/assets/codemods/runner.mjs +1 -4
  196. package/assets/codemods/transforms/next/index.mjs +11 -1
  197. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  198. package/assets/component-list.generated.json +1 -0
  199. package/assets/docs/author-a-theme.doc.mjs +2 -0
  200. package/assets/docs/theme.doc.dense.mjs +76 -7
  201. package/assets/docs/theme.doc.mjs +66 -2
  202. package/assets/docs/theme.doc.zh.mjs +51 -1
  203. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  204. package/assets/docs/tree/checks.doc.mjs +2 -2
  205. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  206. package/assets/docs/tree/document-the-theme.doc.mjs +1 -1
  207. package/assets/docs/tree/font-setup.doc.mjs +1 -1
  208. package/assets/docs/tree/fonts-and-assets.doc.mjs +1 -1
  209. package/assets/docs/tree/render-pages.doc.mjs +46 -5
  210. package/assets/docs/tree/share-a-page.doc.mjs +157 -0
  211. package/assets/docs/tree/single-component.doc.mjs +4 -0
  212. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  213. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  214. package/assets/docs/tree/write-good-templates.doc.mjs +1 -1
  215. package/assets/docs/use-a-theme.doc.mjs +2 -2
  216. package/assets/docs-routes.generated.json +1 -0
  217. package/assets/docs.generated.json +2 -2
  218. package/assets/search-catalog.generated.json +2 -0
  219. package/assets/self-audit.generated.json +1 -1
  220. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  221. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  222. package/assets/templates/blocks/components/ChatComposerInput/useSpeechRecognitionHookUsage.doc.mjs +14 -0
  223. package/assets/templates/blocks/components/ChatComposerInput/useSpeechRecognitionHookUsage.tsx +43 -0
  224. package/assets/templates/blocks/components/Hooks/useContainerRevealHookUsage.tsx +2 -2
  225. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  226. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  227. package/assets/templates/components.generated.json +1 -1
  228. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  229. package/assets/templates/pages/ai-chat-landing/page.tsx +31 -4
  230. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +5 -1
  231. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  232. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  233. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  234. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  235. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  236. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  237. package/assets/templates/pages/dashboard-alert-rail/page.tsx +1 -1
  238. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  239. package/assets/templates/pages/dashboard-cohort-funnel/page.tsx +1 -1
  240. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  241. package/assets/templates/pages/dashboard-comparison/page.tsx +2 -2
  242. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  243. package/assets/templates/pages/dashboard-progress/page.tsx +1 -1
  244. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  245. package/assets/templates/pages/detail-page/page.tsx +60 -7
  246. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  247. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  248. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  249. package/assets/templates/pages/documentation-technical/page.tsx +13 -13
  250. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  251. package/assets/templates/pages/editor/page.tsx +14 -2
  252. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  253. package/assets/templates/pages/file-explorer/page.tsx +9 -0
  254. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  255. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  256. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  257. package/assets/templates/pages/form-wizard-vertical/page.tsx +23 -3
  258. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  259. package/assets/templates/pages/ide/page.tsx +33 -2
  260. package/assets/templates/pages/kanban-board/page.tsx +12 -2
  261. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  262. package/assets/templates/pages/library/template.doc.mjs +4 -1
  263. package/assets/templates/pages/login/template.doc.mjs +2 -1
  264. package/assets/templates/pages/login-card/page.tsx +16 -0
  265. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  266. package/assets/templates/pages/login-split/page.tsx +19 -6
  267. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  268. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  269. package/assets/templates/pages/messaging-shell/template.doc.mjs +6 -0
  270. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  271. package/assets/templates/pages/payment-form/page.tsx +30 -4
  272. package/assets/templates/pages/product-detail/page.tsx +26 -2
  273. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  274. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  275. package/assets/templates/pages/settings-dialog/page.tsx +162 -12
  276. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  277. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  278. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  279. package/assets/templates/pages/shell-side-nav/page.tsx +11 -3
  280. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  281. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  282. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  283. package/assets/templates/pages/table-filter/page.tsx +9 -0
  284. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  285. package/assets/templates/pages/table-grouped/page.tsx +161 -133
  286. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  287. package/assets/templates/pages/table-page/page.tsx +14 -1
  288. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  289. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  290. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  291. package/assets/templates/pages/work-item-detail/page.tsx +47 -7
  292. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  293. package/assets/theme.template.ts +9 -2
  294. package/authoring/debug/parse.d.mts +3 -3
  295. package/authoring/doctypes/_schema.d.mts +9 -9
  296. package/authoring/doctypes/command/command.doc.mjs +1 -1
  297. package/authoring/doctypes/component/categories.d.mts +37 -0
  298. package/authoring/doctypes/component/categories.mjs +54 -0
  299. package/authoring/doctypes/template/template.doc.mjs +1 -1
  300. package/authoring/doctypes/template/type.ts +9 -0
  301. package/authoring/example/example.doc.d.mts +12 -0
  302. package/authoring/example/example.doc.mjs +69 -0
  303. package/authoring/example/preview.d.mts +92 -0
  304. package/authoring/example/preview.mjs +994 -0
  305. package/authoring/example/type.ts +102 -0
  306. package/authoring/index.d.mts +1 -0
  307. package/authoring/index.d.ts +12 -0
  308. package/authoring/index.mjs +3 -1
  309. package/authoring/integration/integration.doc.mjs +8 -0
  310. package/authoring/integration/schema.d.mts +24 -1
  311. package/authoring/integration/schema.mjs +126 -4
  312. package/authoring/integration/type.ts +14 -0
  313. package/clients/cli/bin/astryx.mjs +6 -9
  314. package/clients/cli/build-id.generated.json +1 -1
  315. package/clients/cli/commands/component.doc.mjs +1 -1
  316. package/clients/cli/commands/component.mjs +22 -3
  317. package/clients/cli/commands/discover.mjs +70 -3
  318. package/clients/cli/commands/docs.doc.mjs +7 -1
  319. package/clients/cli/commands/docs.mjs +44 -6
  320. package/clients/cli/commands/doctor.mjs +84 -16
  321. package/clients/cli/commands/experimental/render.mjs +42 -1
  322. package/clients/cli/commands/experimental/theme.mjs +1032 -134
  323. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  324. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  325. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +87 -1
  326. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +10 -3
  327. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  328. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +2 -2
  329. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  330. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  331. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +2 -2
  332. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +2 -2
  333. package/clients/cli/commands/experimental-theme-preview.doc.mjs +2 -1
  334. package/clients/cli/commands/experimental-theme-remove.doc.mjs +4 -4
  335. package/clients/cli/commands/experimental-theme.doc.mjs +5 -1
  336. package/clients/cli/commands/search.doc.mjs +2 -1
  337. package/clients/cli/commands/search.mjs +6 -1
  338. package/clients/cli/commands/template.doc.mjs +1 -1
  339. package/clients/cli/commands/template.mjs +15 -2
  340. package/clients/cli/commands/theme-add.doc.mjs +1 -1
  341. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  342. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  343. package/clients/cli/commands/theme-remove.doc.mjs +13 -5
  344. package/clients/cli/commands/theme.doc.mjs +1 -1
  345. package/clients/cli/commands/theme.mjs +849 -441
  346. package/clients/cli/commands/upgrade.mjs +46 -8
  347. package/clients/cli/index.mjs +9 -19
  348. package/clients/cli/lib/cli-error.mjs +2 -1
  349. package/clients/cli/lib/component-format.mjs +205 -98
  350. package/clients/cli/lib/hook-format.mjs +9 -19
  351. package/clients/cli/lib/json-shim.mjs +265 -29
  352. package/clients/cli/lib/manifest.mjs +3 -2
  353. package/clients/cli/lib/stray-option.mjs +478 -0
  354. package/clients/cli/lib/unknown-command.mjs +353 -0
  355. package/clients/cli/manifest.generated.json +1 -1
  356. package/foundation/agent-docs/agent-docs.mjs +1 -1
  357. package/foundation/config/project.d.mts +8 -0
  358. package/foundation/config/project.mjs +26 -29
  359. package/foundation/config/theme-state.d.mts +31 -2
  360. package/foundation/config/theme-state.mjs +140 -8
  361. package/foundation/discovery/authoring-self-docs.mjs +1 -0
  362. package/foundation/discovery/cli-self-doc-names.d.mts +13 -0
  363. package/foundation/discovery/cli-self-doc-names.mjs +51 -0
  364. package/foundation/discovery/cli-self-docs.d.mts +0 -2
  365. package/foundation/discovery/cli-self-docs.mjs +2 -15
  366. package/foundation/discovery/component-discovery.d.mts +11 -0
  367. package/foundation/discovery/component-discovery.mjs +59 -10
  368. package/foundation/discovery/component-replacement.mjs +130 -1
  369. package/foundation/discovery/copied-passages.mjs +2 -1
  370. package/foundation/discovery/core-component-docs.d.mts +29 -0
  371. package/foundation/discovery/core-component-docs.mjs +83 -0
  372. package/foundation/discovery/core-theme-facts.d.mts +70 -0
  373. package/foundation/discovery/core-theme-facts.mjs +384 -0
  374. package/foundation/discovery/doc-types.mjs +4 -3
  375. package/foundation/discovery/docs-discovery.d.mts +66 -9
  376. package/foundation/discovery/docs-discovery.mjs +126 -60
  377. package/foundation/discovery/entry-name-files.d.mts +106 -0
  378. package/foundation/discovery/entry-name-files.mjs +354 -0
  379. package/foundation/discovery/hook-discovery.d.mts +18 -2
  380. package/foundation/discovery/hook-discovery.mjs +93 -42
  381. package/foundation/discovery/icon-definition-discovery.mjs +2 -1
  382. package/foundation/discovery/icon-set-checks.mjs +2 -1
  383. package/foundation/discovery/icon-set-discovery.mjs +2 -1
  384. package/foundation/discovery/integration-component-views.d.mts +15 -0
  385. package/foundation/discovery/integration-component-views.mjs +91 -0
  386. package/foundation/discovery/integration-doc-files.mjs +2 -1
  387. package/foundation/discovery/module-exports.d.mts +26 -1
  388. package/foundation/discovery/module-exports.mjs +114 -40
  389. package/foundation/discovery/name-roots.d.mts +38 -0
  390. package/foundation/discovery/name-roots.mjs +108 -0
  391. package/foundation/discovery/next-routes.d.mts +48 -0
  392. package/foundation/discovery/next-routes.mjs +181 -0
  393. package/foundation/discovery/package-exports.d.mts +10 -0
  394. package/foundation/discovery/package-exports.mjs +56 -3
  395. package/foundation/discovery/prop-drift.mjs +9 -9
  396. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  397. package/foundation/discovery/runner-allowlist.mjs +2 -0
  398. package/foundation/discovery/stored-component-list.d.mts +43 -0
  399. package/foundation/discovery/stored-component-list.mjs +90 -0
  400. package/foundation/discovery/stored-search-catalog.d.mts +115 -0
  401. package/foundation/discovery/stored-search-catalog.mjs +297 -0
  402. package/foundation/discovery/stored-self-audit.d.mts +26 -10
  403. package/foundation/discovery/stored-self-audit.mjs +40 -18
  404. package/foundation/discovery/template-adapter.d.mts +49 -29
  405. package/foundation/discovery/template-adapter.mjs +89 -99
  406. package/foundation/discovery/template-destination.d.mts +28 -0
  407. package/foundation/discovery/template-destination.mjs +104 -0
  408. package/foundation/discovery/template-icons.mjs +2 -1
  409. package/foundation/discovery/template-ids.d.mts +69 -0
  410. package/foundation/discovery/template-ids.mjs +199 -0
  411. package/foundation/discovery/theme-discovery.d.mts +12 -0
  412. package/foundation/discovery/theme-discovery.mjs +34 -4
  413. package/foundation/discovery/theme-imports.d.mts +24 -0
  414. package/foundation/discovery/theme-imports.mjs +61 -4
  415. package/foundation/discovery/theming-targets.d.mts +13 -5
  416. package/foundation/discovery/theming-targets.mjs +41 -47
  417. package/foundation/doc-compiler/generated-levels.d.mts +43 -0
  418. package/foundation/doc-compiler/generated-levels.mjs +72 -0
  419. package/foundation/doc-compiler/import.mjs +7 -1
  420. package/foundation/doc-compiler/inputs.mjs +3 -2
  421. package/foundation/doc-compiler/literal-doc.d.mts +12 -0
  422. package/foundation/doc-compiler/literal-doc.mjs +322 -0
  423. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  424. package/foundation/doc-compiler/stored-docs.d.mts +29 -0
  425. package/foundation/doc-compiler/stored-docs.mjs +63 -1
  426. package/foundation/doc-compiler/tree.d.mts +4 -84
  427. package/foundation/doc-compiler/tree.mjs +4 -62
  428. package/foundation/env/semver.mjs +3 -1
  429. package/foundation/fonts/font-stylesheet.d.mts +46 -0
  430. package/foundation/fonts/font-stylesheet.mjs +173 -0
  431. package/foundation/fs/cache-eviction.d.mts +21 -0
  432. package/foundation/fs/cache-eviction.mjs +73 -0
  433. package/foundation/fs/exact-codec.d.mts +12 -2
  434. package/foundation/fs/exact-codec.mjs +23 -6
  435. package/foundation/fs/file-protection.mjs +16 -5
  436. package/foundation/fs/gather-cache.d.mts +94 -4
  437. package/foundation/fs/gather-cache.mjs +671 -106
  438. package/foundation/fs/glob.d.mts +16 -0
  439. package/foundation/fs/glob.mjs +105 -0
  440. package/foundation/fs/jiti-cache.d.mts +19 -1
  441. package/foundation/fs/jiti-cache.mjs +130 -6
  442. package/foundation/fs/kept-tree.d.mts +80 -0
  443. package/foundation/fs/kept-tree.mjs +240 -0
  444. package/foundation/fs/listing-cache.d.mts +7 -0
  445. package/foundation/fs/listing-cache.mjs +10 -0
  446. package/foundation/fs/module-loader.d.mts +24 -2
  447. package/foundation/fs/module-loader.mjs +94 -21
  448. package/foundation/fs/path-safety.d.mts +11 -2
  449. package/foundation/fs/path-safety.mjs +108 -18
  450. package/foundation/fs/paths.d.mts +18 -0
  451. package/foundation/fs/paths.mjs +15 -2
  452. package/foundation/fs/read-record.d.mts +56 -7
  453. package/foundation/fs/read-record.mjs +280 -56
  454. package/foundation/fs/regular-file.d.mts +29 -0
  455. package/foundation/fs/regular-file.mjs +77 -0
  456. package/foundation/fs/stop-cleanup.d.mts +12 -0
  457. package/foundation/fs/stop-cleanup.mjs +66 -0
  458. package/foundation/identity/provider-identity.d.mts +6 -0
  459. package/foundation/identity/provider-identity.mjs +10 -1
  460. package/foundation/integrations/contribution-inventory.mjs +4 -3
  461. package/foundation/integrations/example-code.d.mts +63 -0
  462. package/foundation/integrations/example-code.mjs +416 -0
  463. package/foundation/integrations/integrations.d.mts +23 -1
  464. package/foundation/integrations/integrations.mjs +18 -1
  465. package/foundation/integrations/pack-state.d.mts +75 -0
  466. package/foundation/integrations/pack-state.mjs +314 -0
  467. package/foundation/integrations/public-imports.d.mts +9 -0
  468. package/foundation/integrations/public-imports.mjs +3 -2
  469. package/foundation/integrations/shipped-imports.d.mts +122 -0
  470. package/foundation/integrations/shipped-imports.mjs +497 -0
  471. package/foundation/integrations/validate-contributions.d.mts +0 -17
  472. package/foundation/integrations/validate-contributions.mjs +59 -333
  473. package/foundation/render/assets.mjs +52 -7
  474. package/foundation/render/charts.d.mts +78 -27
  475. package/foundation/render/charts.mjs +266 -90
  476. package/foundation/render/embedded-files.d.mts +6 -0
  477. package/foundation/render/embedded-files.mjs +25 -5
  478. package/foundation/render/embedded-imports.d.mts +70 -7
  479. package/foundation/render/embedded-imports.mjs +132 -41
  480. package/foundation/render/file-header.d.mts +66 -0
  481. package/foundation/render/file-header.mjs +118 -0
  482. package/foundation/render/host-answer.d.mts +18 -0
  483. package/foundation/render/host-answer.mjs +46 -0
  484. package/foundation/render/host-exit.d.mts +1 -0
  485. package/foundation/render/host-exit.mjs +6 -1
  486. package/foundation/render/html-reader.d.mts +55 -2
  487. package/foundation/render/html-reader.mjs +145 -26
  488. package/foundation/render/layers.d.mts +30 -0
  489. package/foundation/render/layers.mjs +158 -0
  490. package/foundation/render/markup-edits.d.mts +57 -0
  491. package/foundation/render/markup-edits.mjs +182 -0
  492. package/foundation/render/offline.d.mts +32 -0
  493. package/foundation/render/offline.mjs +56 -0
  494. package/foundation/render/page-host.mjs +29 -12
  495. package/foundation/render/page-worker.mjs +354 -21
  496. package/foundation/render/picture-chrome.d.mts +4 -0
  497. package/foundation/render/picture-chrome.mjs +192 -0
  498. package/foundation/render/picture-playwright.d.mts +4 -0
  499. package/foundation/render/picture-playwright.mjs +46 -0
  500. package/foundation/render/rebuild.mjs +2 -1
  501. package/foundation/render/render-page.d.mts +79 -5
  502. package/foundation/render/render-page.mjs +735 -109
  503. package/foundation/render/source-block.d.mts +85 -6
  504. package/foundation/render/source-block.mjs +211 -20
  505. package/foundation/render/ts-paths.d.mts +69 -6
  506. package/foundation/render/ts-paths.mjs +326 -40
  507. package/foundation/response/error-codes.d.mts +3 -1
  508. package/foundation/response/error-codes.d.ts +1 -0
  509. package/foundation/response/error-codes.doc.mjs +12 -1
  510. package/foundation/response/error-codes.mjs +11 -1
  511. package/foundation/response/response-types.doc.mjs +6 -6
  512. package/foundation/suggest/name-index.d.mts +148 -0
  513. package/foundation/suggest/name-index.mjs +317 -0
  514. package/foundation/suggest/other-command.d.mts +140 -0
  515. package/foundation/suggest/other-command.mjs +756 -0
  516. package/foundation/text/compare-text.d.mts +14 -0
  517. package/foundation/text/compare-text.mjs +68 -0
  518. package/foundation/text/css-escape.d.mts +18 -0
  519. package/foundation/text/css-escape.mjs +35 -0
  520. package/foundation/text/entry-names.d.mts +14 -0
  521. package/foundation/text/entry-names.mjs +14 -0
  522. package/foundation/text/string-utils.d.mts +46 -6
  523. package/foundation/text/string-utils.mjs +118 -20
  524. package/foundation/text/suggest-order.d.mts +47 -4
  525. package/foundation/text/suggest-order.mjs +174 -5
  526. package/foundation/xle/browser.d.mts +2 -2
  527. package/foundation/xle/expand.mjs +2 -1
  528. package/host/index.mjs +8 -6
  529. package/package.json +7 -6
@@ -8,26 +8,46 @@
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';
15
17
  import {
18
+ MODULE_EXTENSIONS,
16
19
  PAGE_EXTENSIONS,
17
20
  RenderError,
18
21
  renderPage,
19
22
  } from '../../foundation/render/render-page.mjs';
20
- import {readSourceBlock} from '../../foundation/render/source-block.mjs';
23
+ import {
24
+ RENDER_FORMAT,
25
+ asParsed,
26
+ readSourceBlock,
27
+ recordedText,
28
+ renderedHeadOf,
29
+ renderedMarkupOf,
30
+ sha256,
31
+ } from '../../foundation/render/source-block.mjs';
32
+ import {decode} from '../../foundation/render/html-reader.mjs';
33
+ import {clip, locate, textEdits, textRuns} from '../../foundation/render/markup-edits.mjs';
34
+ import {isPackageName} from '../../foundation/identity/provider-identity.mjs';
35
+ import {cliCommand} from '../../foundation/render/file-header.mjs';
36
+ import {shellArg} from '../../foundation/text/shell-arg.mjs';
37
+ import {isValidSemver} from '../../foundation/env/semver.mjs';
21
38
  import {embeddedPathProblem, runnerPicksUp} from '../../foundation/render/embedded-files.mjs';
22
39
  import {isAssetBytes, isAssetPath} from '../../foundation/render/assets.mjs';
23
40
  import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
41
+ import {publishNewFile} from '../../foundation/fs/publish-file.mjs';
24
42
  import {reachableFiles, receivingAliases} from '../../foundation/render/embedded-imports.mjs';
43
+ import {pathsHomeFor} from '../../foundation/render/ts-paths.mjs';
25
44
  import {isAstryxMarkup} from '../../foundation/render/html-reader.mjs';
26
45
  import {rebuildPage} from '../../foundation/render/rebuild.mjs';
27
46
  import {cliVersion} from '../../foundation/integrations/cli-peer-version.mjs';
28
47
  import {assertWithin, PathSafetyError} from '../../foundation/fs/path-safety.mjs';
29
- import {requireCoreDir} from '../../foundation/fs/paths.mjs';
48
+ import {climbsOut, findPackageRoot, isInside as liesInside, requireCoreDir} from '../../foundation/fs/paths.mjs';
30
49
  import {runChoice} from '../../foundation/release/run-context.mjs';
50
+ import {isAlive, pidSpace} from '../../foundation/release/cache.mjs';
31
51
  import {isServedPackage} from '../../foundation/render/served-packages.mjs';
32
52
  import {hostedRun, recordResolved} from '../../foundation/runtime/package-root.mjs';
33
53
 
@@ -36,28 +56,62 @@ export {PAGE_EXTENSIONS, embeddedPathProblem};
36
56
  /** @param {string} cwd @param {string} file */
37
57
  const shown = (cwd, file) => {
38
58
  const rel = path.relative(cwd, file);
39
- return rel && !rel.startsWith('..') && !path.isAbsolute(rel)
59
+ return rel && !climbsOut(rel) && !path.isAbsolute(rel)
40
60
  ? rel.split(path.sep).join('/')
41
61
  : file;
42
62
  };
43
63
 
64
+ /** Why a file cannot be read, in a few words, by its errno. */
65
+ const READ_FAILURES = {EACCES: 'no permission', EPERM: 'no permission', EISDIR: 'it is a folder'};
66
+
44
67
  /**
45
- * Read a file the caller named, or throw ERR_FILE_NOT_FOUND.
68
+ * The error for an input the file system would not give: ERR_FILE_NOT_FOUND
69
+ * when nothing is there, ERR_READ_FAILED with the errno and its reason
70
+ * otherwise.
71
+ * @param {string} file absolute
72
+ * @param {string} cwd
73
+ * @param {unknown} e what the file system threw
74
+ */
75
+ function inputFailure(file, cwd, e) {
76
+ const errno = /** @type {NodeJS.ErrnoException} */ (e).code;
77
+ if (errno === 'ENOENT' || errno === 'ENOTDIR') {
78
+ return new AstryxError(`${shown(cwd, file)} does not exist`, [], ERROR_CODES.ERR_FILE_NOT_FOUND);
79
+ }
80
+ const why = READ_FAILURES[/** @type {keyof typeof READ_FAILURES} */ (errno)];
81
+ return new AstryxError(
82
+ `${shown(cwd, file)} cannot be read${errno ? ` (${errno}${why ? `: ${why}` : ''})` : ''}; nothing was written.`,
83
+ [],
84
+ ERROR_CODES.ERR_READ_FAILED,
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Read a file the caller named. A folder, a pipe or any other entry that is
90
+ * not a regular file is refused before it is opened, so nothing waits on it.
46
91
  * @param {string} file absolute
47
92
  * @param {string} cwd
48
93
  * @returns {Buffer}
49
94
  */
50
95
  function readInput(file, cwd) {
96
+ /** @type {fs.Stats} */
97
+ let stat;
51
98
  try {
52
- if (!fs.statSync(file).isFile()) throw new Error('not a file');
53
- return fs.readFileSync(file);
54
- } catch {
99
+ stat = fs.statSync(file);
100
+ } catch (e) {
101
+ throw inputFailure(file, cwd, e);
102
+ }
103
+ if (!stat.isFile()) {
55
104
  throw new AstryxError(
56
- `${shown(cwd, file)} does not exist`,
105
+ `${shown(cwd, file)} cannot be read (${stat.isDirectory() ? 'it is a folder' : 'it is not a regular file'}); nothing was written.`,
57
106
  [],
58
- ERROR_CODES.ERR_FILE_NOT_FOUND,
107
+ ERROR_CODES.ERR_READ_FAILED,
59
108
  );
60
109
  }
110
+ try {
111
+ return fs.readFileSync(file);
112
+ } catch (e) {
113
+ throw inputFailure(file, cwd, e);
114
+ }
61
115
  }
62
116
 
63
117
  /**
@@ -99,15 +153,25 @@ function confined(file, cwd, what) {
99
153
  }
100
154
  }
101
155
 
156
+ /**
157
+ * Whether a file is inside a folder (not the folder itself).
158
+ * @param {string} file absolute
159
+ * @param {string | null} folder absolute
160
+ */
161
+ const isInside = (file, folder) => Boolean(folder) && liesInside(file, /** @type {string} */ (folder));
162
+
102
163
  /**
103
164
  * Refuse, before anything is written, a write that reaches through a
104
165
  * symbolic link, and the replacement of an existing file the project
105
166
  * protects (generated, vendored, ignored, a dependency or version-control
106
- * metadata; spec:AST-040 FR2), even with --overwrite.
167
+ * metadata; spec:AST-040 FR2), even with --overwrite. A file inside the new
168
+ * folder a restore creates replaces nothing: that folder takes its name in
169
+ * one step, after every check.
107
170
  * @param {string[]} files absolute
108
171
  * @param {string} cwd
172
+ * @param {string | null} [newFolder] the new folder a restore creates, if any
109
173
  */
110
- function refuseProtected(files, cwd) {
174
+ function refuseProtected(files, cwd, newFolder = null) {
111
175
  for (const file of files) {
112
176
  let current = cwd;
113
177
  for (const part of path.relative(cwd, file).split(path.sep)) {
@@ -127,7 +191,7 @@ function refuseProtected(files, cwd) {
127
191
  }
128
192
  }
129
193
  }
130
- const existing = files.filter(file => fs.existsSync(file));
194
+ const existing = files.filter(file => !isInside(file, newFolder) && fs.existsSync(file));
131
195
  if (existing.length === 0) return;
132
196
  /** @type {ReturnType<typeof createFileProtectionResolver>} */
133
197
  let resolver;
@@ -154,76 +218,192 @@ function refuseProtected(files, cwd) {
154
218
  }
155
219
 
156
220
  /**
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
221
+ * The process space runs here share: this computer's name and its process-ID
222
+ * namespace (a container or sandbox on one computer has its own), in which a
223
+ * process id names one process.
224
+ */
225
+ const PROCESS_SPACE = `${os.hostname()}-${/\[(\d+)\]/.exec(pidSpace() ?? '')?.[1] ?? 'x'}`;
226
+
227
+ /**
228
+ * The start of the hidden temporary names a run in this process space gives
229
+ * a file or folder beside its target, before the run's process id.
230
+ * @param {string} target absolute
231
+ */
232
+ const temporaryPrefix = target => `.${path.basename(target)}.tmp-${PROCESS_SPACE}-`;
233
+
234
+ /**
235
+ * A hidden temporary name beside a file or folder, as the CLI's other writers
236
+ * name theirs, with this process space and this process's id, so a later run
237
+ * can tell when the run that made it is gone.
238
+ * @param {string} target absolute
239
+ */
240
+ const temporaryBeside = target => path.join(path.dirname(target), `${temporaryPrefix(target)}${process.pid}-${randomUUID()}`);
241
+
242
+ /**
243
+ * Remove the temporaries that runs in this process space left beside a
244
+ * target when they stopped between their write and their rename: those whose
245
+ * process no longer runs. A temporary of a run that still runs, or of a run
246
+ * in another process space (another computer, container or sandbox, whose
247
+ * processes cannot be seen from here), stays.
248
+ * @param {string} target absolute
249
+ */
250
+ function removeStaleTemporaries(target) {
251
+ const prefix = temporaryPrefix(target);
252
+ let names;
253
+ try {
254
+ names = fs.readdirSync(path.dirname(target));
255
+ } catch {
256
+ return;
257
+ }
258
+ for (const name of names) {
259
+ if (!name.startsWith(prefix)) continue;
260
+ const pid = /^(\d+)-[0-9a-f-]{36}$/.exec(name.slice(prefix.length))?.[1];
261
+ if (pid === undefined || isAlive(Number(pid))) continue;
262
+ fs.rmSync(path.join(path.dirname(target), name), {recursive: true, force: true});
263
+ }
264
+ }
265
+
266
+ /**
267
+ * The topmost folder on the way to `file` that does not exist yet, or null
268
+ * when the file's own folder exists.
269
+ * @param {string} file absolute
270
+ * @returns {string | null}
271
+ */
272
+ function newFolderOf(file) {
273
+ /** @type {string | null} */
274
+ let top = null;
275
+ for (let d = path.dirname(file); !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) top = d;
276
+ return top;
277
+ }
278
+
279
+ /**
280
+ * Why a write failed, in terms of the target, never the hidden temporary
281
+ * file or folder beside it: the folder that would not take the temporary,
282
+ * or the error a file inside the temporary folder met.
283
+ * @param {unknown} e
284
+ * @param {string | null} temporary the temporary file or folder
285
+ * @param {string} folder the folder that holds the target
162
286
  * @param {string} cwd
163
287
  */
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 = '';
288
+ function writeFailure(e, temporary, folder, cwd) {
289
+ const err = /** @type {NodeJS.ErrnoException} */ (e);
290
+ if (temporary && err?.path === temporary && (err.syscall === 'open' || err.syscall === 'mkdir')) {
291
+ return `${shown(cwd, folder)} does not take a new file (${err.code ?? err.message})`;
292
+ }
293
+ if (temporary && err?.path?.startsWith(temporary + path.sep)) return err.code ?? err.message;
294
+ return String(err?.message ?? e);
295
+ }
296
+
297
+ /**
298
+ * Write one file in one step: its bytes go to a temporary file beside it,
299
+ * which then takes its name. A reader, or another run at the same time, sees
300
+ * the old whole file or the new one, never part of one, and a run stopped
301
+ * part-way leaves the old file as it was; the next write to the file removes
302
+ * the temporary that run left.
303
+ * @param {string} file absolute
304
+ * @param {string | Buffer} content
305
+ * @param {string} cwd
306
+ * @param {{replace: boolean, mode?: number}} options `replace`: an existing
307
+ * file may be replaced; without it, a file that appeared since the checks
308
+ * stays. `mode`: the permission bits the file gets
309
+ */
310
+ function writeOutput(file, content, cwd, {replace, mode}) {
311
+ /** @type {string | null} */
312
+ let temporary = null;
180
313
  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});
314
+ fs.mkdirSync(path.dirname(file), {recursive: true});
315
+ /** @type {fs.Stats | null} */
316
+ let existing = null;
317
+ try {
318
+ existing = fs.statSync(file);
319
+ } catch {
320
+ // No file there yet.
193
321
  }
194
- for (const {temp, file} of staged) {
195
- current = file;
196
- fs.renameSync(temp, file);
322
+ if (existing?.isDirectory()) {
323
+ throw Object.assign(new Error(`EISDIR: illegal operation on a directory, open '${file}'`), {code: 'EISDIR'});
197
324
  }
325
+ removeStaleTemporaries(file);
326
+ temporary = temporaryBeside(file);
327
+ fs.writeFileSync(temporary, content, {flag: 'wx'});
328
+ if (mode !== undefined) fs.chmodSync(temporary, mode);
329
+ if (replace) fs.renameSync(temporary, file);
330
+ else publishNewFile(temporary, file);
198
331
  } catch (e) {
199
- undo();
332
+ if (!replace && /** @type {any} */ (e)?.code === 'EEXIST') {
333
+ throw new AstryxError(
334
+ `${shown(cwd, file)} appeared while this ran; nothing was written. Pass --overwrite to replace it.`,
335
+ [],
336
+ ERROR_CODES.ERR_FILE_EXISTS,
337
+ );
338
+ }
200
339
  throw new AstryxError(
201
- `Could not write ${shown(cwd, current)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
340
+ `Could not write ${shown(cwd, file)}: ${writeFailure(e, temporary, path.dirname(file), cwd)}; nothing was written.`,
202
341
  [],
203
342
  ERROR_CODES.ERR_WRITE_FAILED,
204
343
  );
344
+ } finally {
345
+ if (temporary) fs.rmSync(temporary, {force: true});
205
346
  }
206
347
  }
207
348
 
208
349
  /**
209
- * Write one file, creating its folder.
210
- * @param {string} file absolute
211
- * @param {string | Buffer} content
350
+ * Write a new folder and every file in it, all or nothing, in one step: the
351
+ * files go into a temporary folder beside it, which then takes the folder's
352
+ * name. A run stopped part-way leaves no folder behind, so running it again
353
+ * works (and removes the temporary folder that run left), and of two runs
354
+ * that pick the same name, one gets it and the other learns that it is
355
+ * taken.
356
+ * @param {string} folder absolute; does not exist yet
357
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets inside `folder`
212
358
  * @param {string} cwd
359
+ * @returns {boolean} false when the folder appeared before this run could take its name
213
360
  */
214
- function writeOutput(file, content, cwd) {
361
+ function writeFolder(folder, writes, cwd) {
362
+ removeStaleTemporaries(folder);
363
+ const staging = temporaryBeside(folder);
364
+ let current = folder;
215
365
  try {
216
- fs.mkdirSync(path.dirname(file), {recursive: true});
217
- fs.writeFileSync(file, content);
366
+ for (const w of writes) {
367
+ current = w.file;
368
+ const staged = path.join(staging, path.relative(folder, w.file));
369
+ fs.mkdirSync(path.dirname(staged), {recursive: true});
370
+ fs.writeFileSync(staged, w.bytes, {flag: 'wx'});
371
+ }
372
+ current = folder;
373
+ try {
374
+ fs.renameSync(staging, folder);
375
+ } catch (e) {
376
+ if (fs.existsSync(folder)) return false;
377
+ throw e;
378
+ }
379
+ return true;
218
380
  } catch (e) {
219
381
  throw new AstryxError(
220
- `Could not write ${shown(cwd, file)}: ${/** @type {Error} */ (e).message}`,
382
+ `Could not write ${shown(cwd, current)}: ${writeFailure(e, staging, path.dirname(folder), cwd)}; nothing was written.`,
221
383
  [],
222
384
  ERROR_CODES.ERR_WRITE_FAILED,
223
385
  );
386
+ } finally {
387
+ fs.rmSync(staging, {recursive: true, force: true});
224
388
  }
225
389
  }
226
390
 
391
+ /**
392
+ * Write a restore's files: into the new folder that holds them all, in one
393
+ * step, or, when the page goes into a folder that exists (the only file a
394
+ * restore writes there), the page alone.
395
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets, the page first
396
+ * @param {string | null} folder the new folder that holds every file, or null
397
+ * @param {string} cwd
398
+ * @param {boolean} overwrite whether an existing page may be replaced
399
+ * @returns {boolean} false when the new folder appeared before this run could take its name
400
+ */
401
+ function writeRestore(writes, folder, cwd, overwrite) {
402
+ if (folder) return writeFolder(folder, writes, cwd);
403
+ writeOutput(writes[0].file, writes[0].bytes, cwd, {replace: overwrite});
404
+ return true;
405
+ }
406
+
227
407
  /** @param {unknown} e */
228
408
  function asAstryxError(e) {
229
409
  if (e instanceof RenderError) {
@@ -278,7 +458,7 @@ export async function renderToFile({cwd, input, output, title}) {
278
458
  try {
279
459
  const set = servedSet(input);
280
460
  try {
281
- page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null});
461
+ page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null, output, cwd});
282
462
  } catch (e) {
283
463
  // A page that needs the Core the CLI could not obtain says why.
284
464
  const missing = /** @type {any} */ (e)?.code === 'ERR_RENDER_MISSING_DEPENDENCY' ? /** @type {any} */ (e).detail?.package : null;
@@ -312,7 +492,21 @@ export async function renderToFile({cwd, input, output, title}) {
312
492
  ERROR_CODES.ERR_FILE_EXISTS,
313
493
  );
314
494
  }
315
- writeOutput(output, page.html, cwd);
495
+ // A render never replaces an HTML file this user cannot write, and the file
496
+ // it replaces keeps its permission bits.
497
+ const existingMode = fs.statSync(output, {throwIfNoEntry: false})?.mode;
498
+ if (existingMode !== undefined) {
499
+ try {
500
+ fs.accessSync(output, fs.constants.W_OK);
501
+ } catch (e) {
502
+ throw new AstryxError(
503
+ `Could not write ${shown(cwd, output)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
504
+ [],
505
+ ERROR_CODES.ERR_WRITE_FAILED,
506
+ );
507
+ }
508
+ }
509
+ writeOutput(output, page.html, cwd, {replace: true, ...(existingMode === undefined ? {} : {mode: existingMode & 0o7777})});
316
510
  return {
317
511
  input: shown(cwd, input),
318
512
  output: shown(cwd, output),
@@ -361,19 +555,158 @@ function refuseRunnable(files, cwd, input) {
361
555
  }
362
556
  }
363
557
 
558
+ /**
559
+ * The `paths` entry that lets an alias import find the file it came back
560
+ * as, from the folder the config resolves targets from: the part of the
561
+ * import that the file's path ends with becomes the `*`
562
+ * (`@/components/Header` in `report-restored/components/` gives `@/*` and
563
+ * `./report-restored/*`), else the import maps to its file.
564
+ * @param {string} spec
565
+ * @param {string} file absolute
566
+ * @param {string} base absolute
567
+ * @returns {[string, string]}
568
+ */
569
+ function aliasEntry(spec, file, base) {
570
+ /** @param {string} p */
571
+ const fromBase = p => {
572
+ const rel = path.relative(base, p).split(path.sep).join('/');
573
+ return climbsOut(rel) ? rel : `./${rel}`;
574
+ };
575
+ const named = spec.split('/');
576
+ let held = path.relative(base, file).split(path.sep).join('/').replace(/\.[^./]+$/, '').split('/');
577
+ if (held.at(-1) === 'index' && named.at(-1) !== 'index') held = held.slice(0, -1);
578
+ let same = 0;
579
+ while (same < named.length - 1 && same < held.length && named[named.length - 1 - same] === held[held.length - 1 - same]) same++;
580
+ if (same === 0) return [spec, fromBase(file)];
581
+ const folder = fromBase(path.join(base, ...held.slice(0, held.length - same)));
582
+ return [`${named.slice(0, named.length - same).join('/')}/*`, folder === './' ? './*' : `${folder}/*`];
583
+ }
584
+
585
+ /**
586
+ * What a restore tells about the alias imports no alias of the receiving
587
+ * project names: the config the `paths` belong in (the one TypeScript reads
588
+ * for the page, else a new tsconfig.json at the project's root or the
589
+ * current folder), the whole `paths` it needs (its current entries and the
590
+ * new ones), and each import with its file.
591
+ * @param {{spec: string, file: string}[]} unaliased
592
+ * @param {string} page absolute: where the page lands
593
+ * @param {string} cwd
594
+ */
595
+ function aliasedResult(unaliased, page, cwd) {
596
+ const home = pathsHomeFor(page, findPackageRoot(path.dirname(page)) ?? cwd);
597
+ /** @param {string} p */
598
+ const fromBase = p => {
599
+ const rel = path.relative(home.base, p).split(path.sep).join('/');
600
+ return climbsOut(rel) ? rel : `./${rel}`;
601
+ };
602
+ // The whole `paths` the config needs: the entries it has now (a `paths` of
603
+ // its own replaces inherited ones), then every target the imports need.
604
+ /** @type {Record<string, string[]>} */
605
+ const paths = {};
606
+ for (const pattern of home.current) paths[pattern.key] = pattern.targets.map(fromBase);
607
+ const entries = unaliased.map(({spec, file}) => aliasEntry(spec, file, home.base));
608
+ for (const [key, target] of entries) paths[key] = [...new Set([...(paths[key] ?? []), target])];
609
+ // TypeScript tries a pattern's targets in turn, so an import through a
610
+ // pattern with more than one target could reach another file first; each
611
+ // such import gets an entry of its own, which TypeScript reads before any
612
+ // pattern.
613
+ unaliased.forEach(({spec, file}, i) => {
614
+ const [key] = entries[i];
615
+ if (key !== spec && paths[key].length > 1) paths[spec] = [fromBase(file)];
616
+ });
617
+ return {
618
+ config: shown(cwd, home.config),
619
+ paths,
620
+ imports: unaliased.map(({spec, file}) => ({import: spec, file: shown(cwd, file)})),
621
+ };
622
+ }
623
+
364
624
  /**
365
625
  * The new folder a restore without --out writes into: beside the HTML file,
366
626
  * named after it (`report.html` gives `report-restored/`, then
367
- * `report-restored-2/` when that exists).
627
+ * `report-restored-2/` when that exists). A name already taken is never
628
+ * written again, so a temporary folder a stopped run left for it goes.
368
629
  * @param {string} input absolute
369
630
  */
370
631
  function restoreFolder(input) {
371
632
  const stem = path.basename(input).replace(/\.[^.]+$/, '');
372
633
  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}`);
634
+ for (let n = 2; fs.existsSync(folder); n++) {
635
+ removeStaleTemporaries(folder);
636
+ folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
637
+ }
374
638
  return folder;
375
639
  }
376
640
 
641
+ /**
642
+ * The version of the CLI that rendered a file: the one its embedded source
643
+ * records, else the one its generator meta names.
644
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
645
+ * @param {string} html
646
+ * @returns {string | null}
647
+ */
648
+ function renderedByOf(source, html) {
649
+ const named = source.cli ?? /<meta name="generator" content="Astryx ([^"<>]+)">/.exec(html.slice(0, 4096))?.[1];
650
+ return isValidSemver(named) ? /** @type {string} */ (named) : null;
651
+ }
652
+
653
+ /**
654
+ * The packages a file says its page rendered with, as `name@version`, when
655
+ * it records them.
656
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
657
+ * @returns {string[] | null}
658
+ */
659
+ function packagesOf(source) {
660
+ const recorded = source.packages;
661
+ if (!recorded || typeof recorded !== 'object' || Array.isArray(recorded)) return null;
662
+ return Object.entries(recorded)
663
+ .filter(([name, version]) => isPackageName(name) && isValidSemver(version))
664
+ .map(([name, version]) => `${name}@${version}`);
665
+ }
666
+
667
+ /**
668
+ * Whether someone changed the page after the render, for a file that records
669
+ * the page as rendered: each run of text that changed (the title first), and
670
+ * whether the styles changed. The restored source never takes these changes:
671
+ * it is the page as rendered.
672
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
673
+ * @param {string} html
674
+ * @param {{file: string, text: string}[]} texts the restored modules and JSON files, as shown to the caller
675
+ * @returns {{edited?: boolean, stylesEdited?: boolean, edits?: import('./render.type.mjs').RenderEdit[], moreEdits?: number}}
676
+ */
677
+ function pageChanges(source, html, texts) {
678
+ const recorded = source.markup;
679
+ if (!recorded || typeof recorded.sha256 !== 'string') return {};
680
+ // The page as a browser reads it, so a copy whose line ends changed on the
681
+ // way is no edit.
682
+ const markupNow = renderedMarkupOf(html);
683
+ const now = markupNow === null ? null : asParsed(markupNow);
684
+ const head = renderedHeadOf(html);
685
+ const text = recordedText(recorded);
686
+ const titleNow = head.title === null ? null : asParsed(decode(head.title));
687
+ const titleEdited = typeof text?.title === 'string' && titleNow !== asParsed(text.title);
688
+ const stylesEdited = typeof recorded.style === 'string' ? head.style === null || sha256(asParsed(head.style)) !== recorded.style : undefined;
689
+ const markupEdited = now === null || sha256(now) !== recorded.sha256;
690
+ const styles = stylesEdited === undefined ? {} : {stylesEdited};
691
+ if (!markupEdited && !titleEdited && !stylesEdited) return {edited: false, ...styles};
692
+ const {edits, more} = markupEdited ? textEdits(text?.runs ?? [], textRuns(now ?? '')) : {edits: [], more: 0};
693
+ // A title that changed with the heading it comes from is one change, not two.
694
+ const titleEdit = {was: /** @type {string} */ (text?.title), now: titleNow};
695
+ const titleAgain = edits.some(edit => edit.was === titleEdit.was && edit.now === titleEdit.now);
696
+ const all = [...(titleEdited && !titleAgain ? [titleEdit] : []), ...edits];
697
+ return {
698
+ edited: true,
699
+ ...styles,
700
+ // Each change is found in the source by its whole text, then cut to show.
701
+ edits: all.map(edit => ({
702
+ was: edit.was === null ? null : clip(edit.was),
703
+ now: edit.now === null ? null : clip(edit.now),
704
+ ...((edit.was && locate(edit.was, texts)) || {}),
705
+ })),
706
+ ...(more > 0 ? {moreEdits: more} : {}),
707
+ };
708
+ }
709
+
377
710
  /**
378
711
  * Turn a rendered HTML file back into a page module.
379
712
  * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
@@ -382,6 +715,17 @@ function restoreFolder(input) {
382
715
  export function reverseToFile({cwd, input, output, overwrite}) {
383
716
  const html = readInput(input, cwd).toString('utf8');
384
717
  const block = readSourceBlock(html);
718
+ const rendered = /<meta name="generator" content="Astryx[ "]/.test(html);
719
+ // A merge that left conflict markers in an Astryx page holds two versions
720
+ // of it at once, the embedded source too: choosing one would choose for
721
+ // the user.
722
+ if ((block.found || rendered || isAstryxMarkup(html)) && /^<{7}(?: |$)/m.test(html) && /^>{7}(?: |$)/m.test(html)) {
723
+ throw new AstryxError(
724
+ `${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.`,
725
+ [],
726
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
727
+ );
728
+ }
385
729
  /** @param {string[]} files */
386
730
  const refuseExisting = files => {
387
731
  if (overwrite) return;
@@ -397,7 +741,7 @@ export function reverseToFile({cwd, input, output, overwrite}) {
397
741
  /** A page is never written as a configuration, test, spec or story file. @param {string} file */
398
742
  const refuseConfigTarget = file => {
399
743
  const rel = path.relative(cwd, file).split(path.sep).join('/');
400
- const where = rel.startsWith('..') || path.isAbsolute(rel) ? path.basename(file) : rel;
744
+ const where = climbsOut(rel) || path.isAbsolute(rel) ? path.basename(file) : rel;
401
745
  // Where the page lands must be a page module, and a name no tool takes
402
746
  // as its own (configuration, a runner's file): the same rules as any
403
747
  // file a restore writes.
@@ -410,6 +754,15 @@ export function reverseToFile({cwd, input, output, overwrite}) {
410
754
  );
411
755
  }
412
756
  };
757
+ if (block.found && 'newer' in block) {
758
+ const {format, cli} = block.newer;
759
+ const command = `${cliCommand(cli ?? 'latest')} experimental render --reverse ${shellArg(shown(cwd, input))}`;
760
+ throw new AstryxError(
761
+ `${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}`,
762
+ [{name: command, reason: cli ? 'give it back with the CLI version that wrote the file' : 'give it back with the latest CLI'}],
763
+ ERROR_CODES.ERR_RENDER_NEWER_FORMAT,
764
+ );
765
+ }
413
766
  if (block.found && 'damaged' in block) {
414
767
  throw new AstryxError(
415
768
  `${shown(cwd, input)} carries an Astryx page source, but ${block.damaged}, so it cannot be given back exactly.`,
@@ -431,126 +784,164 @@ export function reverseToFile({cwd, input, output, overwrite}) {
431
784
  );
432
785
  }
433
786
  });
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)) {
787
+ // A restore without --out picks the first folder name no folder has.
788
+ // When another run creates the new folder first, this one plans again:
789
+ // without --out it takes the next name; with --out its files go into the
790
+ // folder still new under it, or meet every check a restore into folders
791
+ // that exist meets. A folder that appears exists from then on, so every
792
+ // pass plans for a new one.
793
+ for (;;) {
794
+ // Without --out, the page and the files it imports come back into a new
795
+ // folder beside the HTML file, named after it (`report.html` gives
796
+ // `report-restored/`), with the layout they were rendered in. Nothing in
797
+ // the received file decides where in your project anything goes.
798
+ const folder = output ? null : restoreFolder(input);
799
+ const requested = output ?? path.join(/** @type {string} */ (folder), ...source.files[0].path.split('/'));
800
+ refuseConfigTarget(requested);
801
+ const seen = new Set();
802
+ for (const f of source.files) {
803
+ const key = f.path.toLowerCase();
804
+ if (seen.has(key)) {
805
+ throw new AstryxError(
806
+ `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
807
+ [],
808
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
809
+ );
810
+ }
811
+ seen.add(key);
812
+ }
813
+ // Modules, stylesheets and JSON are written only when the page reaches
814
+ // them through its own imports: one it never imports is not part of it,
815
+ // whatever its name.
816
+ const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(requested), recorded: source.aliases});
817
+ // A carried image, font or media file needs no import to be part of the
818
+ // page (it may be named in markup, a stylesheet, JSON or a computed
819
+ // path): the render's own list is the authority, so it is kept when its
820
+ // bytes are a known image, font or media format (any, whatever the
821
+ // extension), and goes where the layout puts it.
822
+ for (const f of source.files) {
823
+ if (reached.has(f.path) || !isAssetPath(f.path)) continue;
824
+ if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set(), unaliased: new Set()});
825
+ }
826
+ const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
827
+ if (stray.length > 0) {
444
828
  throw new AstryxError(
445
- `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
829
+ `${shown(cwd, input)} carries ${stray.length === 1 ? 'a file' : 'files'} the page does not reach through its imports here, 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 the page imports through a path alias comes back where this project's tsconfig.json or jsconfig.json has that alias, and anywhere when the import cannot be a package name (\`@/…\`, \`~/…\`) and the CLI that rendered the file recorded it (as this one does).`,
446
830
  [],
447
831
  ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
448
832
  );
449
833
  }
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')});
834
+ // Each file the page reaches by a relative import goes where that import
835
+ // finds it from the page's new folder, so every relative import still
836
+ // resolves wherever the page lands; a file reached through an alias goes
837
+ // where this project's alias points. Every file but the page must land
838
+ // in a folder this restore creates: a received file never adds a file to
839
+ // a folder that already exists (a server hook at the project root, a
840
+ // middleware module), so a page with neighbours comes back into a new
841
+ // folder.
842
+ const entryDir = path.posix.dirname(source.files[0].path);
843
+ const anchor = path.dirname(requested);
844
+ /** @param {string} p */
845
+ const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
846
+ // A file beside the page or elsewhere goes only into a folder this
847
+ // restore creates: never into a folder that already exists.
848
+ // The one folder every file but the page must land in: the topmost
849
+ // folder on the page's path that this restore creates. When the page's
850
+ // folder already exists there is none, so a page with neighbours comes
851
+ // back only into a new folder.
852
+ // Without --out, that is the folder this restore picked because no
853
+ // folder had its name: another run that takes the name first makes this
854
+ // one take the next.
855
+ const home = folder ?? newFolderOf(requested);
856
+ const within = (/** @type {string} */ file) => isInside(file, home);
857
+ const target = path.join(anchor, path.basename(requested));
858
+ // The alias imports no alias here names: their files come back in the
859
+ // page's own layout, and the page needs the alias to build, in the config
860
+ // TypeScript reads for it.
861
+ const unaliased = [...reached]
862
+ .flatMap(([p, r]) => [...r.unaliased].map(spec => ({spec, file: placeFrom(p)})))
863
+ .sort((a, b) => (a.spec < b.spec ? -1 : a.spec > b.spec ? 1 : 0));
864
+ const aliased = unaliased.length === 0 ? null : aliasedResult(unaliased, requested, cwd);
865
+ /** @type {{file: string, bytes: Buffer}[]} */
866
+ const writes = [];
867
+ const placed = new Set();
868
+ /** @type {string[]} */
869
+ const outside = [];
870
+ /** @type {string[]} */
871
+ const aliasedOutside = [];
872
+ source.files.forEach((f, i) => {
873
+ const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
874
+ const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
875
+ for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
876
+ if (placed.has(file)) continue;
877
+ placed.add(file);
878
+ // Every copy but the page at its target, the page's own copy that an
879
+ // alias places included, lands in the one new folder.
880
+ if (file !== target && !within(file)) (aliased ? aliasedOutside : outside).push(file);
881
+ writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
882
+ }
883
+ });
884
+ if (aliasedOutside.length > 0) {
885
+ throw new AstryxError(
886
+ `${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.`,
887
+ [],
888
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
889
+ );
515
890
  }
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
- );
891
+ if (outside.length > 0) {
892
+ const top = entryDir === '.' ? '' : `${entryDir}/`;
893
+ let fresh = 'restored';
894
+ for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
895
+ const suggestion = `--out ${shellArg(`${fresh}/${top}${path.basename(requested)}`)}`;
896
+ throw new AstryxError(
897
+ `${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}.`,
898
+ [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
899
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
900
+ );
901
+ }
902
+ writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
903
+ refuseRunnable(writes.map(w => w.file), cwd, input);
904
+ refuseExisting(writes.filter(w => !isInside(w.file, home)).map(w => w.file));
905
+ refuseProtected(writes.map(w => w.file), cwd, home);
906
+ if (!writeRestore(writes, home, cwd, overwrite)) continue;
907
+ const renderedBy = renderedByOf(source, html);
908
+ const packages = packagesOf(source);
909
+ // The files whose text a page shows: its modules and the JSON data
910
+ // they import.
911
+ const texts = writes
912
+ .filter(w => [...MODULE_EXTENSIONS, '.json'].includes(path.extname(w.file).toLowerCase()))
913
+ .map(w => ({file: shown(cwd, w.file), text: w.bytes.toString('utf8')}));
914
+ return {
915
+ input: shown(cwd, input),
916
+ mode: 'embedded',
917
+ output: shown(cwd, target),
918
+ files: writes.map(w => shown(cwd, w.file)),
919
+ // The page is byte for byte the one rendered; an import it makes that
920
+ // the file does not carry (a file a render never embeds) is named.
921
+ exact: missing.length === 0,
922
+ ...(missing.length > 0 ? {missing} : {}),
923
+ ...(aliased ? {aliased} : {}),
924
+ format: source.version,
925
+ ...(renderedBy ? {renderedBy} : {}),
926
+ ...(packages ? {packages} : {}),
927
+ ...(typeof source.title === 'string' ? {title: source.title} : {}),
928
+ ...pageChanges(source, html, texts),
929
+ };
534
930
  }
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
- };
931
+ }
932
+ // A render always ends its file with `</html>`. A file a render wrote that
933
+ // has none lost its end on the way, the embedded source with it: the
934
+ // markup left is only part of the page.
935
+ if (rendered && !/<\/html>/i.test(html)) {
936
+ throw new AstryxError(
937
+ `${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.`,
938
+ [],
939
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
940
+ );
550
941
  }
551
942
  // A file a render wrote, whose source block was taken out on the way
552
943
  // (sanitizers and editors strip <script> elements), says so.
553
- if (!isAstryxMarkup(html) && /<meta name="generator" content="Astryx[ "]/.test(html)) {
944
+ if (!isAstryxMarkup(html) && rendered) {
554
945
  throw new AstryxError(
555
946
  `${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
947
  [],
@@ -569,27 +960,32 @@ export function reverseToFile({cwd, input, output, overwrite}) {
569
960
  ERROR_CODES.ERR_RENDER_NOT_ASTRYX,
570
961
  );
571
962
  }
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
- };
963
+ // As above: a folder another run creates first exists from then on.
964
+ for (;;) {
965
+ const folder = output ? null : restoreFolder(input);
966
+ const target = output ?? path.join(/** @type {string} */ (folder), 'page.tsx');
967
+ const home = folder ?? newFolderOf(target);
968
+ refuseConfigTarget(target);
969
+ confined(target, cwd, 'The page');
970
+ refuseRunnable([target], cwd, input);
971
+ refuseExisting(isInside(target, home) ? [] : [target]);
972
+ // Components resolve from where the page will live, then from the HTML
973
+ // file's folder, then from the current folder.
974
+ const from =
975
+ [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
976
+ const rebuilt = rebuildPage(html, from);
977
+ refuseProtected([target], cwd, home);
978
+ if (!writeRestore([{file: target, bytes: Buffer.from(rebuilt.source)}], home, cwd, overwrite)) continue;
979
+ return {
980
+ input: shown(cwd, input),
981
+ mode: 'rebuilt',
982
+ output: shown(cwd, target),
983
+ files: [shown(cwd, target)],
984
+ exact: false,
985
+ components: rebuilt.components,
986
+ elements: rebuilt.elements,
987
+ unknown: rebuilt.unknown,
988
+ omitted: rebuilt.omitted,
989
+ };
990
+ }
595
991
  }