@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
@@ -10,6 +10,13 @@
10
10
  * @position api/theme-edit — imported only by _adapter.mjs
11
11
  */
12
12
 
13
+ import {typoNear, wholeNumberOf} from './_normal.mjs';
14
+ import {
15
+ assetRef,
16
+ CSS_URL,
17
+ cssUrlRef,
18
+ } from '../../foundation/render/render-page.mjs';
19
+ import {IMPORTER_SCAN_MAX, pageImporters} from './_importers.mjs';
13
20
  import {parse as parseModule} from '@babel/parser';
14
21
  import * as fs from 'node:fs';
15
22
  import * as path from 'node:path';
@@ -17,6 +24,13 @@ import {createRequire} from 'node:module';
17
24
  import {fileURLToPath} from 'node:url';
18
25
  import {cliVersion} from '../../foundation/release/run-context.mjs';
19
26
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
27
+ import {
28
+ nestedRootLayouts,
29
+ nextAppAt,
30
+ nextRouteFolders,
31
+ sameUrlPage,
32
+ urlSegments,
33
+ } from '../../foundation/discovery/next-routes.mjs';
20
34
  import {
21
35
  assertWithin,
22
36
  PathSafetyError,
@@ -38,6 +52,9 @@ import {
38
52
  unlabeledThemeName,
39
53
  usableNewName,
40
54
  windowsReserved,
55
+ isEditorPage,
56
+ fontsourceSuggestion,
57
+ builtFontWeights,
41
58
  } from './_settings.mjs';
42
59
  import {
43
60
  baseFontsCss,
@@ -46,16 +63,19 @@ import {
46
63
  overviewPageSource,
47
64
  previewRouteSource,
48
65
  appCopyBlocker,
66
+ fontPackageSheets,
49
67
  themeImports,
50
68
  } from './_preview.mjs';
51
69
  import {
52
70
  isEditorTemp,
71
+ readWrittenRecord,
53
72
  PALETTE_STAND_IN,
54
73
  paletteFiles,
55
74
  paletteMapping,
56
75
  tempFor,
57
76
  writeWhole,
58
77
  refuseIfLockLost,
78
+ readRegularFile,
59
79
  } from './_palette.mjs';
60
80
  import {build} from '../build/build.mjs';
61
81
  import {search} from '../search/search.mjs';
@@ -63,9 +83,15 @@ import {template} from '../template/template.mjs';
63
83
  import {
64
84
  analyzeTemplateNeeds,
65
85
  extractImportedPackages,
86
+ parsedSpecifiers,
66
87
  } from '../../foundation/discovery/template-needs.mjs';
67
88
  import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
68
- import {requireProject, context} from './_context.mjs';
89
+ import {
90
+ coreApp,
91
+ requireProject,
92
+ context,
93
+ familiesNothingLoads,
94
+ } from './_context.mjs';
69
95
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
70
96
  import {
71
97
  formatCliCommand,
@@ -73,9 +99,12 @@ import {
73
99
  } from '../../foundation/env/package-manager.mjs';
74
100
  import {sha256} from '../../foundation/render/source-block.mjs';
75
101
  import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
102
+ import {compareText} from '../../foundation/text/compare-text.mjs';
76
103
 
77
104
  const E = ERROR_CODES;
78
105
 
106
+ /** The most bytes one file read takes in Node (2 GiB less one byte). */
107
+ const NODE_READ_MAX = 2 ** 31 - 1;
79
108
  /** The preview's data file: the pages it shows and the files it wrote. */
80
109
  const PREVIEW_DATA = 'theme-preview.json';
81
110
  const PREVIEW = 'astryx experimental theme preview';
@@ -179,11 +208,9 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
179
208
  } catch {
180
209
  return false;
181
210
  }
182
- if (sheet.test(text)) return true;
183
- for (const m of text.matchAll(
184
- /(?:import|@import)\s*(?:[^'"]*from\s*)?(?:url\()?['"]([^'"]+)['"]/g,
185
- )) {
186
- const spec = m[1];
211
+ const specs = importSpecifiers(file, text);
212
+ if (specs.some(spec => sheet.test(spec))) return true;
213
+ for (const spec of specs) {
187
214
  // An alias the tsconfig sets; else `@/` is the src folder or the
188
215
  // project root.
189
216
  const alias = aliases.find(a => spec.startsWith(a.prefix));
@@ -209,6 +236,25 @@ function layoutImportsSheet(cwd, app, sheet, dir = app) {
209
236
  return starts.some(start => reads(start, 0));
210
237
  }
211
238
 
239
+ /**
240
+ * The modules a file imports, from its import statements: a script's
241
+ * through the shared reader of import statements (its syntax tree, so a
242
+ * comment or a string says nothing), or the `@import` rules of a stylesheet
243
+ * (comments left out).
244
+ * @param {string} file
245
+ * @param {string} text
246
+ * @returns {string[]}
247
+ */
248
+ function importSpecifiers(file, text) {
249
+ if (/\.(css|scss)$/.test(file))
250
+ return [
251
+ ...text
252
+ .replace(/\/\*[\s\S]*?\*\//g, '')
253
+ .matchAll(/@import\s+(?:url\()?\s*['"]([^'"]+)['"]/g),
254
+ ].map(m => m[1]);
255
+ return parsedSpecifiers(text);
256
+ }
257
+
212
258
  /**
213
259
  * The import aliases the app's tsconfig `paths` set (`~/*`, `#app/*`), each
214
260
  * with the folders it stands for.
@@ -238,55 +284,19 @@ function tsconfigAliases(cwd) {
238
284
  }
239
285
 
240
286
  /**
241
- * A note when the app never imports Core's stylesheet, or null: without
242
- * it, components render unstyled, and some show nothing. Read from the
243
- * files of the routes folder and src/ (best effort).
287
+ * A note when the preview's layouts never import Core's stylesheet, or
288
+ * null: without it, components render unstyled, and some show nothing.
289
+ * Judged by the real import statements of the layouts over the preview and
290
+ * the files they import, never by text in a comment or in a file the route
291
+ * does not reach.
244
292
  * @param {string} cwd
245
293
  * @param {{dir: string, app: string | null}} at
246
294
  * @returns {string | null}
247
295
  */
248
296
  function coreStylesheetMissing(cwd, at) {
249
297
  if (!at.app) return null;
250
- const SHEET = /@astryxdesign\/core\/astryx\.css/;
251
- let seen = 0;
252
- /** @param {string} folder @returns {boolean} */
253
- const imports = folder => {
254
- /** @type {fs.Dirent[]} */
255
- let entries;
256
- try {
257
- entries = fs.readdirSync(folder, {withFileTypes: true});
258
- } catch {
259
- return false;
260
- }
261
- for (const e of entries) {
262
- const full = path.join(folder, e.name);
263
- if (e.isDirectory()) {
264
- if (
265
- e.name === 'node_modules' ||
266
- e.name.startsWith('.') ||
267
- full === at.dir
268
- )
269
- continue;
270
- if (imports(full)) return true;
271
- } else if (
272
- /\.(tsx|ts|jsx|js|mjs|css|scss)$/.test(e.name) &&
273
- ++seen < 2000
274
- )
275
- try {
276
- if (SHEET.test(fs.readFileSync(full, 'utf8'))) return true;
277
- } catch {
278
- // Unreadable: skip it.
279
- }
280
- }
281
- return false;
282
- };
283
- const src = path.join(cwd, 'src');
284
- if (
285
- imports(at.app) ||
286
- (at.app.startsWith(src + path.sep) ? false : imports(src)) ||
287
- layoutImportsSheet(cwd, at.app, SHEET, at.dir)
288
- )
289
- return null;
298
+ const SHEET = /^@astryxdesign\/core\/astryx\.css$/;
299
+ if (layoutImportsSheet(cwd, at.app, SHEET, at.dir)) return null;
290
300
  const layout = ['tsx', 'ts', 'jsx', 'js']
291
301
  .map(x => path.join(at.app ?? '', `layout.${x}`))
292
302
  .find(f => fs.existsSync(f));
@@ -562,6 +572,41 @@ function nextConfigNotes(cwd) {
562
572
  * @param {string} dir
563
573
  */
564
574
  function reservedFolder(cwd, dir) {
575
+ // The rules of every app the folder is in: the project's, and a Next app
576
+ // below it that holds the folder (a workspace app, from the root).
577
+ for (const owner of appsOver(cwd, dir)) {
578
+ const why = reservedIn(owner, dir);
579
+ if (why) return why;
580
+ }
581
+ return null;
582
+ }
583
+
584
+ /**
585
+ * The app folders that hold `dir`, nearest first: each Next app between it
586
+ * and the project root (a workspace app, a starter app an earlier
587
+ * `preview app` made), then the project root itself.
588
+ * @param {string} cwd
589
+ * @param {string} dir
590
+ * @returns {string[]}
591
+ */
592
+ function appsOver(cwd, dir) {
593
+ /** @type {string[]} */
594
+ const out = [];
595
+ for (
596
+ let at = path.dirname(path.resolve(dir));
597
+ at.startsWith(path.resolve(cwd) + path.sep);
598
+ at = path.dirname(at)
599
+ )
600
+ if (nextAppAt(at)) out.push(at);
601
+ return [...out, cwd];
602
+ }
603
+
604
+ /**
605
+ * {@link reservedFolder} for one app folder.
606
+ * @param {string} cwd the app folder
607
+ * @param {string} dir
608
+ */
609
+ function reservedIn(cwd, dir) {
565
610
  const segs = shown(cwd, dir).split('/').filter(Boolean);
566
611
  if (segs[0] === 'themes')
567
612
  return 'themes/ holds the themes, and everything in a theme folder is copied with the theme';
@@ -588,6 +633,21 @@ function reservedFolder(cwd, dir) {
588
633
  return null;
589
634
  }
590
635
 
636
+ /**
637
+ * The compile of an editor theme as it runs from the folder the command ran
638
+ * in: an editor theme compiles from the app root, so from a subfolder the
639
+ * line goes there first.
640
+ * @param {string} cwd the app root
641
+ * @param {string} slug
642
+ */
643
+ function compileFromHere(cwd, slug) {
644
+ const line = `${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)}`;
645
+ const up = path.relative(process.cwd(), cwd);
646
+ return up && path.resolve(process.cwd()) !== path.resolve(cwd)
647
+ ? `cd ${quoteCommandArgument(up.split(path.sep).join('/'))} && ${line}`
648
+ : line;
649
+ }
650
+
591
651
  /**
592
652
  * The app's tsconfig.json compiler options (comments and trailing commas
593
653
  * allowed), or null when there is none.
@@ -645,9 +705,7 @@ function typeScriptNotes(cwd, dir, added) {
645
705
  `the app has no TypeScript, and the preview's files are .tsx, so the next build sets it up; to do it now: ${installLine(cwd, ['typescript', '@types/react', '@types/node']).replace(/ (add|install) /, ' $1 -D ')}`,
646
706
  ];
647
707
  }
648
- const templates = added.filter(
649
- id => !['overview', 'components', COLORS_PAGE.id].includes(id),
650
- );
708
+ const templates = added.filter(id => !DEFAULT_PAGE_IDS.includes(id));
651
709
  if (options.noUncheckedIndexedAccess !== true || !templates.length) return [];
652
710
  const files = templates.map(id =>
653
711
  shown(cwd, path.join(dir, PAGES_DIR, `${id}.tsx`)),
@@ -657,6 +715,18 @@ function typeScriptNotes(cwd, dir, added) {
657
715
  ];
658
716
  }
659
717
 
718
+ /**
719
+ * A file's text when it is a regular file that can be read, else null.
720
+ * @param {string} file
721
+ */
722
+ const regularText = file => {
723
+ try {
724
+ return readRegularFile(file, 'utf8');
725
+ } catch {
726
+ return null;
727
+ }
728
+ };
729
+
660
730
  /**
661
731
  * Why a file cannot be read (its error code), or null when it can.
662
732
  * @param {string} file
@@ -664,7 +734,7 @@ function typeScriptNotes(cwd, dir, added) {
664
734
  */
665
735
  function unreadable(file) {
666
736
  try {
667
- fs.closeSync(fs.openSync(file, 'r'));
737
+ readRegularFile(file);
668
738
  return null;
669
739
  } catch (e) {
670
740
  const code = /** @type {any} */ (e)?.code;
@@ -735,116 +805,6 @@ function unroutedSegment(app, dir) {
735
805
  : null;
736
806
  }
737
807
 
738
- /**
739
- * The URL a folder of the routes folder is served at, with route groups
740
- * dropped, as path segments.
741
- * @param {string} app
742
- * @param {string} dir
743
- */
744
- const urlSegments = (app, dir) =>
745
- path
746
- .relative(app, dir)
747
- .split(path.sep)
748
- .filter(seg => seg && !/^\(.*\)$/.test(seg));
749
-
750
- /** An optional catch-all route folder, `[[...slug]]`: it also serves its parent folder's URL (a required `[...slug]` does not). */
751
- const CATCH_ALL = /^\[\[\.\.\.[^\]]+\]\]$/;
752
-
753
- /** A file Next serves a URL from: a page or a route handler. */
754
- const ROUTE_FILE = /^(page\.(tsx|ts|jsx|js|mdx)|route\.(tsx|ts|jsx|js))$/;
755
-
756
- /**
757
- * A page or route handler of the app that Next serves at the same URL as
758
- * `dir`, or null: beside the preview, Next refuses to build (a route and a
759
- * page), or the preview takes that URL from it.
760
- * @param {string} cwd
761
- * @param {string} app the routes folder
762
- * @param {string} dir
763
- */
764
- function sameUrlPage(cwd, app, dir) {
765
- const url = urlSegments(app, dir).join('/');
766
- /** @param {string} folder @returns {string | null} */
767
- const walk = folder => {
768
- /** @type {fs.Dirent[]} */
769
- let entries;
770
- try {
771
- entries = fs.readdirSync(folder, {withFileTypes: true});
772
- } catch {
773
- return null;
774
- }
775
- for (const e of entries) {
776
- const full = path.join(folder, e.name);
777
- if (e.isDirectory()) {
778
- if (/^[_@]/.test(e.name) || e.name === 'node_modules' || full === dir)
779
- continue;
780
- const hit = walk(full);
781
- if (hit) return hit;
782
- } else if (ROUTE_FILE.test(e.name) && servesUrl(folder)) return full;
783
- }
784
- return null;
785
- };
786
- /** A folder served at the URL, or at the URLs under it through a catch-all. @param {string} folder */
787
- const servesUrl = folder => {
788
- const segs = urlSegments(app, folder);
789
- return (
790
- segs.join('/') === url ||
791
- (CATCH_ALL.test(segs.at(-1) ?? '') && segs.slice(0, -1).join('/') === url)
792
- );
793
- };
794
- // The preview's own folder: a route handler, a page other than the
795
- // page.tsx the preview writes, or a catch-all route in it.
796
- try {
797
- for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
798
- if (!e.isDirectory()) {
799
- if (ROUTE_FILE.test(e.name) && e.name !== 'page.tsx')
800
- return path.join(dir, e.name);
801
- } else if (CATCH_ALL.test(e.name))
802
- for (const name of fs.readdirSync(path.join(dir, e.name)))
803
- if (ROUTE_FILE.test(name)) return path.join(dir, e.name, name);
804
- }
805
- } catch {
806
- // No folder yet.
807
- }
808
- const inApp = walk(app);
809
- if (inApp) return inApp;
810
- for (const pages of [path.join(cwd, 'pages'), path.join(cwd, 'src', 'pages')])
811
- for (const ext of ['tsx', 'ts', 'jsx', 'js']) {
812
- for (const f of [`${url}.${ext}`, `${url}/index.${ext}`]) {
813
- const full = path.join(pages, f);
814
- if (url && fs.existsSync(full)) return full;
815
- }
816
- }
817
- return null;
818
- }
819
-
820
- /**
821
- * The folders that hold a root layout when the routes folder has none of
822
- * its own: each route group with a layout (`(shop)/`, `(marketing)/`), or
823
- * a `[locale]/` in an app with the locale in every URL. Empty when the
824
- * routes folder has its own root layout.
825
- * @param {string} app
826
- * @returns {string[]}
827
- */
828
- function nestedRootLayouts(app) {
829
- const LAYOUT = /^layout\.(tsx|ts|jsx|js)$/;
830
- if (fs.readdirSync(app).some(f => LAYOUT.test(f))) return [];
831
- /** @type {string[]} */
832
- const out = [];
833
- /** A folder with a layout counts; a route group without one is looked into. @param {string} dir @param {boolean} top */
834
- const look = (dir, top) => {
835
- for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
836
- if (!e.isDirectory()) continue;
837
- const sub = path.join(dir, e.name);
838
- const group = /^\(.+\)$/.test(e.name);
839
- if (!top && !group) continue;
840
- if (fs.readdirSync(sub).some(f => LAYOUT.test(f))) out.push(sub);
841
- else if (group) look(sub, false);
842
- }
843
- };
844
- look(app, true);
845
- return out.sort();
846
- }
847
-
848
808
  /**
849
809
  * Refuse a folder where the preview would not be served as reported, or
850
810
  * would break the app: one that holds the app itself, a reserved or
@@ -857,9 +817,16 @@ function nestedRootLayouts(app) {
857
817
  * @param {Retry} retry
858
818
  */
859
819
  function checkPlacement(cwd, dir, where, retry) {
860
- const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
861
- r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
862
- );
820
+ // A folder in a Next app below the project (a workspace app, from the
821
+ // root) gets that app's own checks: its routes folder, its next.config,
822
+ // its root layouts. Retries keep the folder as given from here.
823
+ const owner = appsOver(cwd, dir)[0];
824
+ if (owner !== cwd)
825
+ return checkPlacement(owner, dir, where, p =>
826
+ retry(p == null ? null : shown(cwd, path.resolve(owner, p))),
827
+ );
828
+ const routesFolder = nextRouteFolders(cwd).app;
829
+ const served = routesFolder ? path.join(cwd, routesFolder) : undefined;
863
830
  const fallback = retry(
864
831
  served
865
832
  ? shown(cwd, path.join(served, 'theme-preview'))
@@ -935,7 +902,9 @@ function checkPlacement(cwd, dir, where, retry) {
935
902
  const odd = segs.filter(
936
903
  seg => seg && !/^\(.+\)$|^\[.+\]$/.test(seg) && !PLAIN.test(seg),
937
904
  );
938
- if (app && odd.length) {
905
+ // A preview already there is updated where it is (its pages are served at
906
+ // the encoded URL `see` gives); only a new preview gets a plain name.
907
+ if (app && odd.length && !fs.existsSync(path.join(dir, PREVIEW_DATA))) {
939
908
  const slug = (/** @type {string} */ seg) =>
940
909
  seg
941
910
  .normalize('NFD')
@@ -999,7 +968,12 @@ function checkPlacement(cwd, dir, where, retry) {
999
968
  if (served && app !== served)
1000
969
  refuse(
1001
970
  E.ERR_INVALID_ARGUMENT,
1002
- `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
971
+ // Next serves the root app/ when both are there: a preview in src/app/
972
+ // under a root app/ is not served, and a new root app/ beside the
973
+ // app's src/app/ would hide the whole app.
974
+ path.resolve(app) === path.join(path.resolve(cwd), 'app')
975
+ ? `${where} would make ${shown(cwd, app)}/ beside ${shown(cwd, served)}/, and Next serves the root app/ when both are there, so the whole app in ${shown(cwd, served)}/ would stop being served.`
976
+ : `${where} is in ${shown(cwd, app)}/, and Next serves ${shown(cwd, served)}/ instead when both are there.`,
1003
977
  {
1004
978
  run: fs.existsSync(path.join(dir, PREVIEW_DATA))
1005
979
  ? [
@@ -1010,9 +984,7 @@ function checkPlacement(cwd, dir, where, retry) {
1010
984
  );
1011
985
  const exts = readNextConfig(cwd).pageExtensions;
1012
986
  if (exts && !exts.includes('tsx')) {
1013
- let free = 'theme-app';
1014
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1015
- free = `theme-app-${n}`;
987
+ const free = freeAppFolder(cwd);
1016
988
  refuse(
1017
989
  E.ERR_INVALID_ARGUMENT,
1018
990
  `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx, the route file the preview writes.`,
@@ -1020,7 +992,7 @@ function checkPlacement(cwd, dir, where, retry) {
1020
992
  fix: 'add "tsx" to pageExtensions to use the preview in this app',
1021
993
  run: [
1022
994
  `${retry(shown(cwd, dir))} # once "tsx" is in pageExtensions`,
1023
- `${PREVIEW} app ${free} # or a new app of its own, with the preview`,
995
+ `${appCommand(free)} # or a new app of its own, with the preview`,
1024
996
  ],
1025
997
  },
1026
998
  );
@@ -1031,16 +1003,14 @@ function checkPlacement(cwd, dir, where, retry) {
1031
1003
  !rootLayouts.length &&
1032
1004
  !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)))
1033
1005
  ) {
1034
- let free = 'theme-app';
1035
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1036
- free = `theme-app-${n}`;
1006
+ const free = freeAppFolder(cwd);
1037
1007
  refuse(
1038
1008
  E.ERR_INVALID_ARGUMENT,
1039
1009
  `${shown(cwd, served ?? app)}/ has no root layout (no layout.tsx in it or in a route group)${served ? '' : ' and is not there yet'}, so Next cannot build a page in ${where}.`,
1040
1010
  {
1041
1011
  fix: `add a root layout to ${shown(cwd, served ?? app)}/ to use the preview in this app`,
1042
1012
  run: [
1043
- `${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
1013
+ `${appCommand(free)} # a new app with its own root layout and the preview`,
1044
1014
  ],
1045
1015
  },
1046
1016
  );
@@ -1078,7 +1048,9 @@ function checkPlacement(cwd, dir, where, retry) {
1078
1048
  * serves (`app/`, else `src/app/`).
1079
1049
  * @param {string} cwd
1080
1050
  * @param {string | undefined} where
1081
- * @param {{optional?: boolean, write?: boolean, retry?: Retry}} [opts]
1051
+ * @param {{optional?: boolean, write?: boolean, retry?: Retry, theme?: string | null}} [opts]
1052
+ * `theme`: the theme the command was given, kept by a pointer to a new
1053
+ * starter app
1082
1054
  * `optional`: null instead of a refusal when there is no routes folder;
1083
1055
  * `write`: the folder is checked as a place to write; `retry`: the
1084
1056
  * command again with another --path, for refusals
@@ -1092,17 +1064,44 @@ function previewDir(cwd, where, opts = {}) {
1092
1064
  const routes = ['app', path.join('src', 'app')]
1093
1065
  .map(r => path.join(cwd, r))
1094
1066
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
1095
- const appOf = (/** @type {string} */ dir) =>
1096
- routes.find(r => dir.startsWith(r + path.sep)) ?? null;
1067
+ // The routes folder of the app that holds the folder (a workspace app's,
1068
+ // from the root).
1069
+ const appOf = (/** @type {string} */ dir) => {
1070
+ const owner = appsOver(cwd, dir)[0];
1071
+ return (
1072
+ [path.join(owner, 'app'), path.join(owner, 'src', 'app')].find(r =>
1073
+ dir.startsWith(r + path.sep),
1074
+ ) ?? null
1075
+ );
1076
+ };
1097
1077
  if (where != null) {
1098
1078
  checkFolderName(where, '--path', retry);
1099
1079
  /** @type {string} */
1100
1080
  let dir;
1081
+ // A --path read from the folder the command ran in; one that names a
1082
+ // preview from the project root (as every printed folder is) is read
1083
+ // from there, so a printed tip works from a subfolder too.
1084
+ const fromRoot = (() => {
1085
+ // The --path as given from the subfolder the command ran in, rebased
1086
+ // onto the project root by the caller: when that names no folder and
1087
+ // the path without the subfolder names a preview, that one.
1088
+ const sub = path.relative(cwd, process.cwd());
1089
+ if (!sub || sub.startsWith('..') || path.isAbsolute(where)) return null;
1090
+ const given = path.normalize(where);
1091
+ if (!given.startsWith(sub + path.sep)) return null;
1092
+ const there = path.resolve(cwd, given.slice(sub.length + 1));
1093
+ return !fs.existsSync(path.resolve(cwd, where)) &&
1094
+ fs.existsSync(path.join(there, PREVIEW_DATA))
1095
+ ? there
1096
+ : null;
1097
+ })();
1101
1098
  try {
1102
- dir = assertWithin(path.resolve(cwd, where), cwd, {
1103
- allowAbsolute: true,
1104
- label: '--path',
1105
- });
1099
+ dir =
1100
+ fromRoot ??
1101
+ assertWithin(path.resolve(cwd, where), cwd, {
1102
+ allowAbsolute: true,
1103
+ label: '--path',
1104
+ });
1106
1105
  } catch (e) {
1107
1106
  if (e instanceof PathSafetyError)
1108
1107
  refuse(
@@ -1164,11 +1163,11 @@ function previewDir(cwd, where, opts = {}) {
1164
1163
  const candidates = routes.map(r => path.join(r, 'theme-preview'));
1165
1164
  const known = candidates.find(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
1166
1165
  if (!known && opts.retry) {
1167
- // A preview added with --path is recorded with its theme, so a later
1168
- // command finds it without the flag instead of starting a second one.
1169
- const recorded = [
1170
- ...new Set(editedThemes(cwd).flatMap(t => recordedPreviews(cwd, t))),
1171
- ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
1166
+ // A preview added with --path is recorded with its theme, and one
1167
+ // renamed by hand is found in the routes folders (as list, remove and
1168
+ // see find it), so a later command uses it instead of starting a second
1169
+ // one.
1170
+ const recorded = allPreviews(cwd);
1172
1171
  if (recorded.length === 1) {
1173
1172
  inProjectOrRefuse(cwd, recorded[0], retry);
1174
1173
  if (opts.write)
@@ -1191,30 +1190,53 @@ function previewDir(cwd, where, opts = {}) {
1191
1190
  return {dir: older, app: null};
1192
1191
  }
1193
1192
  }
1194
- // The routes folder Next serves: app/ when both app/ and src/app/ are there.
1195
- const served = routes[0];
1193
+ const servedFolder = nextRouteFolders(cwd).app;
1194
+ const served = servedFolder ? path.join(cwd, servedFolder) : undefined;
1196
1195
  const nested =
1197
1196
  served && !known ? (nestedRootLayouts(served)[0] ?? null) : null;
1198
1197
  const dir = known ?? (served && path.join(nested ?? served, 'theme-preview'));
1199
1198
  if (!dir && opts.optional) return /** @type {any} */ (null);
1200
1199
  if (!dir) {
1201
- // A workspace root: the Next apps below it, each with a --path into
1202
- // its routes folder.
1200
+ // A workspace root: the Next apps below it.
1203
1201
  const apps = nextAppsUnder(cwd);
1202
+ const rootIsProject = coreApp(cwd) === path.resolve(cwd);
1203
+ const themesHere = editedThemes(cwd);
1204
+ // The starter carries a theme this folder holds; a theme a workspace
1205
+ // app holds is reached from that app, as `preview app` itself says.
1206
+ const starterTheme =
1207
+ opts.theme != null
1208
+ ? themesHere.includes(opts.theme)
1209
+ ? opts.theme
1210
+ : null
1211
+ : themesHere.length === 1
1212
+ ? themesHere[0]
1213
+ : null;
1214
+ const themeOwner =
1215
+ opts.theme != null && !starterTheme
1216
+ ? apps.find(a =>
1217
+ fs.existsSync(themeFiles(a.root, opts.theme ?? '').settings),
1218
+ )
1219
+ : undefined;
1204
1220
  refuse(
1205
1221
  E.ERR_NOT_FOUND,
1206
1222
  apps.length
1207
1223
  ? `No app routes folder here (app/ or src/app/); the Next ${apps.length > 1 ? 'apps' : 'app'} below ${apps.length > 1 ? 'are' : 'is'} ${apps.map(a => `${shown(cwd, a.root)}/`).join(', ')}.`
1208
1224
  : 'No app routes folder here (app/ or src/app/), so there is no app to put the preview in.',
1209
1225
  {
1226
+ // The same command for each app below, with every argument kept: a
1227
+ // root that is a project (its themes are here) reaches the app with
1228
+ // --path; any other root runs it from the app's own folder.
1210
1229
  run: [
1211
1230
  ...apps
1212
1231
  .slice(0, 3)
1213
- .map(
1214
- a =>
1215
- `${PREVIEW} add --path ${quoteCommandArgument(shown(cwd, path.join(a.routes, 'theme-preview')))}`,
1232
+ .map(a =>
1233
+ rootIsProject
1234
+ ? retry(shown(cwd, path.join(a.routes, 'theme-preview')))
1235
+ : `${cdTo(shown(cwd, a.root))} && ${retry(null)}`,
1216
1236
  ),
1217
- `${PREVIEW} app theme-app # a new starter app with the preview in it`,
1237
+ themeOwner
1238
+ ? `${cdTo(shown(cwd, themeOwner.root))} && ${appCommand(freeAppFolder(themeOwner.root), opts.theme)} # a new starter app with the preview in it`
1239
+ : `${appCommand(freeAppFolder(cwd), starterTheme)} # a new starter app with the preview in it`,
1218
1240
  ],
1219
1241
  },
1220
1242
  );
@@ -1224,6 +1246,80 @@ function previewDir(cwd, where, opts = {}) {
1224
1246
  return {dir, app: appOf(dir)};
1225
1247
  }
1226
1248
 
1249
+ /**
1250
+ * Whether `preview add` takes this folder (null: its usual one): the checks
1251
+ * add itself runs before it writes, run here with nothing written. A
1252
+ * pointer to `preview add` is offered only when this says so.
1253
+ * @param {string} cwd
1254
+ * @param {string | null} where
1255
+ */
1256
+ function addTakes(cwd, where) {
1257
+ try {
1258
+ previewDir(cwd, where ?? undefined, {write: true, retry: () => ''});
1259
+ return true;
1260
+ } catch {
1261
+ return false;
1262
+ }
1263
+ }
1264
+
1265
+ /**
1266
+ * `preview app` for a folder, as a shell runs it: flags first, and a name
1267
+ * that starts with `-` after `--`, which the command would read as an
1268
+ * option. The one way every pointer to `preview app` is written; the
1269
+ * adapter rebases its folder onto the folder the command ran in.
1270
+ * @param {string} folder
1271
+ * @param {string | null} [theme]
1272
+ */
1273
+ function appCommand(folder, theme = null) {
1274
+ const flags = theme == null ? '' : ` --theme ${quoteCommandArgument(theme)}`;
1275
+ return folder.startsWith('-')
1276
+ ? `${PREVIEW} app${flags} -- ${quoteCommandArgument(folder)}`
1277
+ : `${PREVIEW} app ${quoteCommandArgument(folder)}${flags}`;
1278
+ }
1279
+
1280
+ /**
1281
+ * A `cd` to a folder as a shell runs it: quoted, and a name that starts with
1282
+ * `-` given as `./-name`, which `cd` would read as an option.
1283
+ * @param {string} folder
1284
+ */
1285
+ function cdTo(folder) {
1286
+ return `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)}`;
1287
+ }
1288
+
1289
+ /**
1290
+ * A folder name for a new starter app that is free in `cwd`: theme-app, else
1291
+ * theme-app-2, theme-app-3 and so on.
1292
+ * @param {string} cwd
1293
+ */
1294
+ function freeAppFolder(cwd) {
1295
+ return shown(cwd, freeFolder(cwd, cwd, 'theme-app'));
1296
+ }
1297
+
1298
+ /**
1299
+ * A folder in `parent` that `preview app` takes: `base`, else `base-2`,
1300
+ * `base-3` and so on, passing over a name that is there in any form (a
1301
+ * file, a folder, a dangling link), one that differs from a name there only
1302
+ * in case, and a folder no app goes in.
1303
+ * @param {string} cwd the project
1304
+ * @param {string} parent
1305
+ * @param {string} base
1306
+ * @returns {string} the folder, absolute
1307
+ */
1308
+ function freeFolder(cwd, parent, base) {
1309
+ /** @param {string} f */
1310
+ const taken = f => {
1311
+ try {
1312
+ fs.lstatSync(f);
1313
+ return true;
1314
+ } catch {
1315
+ return Boolean(sameCaseSibling(f) || reservedFolder(cwd, f));
1316
+ }
1317
+ };
1318
+ let free = path.join(parent, base);
1319
+ for (let n = 2; taken(free); n++) free = path.join(parent, `${base}-${n}`);
1320
+ return free;
1321
+ }
1322
+
1227
1323
  /**
1228
1324
  * The Next apps in folders below `cwd` (a few levels, node_modules left
1229
1325
  * out): each folder with a package.json that depends on `next` and a routes
@@ -1258,7 +1354,7 @@ function nextAppsUnder(cwd) {
1258
1354
  }
1259
1355
  };
1260
1356
  walk(cwd, 1);
1261
- return out.sort((a, b) => a.root.localeCompare(b.root));
1357
+ return out.sort((a, b) => compareText(a.root, b.root));
1262
1358
  }
1263
1359
 
1264
1360
  /**
@@ -1281,7 +1377,7 @@ export function addWiring(cwd, slug, mode = 'system') {
1281
1377
  : [
1282
1378
  `${slug} is ${mode}-only: give the <Theme> that theme add's wiring puts in the app root mode="${mode}" (<Theme theme={…} mode="${mode}">); the theme keeps both halves of its colors, so a toast or a lightbox Core draws in the other mode stays readable`,
1283
1379
  ]),
1284
- `every set and undo builds the theme and its app copy again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)} builds both again`,
1380
+ `every set and undo builds the theme and its app copy again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${compileFromHere(cwd, slug)} builds both again`,
1285
1381
  ];
1286
1382
  }
1287
1383
 
@@ -1324,7 +1420,7 @@ export function appWiring(ctx, slug, data) {
1324
1420
  return [
1325
1421
  ...(blocker
1326
1422
  ? [
1327
- `${blocker} is not the editor's, so the editor does not write the theme's app copy in src/themes/${slug}/ (and theme add does not take it); the steps by hand:`,
1423
+ `the app copy in src/themes/${slug}/ was not updated: ${blocker}; the steps by hand:`,
1328
1424
  ]
1329
1425
  : []),
1330
1426
  `in ${where}, import the theme and its stylesheets: import {Theme} from '@astryxdesign/core/theme'; import {${name}} from '${ti.module.replace(/\.js$/, '')}'; ${ti.css.map(c => `import '${c}';`).join(' ')}`,
@@ -1334,33 +1430,24 @@ export function appWiring(ctx, slug, data) {
1334
1430
  `${appModule} (written by theme add and use) stays as it is: to keep its themes too, merge them in your own file ({...themes, ${JSON.stringify(slug)}: ${name}}), never in ${appModule}, which add, use and remove write again`,
1335
1431
  ]
1336
1432
  : []),
1337
- `every set and undo builds ${shown(cwd, themeFiles(cwd, slug).js)} and ${shown(cwd, themeFiles(cwd, slug).css)} again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${P.replace(/ editor$/, '')} compile ${shown(cwd, themeFiles(cwd, slug).ts)} builds it again`,
1433
+ `every set and undo builds ${shown(cwd, themeFiles(cwd, slug).js)} and ${shown(cwd, themeFiles(cwd, slug).css)} again, so the app takes each change; after editing ${shown(cwd, themeFiles(cwd, slug).ts)} by hand, ${compileFromHere(cwd, slug)} builds it again`,
1338
1434
  ];
1339
1435
  }
1340
1436
 
1341
1437
  /**
1342
- * The routes folder of a Next app in `dir` (app/, else src/app/, with a
1343
- * root layout), when its package.json depends on `next`; else null.
1438
+ * The App Router folder of a Next app in `dir`, when its package.json
1439
+ * depends on `next` and that folder holds a root layout; else null.
1344
1440
  * @param {string} dir
1345
1441
  * @returns {string | null}
1346
1442
  */
1347
1443
  function nextRoutesOf(dir) {
1348
- try {
1349
- const pkg = JSON.parse(
1350
- fs.readFileSync(path.join(dir, 'package.json'), 'utf8'),
1351
- );
1352
- if (!['dependencies', 'devDependencies'].some(k => pkg?.[k]?.next))
1353
- return null;
1354
- } catch {
1355
- return null;
1356
- }
1357
- return (
1358
- [path.join(dir, 'app'), path.join(dir, 'src', 'app')].find(
1359
- r =>
1360
- fs.existsSync(r) &&
1361
- fs.readdirSync(r).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f)),
1362
- ) ?? null
1363
- );
1444
+ if (!nextAppAt(dir)) return null;
1445
+ const folder = nextRouteFolders(dir).app;
1446
+ if (!folder) return null;
1447
+ const routes = path.join(dir, folder);
1448
+ return fs.readdirSync(routes).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f))
1449
+ ? routes
1450
+ : null;
1364
1451
  }
1365
1452
 
1366
1453
  /**
@@ -1391,7 +1478,7 @@ function inProjectOrRefuse(cwd, dir, retry) {
1391
1478
  run: [
1392
1479
  within(path.dirname(dir))
1393
1480
  ? retry(shown(cwd, free))
1394
- : `${PREVIEW} app theme-app # a new app of its own, inside this folder`,
1481
+ : `${appCommand(freeAppFolder(cwd))} # a new app of its own, inside this folder`,
1395
1482
  ],
1396
1483
  },
1397
1484
  );
@@ -1488,8 +1575,16 @@ export default function Home() {
1488
1575
  */
1489
1576
  function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1490
1577
  const again = (/** @type {string | null} */ p) =>
1491
- `${PREVIEW} app ${quoteCommandArgument(p ?? 'theme-app')}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`;
1492
- checkFolderName(where, 'The app folder', again);
1578
+ appCommand(p ?? freeAppFolder(cwd), slug);
1579
+ // A repaired name (trimmed, with "/" for "\\") is offered only free: the
1580
+ // first free folder from it, as every other suggested folder is.
1581
+ checkFolderName(where, 'The app folder', p => {
1582
+ if (p == null) return again(null);
1583
+ const at = path.resolve(cwd, p);
1584
+ return again(
1585
+ shown(cwd, freeFolder(cwd, path.dirname(at), path.basename(at))),
1586
+ );
1587
+ });
1493
1588
  /** @type {string} */
1494
1589
  let root;
1495
1590
  try {
@@ -1501,44 +1596,48 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1501
1596
  if (e instanceof PathSafetyError)
1502
1597
  refuse(
1503
1598
  E.ERR_PATH_TRAVERSAL,
1504
- `${where} is outside the current folder; make the app inside the folder you run the command from.`,
1599
+ `${where} is outside the project; make the app inside the project folder.`,
1505
1600
  {run: [again(null)]},
1506
1601
  );
1507
1602
  throw e;
1508
1603
  }
1509
1604
  /** A free folder name inside the current folder, near `dir`. @param {string} dir */
1510
- const freeNear = dir => {
1511
- const parent = dir === cwd ? cwd : path.dirname(dir);
1512
- const base = dir === cwd ? 'theme-app' : `${path.basename(dir)}-preview`;
1513
- let free = base;
1514
- for (let n = 2; fs.existsSync(path.join(parent, free)); n++)
1515
- free = `${base}-${n}`;
1516
- return shown(cwd, path.join(parent, free));
1517
- };
1605
+ const freeNear = dir =>
1606
+ dir === cwd
1607
+ ? freeAppFolder(cwd)
1608
+ : shown(
1609
+ cwd,
1610
+ freeFolder(cwd, path.dirname(dir), `${path.basename(dir)}-preview`),
1611
+ );
1518
1612
  const name = shownDir(cwd, root);
1519
- const routes = ['app', path.join('src', 'app')]
1520
- .map(r => path.join(cwd, r))
1613
+ // The routes folders of every app the folder is in (the project's, and a
1614
+ // workspace app's from the root).
1615
+ const routes = appsOver(cwd, root)
1616
+ .flatMap(a => ['app', path.join('src', 'app')].map(r => path.join(a, r)))
1521
1617
  .filter(r => fs.existsSync(r) && fs.statSync(r).isDirectory());
1618
+ const inRoutes = routes.find(
1619
+ r => root === r || root.startsWith(r + path.sep),
1620
+ );
1522
1621
  const why =
1523
1622
  reservedFolder(cwd, root) ??
1524
- (routes.some(r => root === r || root.startsWith(r + path.sep))
1525
- ? "it is inside this app's routes folder, where Next would serve the new app's files as pages of this one"
1623
+ (inRoutes
1624
+ ? `it is inside the routes folder ${shownDir(cwd, inRoutes)}/, where Next would serve the new app's files as pages of that app`
1526
1625
  : null) ??
1527
1626
  (t =>
1528
1627
  t
1529
1628
  ? `${shownDir(cwd, t)}/ differs from it only in case, and on macOS and Windows they are one folder`
1530
1629
  : null)(sameCaseSibling(root));
1531
1630
  if (why) {
1532
- let free = 'theme-app';
1533
- for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
1534
- free = `theme-app-${n}`;
1631
+ const free = freeAppFolder(cwd);
1535
1632
  refuse(
1536
1633
  E.ERR_INVALID_ARGUMENT,
1537
1634
  `${name} is no place for a new app: ${why}.`,
1538
1635
  {
1539
1636
  run: [
1540
1637
  again(free),
1541
- `${PREVIEW} add # the preview inside this app instead`,
1638
+ ...(addTakes(cwd, null)
1639
+ ? [`${PREVIEW} add # the preview inside this app instead`]
1640
+ : []),
1542
1641
  ],
1543
1642
  },
1544
1643
  );
@@ -1590,7 +1689,7 @@ function planStarterApp(cwd, where, extra, dependencies, slug = null) {
1590
1689
  file,
1591
1690
  text:
1592
1691
  key === 'package.json'
1593
- ? starterPackageJson(text, dependencies)
1692
+ ? starterPackageJson(text, dependencies, starterName(cwd, root))
1594
1693
  : key === 'src/app/page.tsx'
1595
1694
  ? STARTER_HOME
1596
1695
  : key === 'src/app/layout.tsx'
@@ -1623,18 +1722,45 @@ function starterLayout(text) {
1623
1722
  }
1624
1723
 
1625
1724
  /**
1626
- * The starter's package.json with the Astryx packages pinned to this CLI's
1627
- * release, and `dependencies` added.
1725
+ * The new app's package name, from its folder's path in the project: two
1726
+ * starter apps in one workspace never share a name, which would break the
1727
+ * whole workspace's install.
1728
+ * @param {string} cwd the project root
1729
+ * @param {string} root the new app's folder
1730
+ */
1731
+ function starterName(cwd, root) {
1732
+ // One spelling per path, no two paths alike: lowercase letters, digits
1733
+ // and `-` stay; a folder break is `.`; every other character (a capital,
1734
+ // a dot, an accent) is `_<its code point in hex>_`.
1735
+ const rel = (path.relative(cwd, root) || path.basename(root))
1736
+ .split(path.sep)
1737
+ .map(seg =>
1738
+ [...seg]
1739
+ .map(c =>
1740
+ /[a-z0-9-]/.test(c)
1741
+ ? c
1742
+ : `_${/** @type {number} */ (c.codePointAt(0)).toString(16)}_`,
1743
+ )
1744
+ .join(''),
1745
+ )
1746
+ .join('.');
1747
+ return `astryx-theme-preview-${rel}`;
1748
+ }
1749
+
1750
+ /**
1751
+ * The starter's package.json with its name, the Astryx packages pinned to
1752
+ * this CLI's release, and `dependencies` added.
1628
1753
  * @param {string} text
1629
1754
  * @param {Record<string, string>} dependencies
1755
+ * @param {string} name the package name
1630
1756
  */
1631
- function starterPackageJson(text, dependencies) {
1757
+ function starterPackageJson(text, dependencies, name) {
1632
1758
  const pinned = text.replaceAll('{{astryxVersion}}', cliVersion());
1633
- if (!Object.keys(dependencies).length) return pinned;
1634
1759
  const pkg = JSON.parse(pinned);
1760
+ pkg.name = name;
1635
1761
  pkg.dependencies = Object.fromEntries(
1636
1762
  Object.entries({...pkg.dependencies, ...dependencies}).sort(([a], [b]) =>
1637
- a.localeCompare(b),
1763
+ compareText(a, b),
1638
1764
  ),
1639
1765
  );
1640
1766
  return `${JSON.stringify(pkg, null, 2)}\n`;
@@ -1696,7 +1822,16 @@ function writeStarterApp(cwd, plan, again) {
1696
1822
  refuse(
1697
1823
  E.ERR_FILE_EXISTS,
1698
1824
  `${shownDir(cwd, root)} was filled by something else while the app was written, so the app was not put there.`,
1699
- {run: [again(`${shownDir(cwd, root)}-2`)]},
1825
+ {
1826
+ run: [
1827
+ again(
1828
+ shown(
1829
+ cwd,
1830
+ freeFolder(cwd, path.dirname(root), path.basename(root)),
1831
+ ),
1832
+ ),
1833
+ ],
1834
+ },
1700
1835
  );
1701
1836
  refuse(
1702
1837
  E.ERR_WRITE_FAILED,
@@ -1828,13 +1963,21 @@ function readPreview(cwd, dir, pf = '', opts = {}) {
1828
1963
  let text;
1829
1964
  try {
1830
1965
  // A byte-order mark (Notepad, PowerShell) is not part of the JSON.
1831
- text = fs
1832
- .readFileSync(path.join(dir, PREVIEW_DATA), 'utf8')
1833
- .replace(/^\uFEFF/, '');
1966
+ text = readRegularFile(path.join(dir, PREVIEW_DATA), 'utf8').replace(
1967
+ /^\uFEFF/,
1968
+ '',
1969
+ );
1834
1970
  } catch (e) {
1835
1971
  const code = /** @type {any} */ (e)?.code;
1836
1972
  if (code === 'ENOENT' || code === 'ENOTDIR') return null;
1837
- damagedPreview(cwd, dir, `it cannot be read (${code})`, pf);
1973
+ damagedPreview(
1974
+ cwd,
1975
+ dir,
1976
+ code === 'ENOTREG'
1977
+ ? 'it is not a regular file (a pipe, a device or a folder), so it is never read'
1978
+ : `it cannot be read (${code})`,
1979
+ pf,
1980
+ );
1838
1981
  }
1839
1982
  /** @type {any} */
1840
1983
  let data;
@@ -2129,13 +2272,15 @@ function editedByHand(dir, data, rel) {
2129
2272
  const was = data.hashes?.[rel];
2130
2273
  if (!was) return false;
2131
2274
  try {
2132
- const text = fs.readFileSync(path.join(dir, rel));
2275
+ const text = readRegularFile(path.join(dir, rel));
2133
2276
  if (was.startsWith('v2:') || was.startsWith('v3:'))
2134
2277
  return !sameAsRecorded(text, was);
2135
2278
  // Older records hold the exact or the earlier normalized hash.
2136
2279
  return oldContentHash(text) !== was && digest(text) !== was;
2137
- } catch {
2138
- return false;
2280
+ } catch (e) {
2281
+ // Something that is not a regular file (a pipe) where the page was is
2282
+ // no longer the preview's own: never read, never replaced.
2283
+ return /** @type {any} */ (e)?.code === 'ENOTREG';
2139
2284
  }
2140
2285
  }
2141
2286
 
@@ -2199,7 +2344,7 @@ function checkWrite(cwd, dir, data, w, elsewhere) {
2199
2344
  `${name} is ${st.isDirectory() ? 'a folder' : 'not a plain file'}, where the preview writes a file; it is never replaced.`,
2200
2345
  {run: [elsewhere]},
2201
2346
  );
2202
- if (fs.readFileSync(file, 'utf8') === w.text) return 'same';
2347
+ if (readRegularFile(file, 'utf8') === w.text) return 'same';
2203
2348
  const page = /^_?pages\/([^/]+)\.tsx$/.exec(w.rel)?.[1];
2204
2349
  if (!data.files.includes(w.rel))
2205
2350
  refuse(
@@ -2259,7 +2404,7 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2259
2404
  const touched = [];
2260
2405
  const before = (/** @type {string} */ file) => {
2261
2406
  try {
2262
- return fs.readFileSync(file);
2407
+ return readRegularFile(file);
2263
2408
  } catch {
2264
2409
  return null;
2265
2410
  }
@@ -2339,12 +2484,10 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2339
2484
  2,
2340
2485
  )}\n`,
2341
2486
  );
2342
- commitStep('pending');
2343
2487
  for (const w of writes) {
2344
2488
  current = path.join(dir, w.rel);
2345
2489
  touched.push({file: current, before: before(current)});
2346
2490
  fs.renameSync(tmp(current), current);
2347
- commitStep('rename');
2348
2491
  }
2349
2492
  staged.length = 0;
2350
2493
  step = 'removed';
@@ -2354,7 +2497,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2354
2497
  if (was == null) continue;
2355
2498
  touched.push({file: current, before: was});
2356
2499
  fs.rmSync(current);
2357
- commitStep('delete');
2358
2500
  }
2359
2501
  step = 'written';
2360
2502
  current = path.join(dir, PREVIEW_DATA);
@@ -2363,8 +2505,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2363
2505
  fs.renameSync(tmp(current), current);
2364
2506
  fs.rmSync(pendingFile, {force: true});
2365
2507
  } catch (e) {
2366
- // A stop injected by a test stands for a kill: nothing is put back.
2367
- if (e === STOPPED) throw e;
2368
2508
  fs.rmSync(pendingFile, {force: true});
2369
2509
  for (const t of staged) fs.rmSync(t, {force: true});
2370
2510
  for (const t of touched.reverse())
@@ -2392,21 +2532,6 @@ function commitPreview(cwd, dir, data, writes, deletes, again) {
2392
2532
  /** The step record a preview change leaves while it runs. */
2393
2533
  const PENDING = '.theme-preview.pending.json';
2394
2534
 
2395
- /** What a test throws to stop a change part way, as a kill would. */
2396
- const STOPPED = Symbol('stopped');
2397
-
2398
- /** @type {((step: string) => boolean) | null} */
2399
- let stopAt = null;
2400
-
2401
- /**
2402
- * For tests: stop the next preview changes at the step where `when`
2403
- * returns true, as a kill would, with nothing put back. Null clears it.
2404
- * @param {((step: string) => boolean) | null} when
2405
- */
2406
- export function stopPreviewCommitAt(when) {
2407
- stopAt = when;
2408
- }
2409
-
2410
2535
  /** Whether a process is running here. @param {number} pid */
2411
2536
  function alive(pid) {
2412
2537
  if (pid === process.pid) return true;
@@ -2418,191 +2543,6 @@ function alive(pid) {
2418
2543
  }
2419
2544
  }
2420
2545
 
2421
- /** @param {string} step */
2422
- function commitStep(step) {
2423
- if (stopAt?.(step)) throw STOPPED;
2424
- }
2425
-
2426
- /** Folders the importer search never enters: installs and build output. */
2427
- const NOT_SOURCE = new Set([
2428
- 'node_modules',
2429
- 'out',
2430
- 'dist',
2431
- 'build',
2432
- 'coverage',
2433
- ]);
2434
-
2435
- /** At most this many source files are read; past it, nothing is deleted. */
2436
- let IMPORTER_SCAN_MAX = 50000;
2437
-
2438
- /**
2439
- * For tests: read at most `n` source files when checking for importers
2440
- * (null: the default).
2441
- * @param {number | null} n
2442
- */
2443
- export function setImporterScanMax(n) {
2444
- IMPORTER_SCAN_MAX = n ?? 50000;
2445
- }
2446
-
2447
- /**
2448
- * Files of the project's own that import any of `targets` (preview files
2449
- * about to be deleted), so deleting them would break the app's build. The
2450
- * whole project root is read: every .ts/.tsx/.js/.jsx/.mjs/.cjs/.mdx file
2451
- * outside node_modules, build output and dot folders, the preview's own
2452
- * files left out. Each file's import and export-from declarations,
2453
- * import() and require() calls (a string or a template with no
2454
- * substitution) are read from its syntax tree and resolved: relative,
2455
- * `@/`, or a tsconfig `paths` alias. `tooBig` when the project holds more
2456
- * source files than are read, so the caller refuses instead of guessing.
2457
- * @param {string} cwd
2458
- * @param {PreviewData} data
2459
- * @param {string} dir the preview folder
2460
- * @param {string[]} targets absolute paths, without extension
2461
- * @returns {{importers: string[], tooBig: boolean}}
2462
- */
2463
- function pageImporters(cwd, data, dir, targets) {
2464
- const wanted = new Set(targets);
2465
- if (!wanted.size) return {importers: [], tooBig: false};
2466
- const names = [...new Set(targets.map(t => path.basename(t)))];
2467
- const own = new Set(data.files.map(f => path.join(dir, f)));
2468
- const aliases = tsconfigAliases(cwd);
2469
- /** @type {Set<string>} */
2470
- const out = new Set();
2471
- let files = 0;
2472
- let tooBig = false;
2473
- /** @param {string} file @param {string} spec */
2474
- const resolves = (file, spec) => {
2475
- const alias = aliases.find(x => spec.startsWith(x.prefix));
2476
- const bases = alias
2477
- ? alias.to.map(t => path.join(t, spec.slice(alias.prefix.length)))
2478
- : spec.startsWith('@/')
2479
- ? [path.join(cwd, 'src', spec.slice(2)), path.join(cwd, spec.slice(2))]
2480
- : spec.startsWith('.')
2481
- ? [path.resolve(path.dirname(file), spec)]
2482
- : [];
2483
- return bases.some(
2484
- b =>
2485
- wanted.has(b.replace(/\.(tsx|ts|jsx|js|mjs|cjs)$/, '')) ||
2486
- wanted.has(path.join(b, 'index')),
2487
- );
2488
- };
2489
- /** @param {any} node @param {(spec: string) => void} found */
2490
- const specifiers = (node, found) => {
2491
- if (!node || typeof node !== 'object') return;
2492
- if (Array.isArray(node)) {
2493
- for (const x of node) specifiers(x, found);
2494
- return;
2495
- }
2496
- const text = (/** @type {any} */ n) =>
2497
- n?.type === 'StringLiteral'
2498
- ? n.value
2499
- : n?.type === 'TemplateLiteral' && n.expressions.length === 0
2500
- ? n.quasis.map((/** @type {any} */ q) => q.value.cooked).join('')
2501
- : null;
2502
- if (
2503
- (node.type === 'ImportDeclaration' ||
2504
- node.type === 'ExportNamedDeclaration' ||
2505
- node.type === 'ExportAllDeclaration') &&
2506
- node.source
2507
- ) {
2508
- const t = text(node.source);
2509
- if (t != null) found(t);
2510
- } else if (node.type === 'ImportExpression') {
2511
- const t = text(node.source);
2512
- if (t != null) found(t);
2513
- } else if (
2514
- node.type === 'CallExpression' &&
2515
- (node.callee?.type === 'Import' ||
2516
- (node.callee?.type === 'Identifier' && node.callee.name === 'require'))
2517
- ) {
2518
- const t = text(node.arguments?.[0]);
2519
- if (t != null) found(t);
2520
- } else if (
2521
- node.type === 'TSImportType' ||
2522
- node.type === 'TSExternalModuleReference'
2523
- ) {
2524
- const t = text(node.argument ?? node.expression);
2525
- if (t != null) found(t);
2526
- }
2527
- for (const [k, v] of Object.entries(node))
2528
- if (
2529
- k !== 'loc' &&
2530
- k !== 'start' &&
2531
- k !== 'end' &&
2532
- v &&
2533
- typeof v === 'object'
2534
- )
2535
- specifiers(v, found);
2536
- };
2537
- /** @param {string} at */
2538
- const walk = at => {
2539
- if (tooBig) return;
2540
- /** @type {fs.Dirent[]} */
2541
- let entries;
2542
- try {
2543
- entries = fs.readdirSync(at, {withFileTypes: true});
2544
- } catch {
2545
- return;
2546
- }
2547
- for (const e of entries) {
2548
- const full = path.join(at, e.name);
2549
- if (e.isDirectory()) {
2550
- if (!NOT_SOURCE.has(e.name) && !e.name.startsWith('.')) walk(full);
2551
- if (tooBig) return;
2552
- continue;
2553
- }
2554
- if (!/\.(tsx|ts|jsx|js|mjs|cjs|mdx)$/.test(e.name) || own.has(full))
2555
- continue;
2556
- if (e.name.endsWith('.d.ts')) continue;
2557
- if (++files > IMPORTER_SCAN_MAX) {
2558
- tooBig = true;
2559
- return;
2560
- }
2561
- /** @type {string} */
2562
- let source;
2563
- try {
2564
- source = fs.readFileSync(full, 'utf8');
2565
- } catch {
2566
- continue;
2567
- }
2568
- // Only a file that names a target's file name can import it.
2569
- if (!names.some(n => source.includes(n))) continue;
2570
- /** @type {string[]} */
2571
- const specs = [];
2572
- try {
2573
- const ast = parseModule(
2574
- e.name.endsWith('.mdx')
2575
- ? source
2576
- .split('\n')
2577
- .filter(l => /^\s*(import|export)\b/.test(l))
2578
- .join('\n')
2579
- : source,
2580
- {
2581
- sourceType: 'unambiguous',
2582
- errorRecovery: true,
2583
- plugins: [
2584
- 'jsx',
2585
- ...(/\.(ts|tsx|mts|cts)$/.test(e.name)
2586
- ? [/** @type {const} */ ('typescript')]
2587
- : []),
2588
- ],
2589
- },
2590
- );
2591
- specifiers(ast.program, spec => specs.push(spec));
2592
- } catch {
2593
- // Not parsed: read its import strings as text.
2594
- for (const m of source.matchAll(
2595
- /(?:from\s*|import\s*\(\s*|require\s*\(\s*|import\s+)['"`]([^'"`$]+)['"`]/g,
2596
- ))
2597
- specs.push(m[1]);
2598
- }
2599
- if (specs.some(sp => resolves(full, sp))) out.add(shown(cwd, full));
2600
- }
2601
- };
2602
- walk(cwd);
2603
- return {importers: [...out].sort(), tooBig};
2604
- }
2605
-
2606
2546
  /**
2607
2547
  * Page files in the preview folder that theme-preview.json does not list:
2608
2548
  * a stopped change can leave one behind when its step record is damaged.
@@ -2614,7 +2554,7 @@ function unrecordedPages(dir) {
2614
2554
  let listed = [];
2615
2555
  try {
2616
2556
  const files = JSON.parse(
2617
- fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'),
2557
+ readRegularFile(path.join(dir, PREVIEW_DATA), 'utf8'),
2618
2558
  )?.files;
2619
2559
  if (Array.isArray(files)) listed = files.map(String);
2620
2560
  } catch {
@@ -2711,7 +2651,7 @@ function recoverPreview(cwd, dir) {
2711
2651
  return `removed ${shown(cwd, pendingFile)}, a damaged step record of a preview change that was stopped${strays.length ? `; ${strays.join(', ')} ${strays.length > 1 ? 'are' : 'is'} in no preview record and may be from that change, so ${strays.length > 1 ? 'they stay' : 'it stays'} until you remove ${strays.length > 1 ? 'them' : 'it'}` : ''}`;
2712
2652
  };
2713
2653
  try {
2714
- p = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
2654
+ p = JSON.parse(readRegularFile(pendingFile, 'utf8'));
2715
2655
  } catch (e) {
2716
2656
  // No step record: temp files a stopped command left (one killed before
2717
2657
  // it wrote the record) go, once their process is gone.
@@ -2738,7 +2678,7 @@ function recoverPreview(cwd, dir) {
2738
2678
  // the record stays as it was; else it is finished.
2739
2679
  const route = (() => {
2740
2680
  try {
2741
- return fs.readFileSync(inside('page.tsx'));
2681
+ return readRegularFile(inside('page.tsx'));
2742
2682
  } catch {
2743
2683
  return null;
2744
2684
  }
@@ -2749,7 +2689,7 @@ function recoverPreview(cwd, dir) {
2749
2689
  /** @param {string} rel */
2750
2690
  const onDisk = rel => {
2751
2691
  try {
2752
- return fs.readFileSync(inside(rel));
2692
+ return readRegularFile(inside(rel));
2753
2693
  } catch {
2754
2694
  return null;
2755
2695
  }
@@ -2845,7 +2785,7 @@ function undoStopped(cwd, dir, record, old) {
2845
2785
  /** @param {string} rel */
2846
2786
  const onDisk = rel => {
2847
2787
  try {
2848
- return fs.readFileSync(inside(rel));
2788
+ return readRegularFile(inside(rel));
2849
2789
  } catch {
2850
2790
  return null;
2851
2791
  }
@@ -2899,17 +2839,14 @@ function movedPages(cwd, dir, data) {
2899
2839
  /** @type {string | null} */
2900
2840
  let text = null;
2901
2841
  try {
2902
- text = fs.readFileSync(
2842
+ text = readRegularFile(
2903
2843
  confined(path.join(dir, from), dir, 'a preview file'),
2904
2844
  'utf8',
2905
2845
  );
2906
2846
  } catch {
2907
2847
  // Gone already: only the record moves.
2908
2848
  }
2909
- if (
2910
- fs.existsSync(target) &&
2911
- (text == null || fs.readFileSync(target, 'utf8') !== text)
2912
- )
2849
+ if (fs.existsSync(target) && (text == null || regularText(target) !== text))
2913
2850
  refuse(
2914
2851
  E.ERR_FILE_EXISTS,
2915
2852
  `${shown(cwd, target)} exists and the preview did not write it; the preview moves its pages there.`,
@@ -2999,11 +2936,13 @@ async function buildWorn(cwd, theme, options, notes) {
2999
2936
  const slug = theme.name;
3000
2937
  /** @type {string | null} */
3001
2938
  let why = null;
2939
+ /** What the build reports (the pictures it removed). @type {string[]} */
2940
+ let built = [];
3002
2941
  const build = async () => {
3003
2942
  const t = loadTheme(cwd, slug);
3004
2943
  why = staleBuild(cwd, slug, t);
3005
2944
  if (!why) return;
3006
- await buildTheme(await context(cwd), slug, t);
2945
+ built = (await buildTheme(await context(cwd), slug, t)).notes;
3007
2946
  };
3008
2947
  await (typeof options?.lockTheme === 'function'
3009
2948
  ? options.lockTheme(slug, build)
@@ -3011,6 +2950,7 @@ async function buildWorn(cwd, theme, options, notes) {
3011
2950
  if (why)
3012
2951
  notes.push(
3013
2952
  `built ${shown(cwd, themeFiles(cwd, slug).dir)}/ first: its build was not current (${why})`,
2953
+ ...built,
3014
2954
  );
3015
2955
  }
3016
2956
 
@@ -3021,6 +2961,13 @@ const COLORS_PAGE = wordTable({
3021
2961
  file: `${PAGES_DIR}/colors`,
3022
2962
  });
3023
2963
 
2964
+ /** The default pages a preview starts with, which `--template` adds back. */
2965
+ const DEFAULT_PAGE_IDS = Object.freeze([
2966
+ 'overview',
2967
+ 'components',
2968
+ COLORS_PAGE.id,
2969
+ ]);
2970
+
3024
2971
  /**
3025
2972
  * The Colors page source of a theme, and whether the theme has generated
3026
2973
  * colors. The page imports the generated color module, so it follows every
@@ -3205,8 +3152,11 @@ function dirFlag(cwd, dir) {
3205
3152
  */
3206
3153
  export async function refreshPreviewRoute(cwd, slug) {
3207
3154
  const at = previewDir(cwd, undefined, {optional: true});
3155
+ // The same previews `see` names: the usual folder, the recorded ones,
3156
+ // and any in the routes folders that wear the theme (a folder renamed by
3157
+ // hand, or one whose record was lost).
3208
3158
  const dirs = [
3209
- ...new Set([...(at ? [at.dir] : []), ...recordedPreviews(cwd, slug)]),
3159
+ ...new Set([...(at ? [at.dir] : []), ...themePreviews(cwd, slug)]),
3210
3160
  ];
3211
3161
  let changed = false;
3212
3162
  /** @type {string[]} */
@@ -3234,17 +3184,16 @@ export async function refreshPreviewRoute(cwd, slug) {
3234
3184
  ).filter(w => {
3235
3185
  const file = confined(path.join(dir, w.rel), dir, 'a preview file');
3236
3186
  if (!data.files.includes(w.rel)) return false;
3237
- if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === w.text)
3238
- return false;
3187
+ if (regularText(file) === w.text) return false;
3239
3188
  if (editedByHand(dir, data, w.rel)) {
3240
3189
  const standIn =
3241
3190
  w.rel === `${COLORS_PAGE.file}.tsx` &&
3242
- fs.readFileSync(file, 'utf8').includes(`${slug}.palette`) &&
3191
+ Boolean(regularText(file)?.includes(`${slug}.palette`)) &&
3243
3192
  paletteStandIn(cwd, slug);
3244
3193
  stale.push(
3245
3194
  standIn
3246
3195
  ? `${shown(cwd, file)} (changed by hand, so it is kept; the theme has no generated colors now, so ${standIn}, which the page imports, holds an empty stand-in that keeps the app building. Give the page another name if you want to keep your changes, then run ${PREVIEW} add)`
3247
- : shown(cwd, file),
3196
+ : `${shown(cwd, file)} (changed by hand, so it does not follow this change: move it out of ${shownDir(cwd, dir)}/, keeping your copy elsewhere in the app and importing nothing from the preview folder, then run ${PREVIEW} add${dirFlag(cwd, dir)} to write it again)`,
3248
3197
  );
3249
3198
  return false;
3250
3199
  }
@@ -3260,7 +3209,20 @@ export async function refreshPreviewRoute(cwd, slug) {
3260
3209
  `${shownDir(cwd, dir)}/ (${slug} has generated colors now; ${PREVIEW} add${dirFlag(cwd, dir)} adds its Colors page)`,
3261
3210
  );
3262
3211
  if (!writes.length) continue;
3263
- commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3212
+ // A route that cannot be written (its permissions, a folder in its
3213
+ // place) does not follow this change: said, never a quiet ok.
3214
+ try {
3215
+ commitPreview(cwd, dir, data, writes, [], `${EDITOR} show ${slug}`);
3216
+ } catch (e) {
3217
+ const code =
3218
+ /\b(E[A-Z]{2,})\b/.exec(
3219
+ `${/** @type {any} */ (e)?.code ?? ''} ${e instanceof Error ? e.message : ''}`,
3220
+ )?.[1] ?? 'it could not be written';
3221
+ stale.push(
3222
+ `${shownDir(cwd, dir)}/ (could not be written: ${code}, so the in-app preview does not follow this change; fix its permissions, then ${PREVIEW} add${dirFlag(cwd, dir)} writes it again)`,
3223
+ );
3224
+ continue;
3225
+ }
3264
3226
  changed = true;
3265
3227
  }
3266
3228
  return {changed, stale};
@@ -3284,7 +3246,7 @@ const previewsFile = (cwd, slug) =>
3284
3246
  */
3285
3247
  function recordedPreviews(cwd, slug) {
3286
3248
  try {
3287
- const list = JSON.parse(fs.readFileSync(previewsFile(cwd, slug), 'utf8'));
3249
+ const list = JSON.parse(readRegularFile(previewsFile(cwd, slug), 'utf8'));
3288
3250
  return (Array.isArray(list) ? list : [])
3289
3251
  .map(rel => path.resolve(cwd, String(rel)))
3290
3252
  .filter(dir => !path.relative(cwd, dir).startsWith('..'));
@@ -3339,11 +3301,53 @@ function routesOf(cwd, at) {
3339
3301
  function previewPath(cwd, at) {
3340
3302
  const app = routesOf(cwd, at);
3341
3303
  if (!app) return null;
3304
+ // A folder Next does not serve (_private, @slot, an intercepting route):
3305
+ // no URL, as add refuses it.
3306
+ if (unservedWhy(cwd, at.dir)) return null;
3342
3307
  const segs = urlSegments(app, at.dir);
3343
3308
  if (segs.some(seg => /^\[.+\]$/.test(seg))) return null;
3344
3309
  const base = nextBasePath(cwd);
3345
3310
  if (base == null) return null;
3346
- return `${base}/${segs.map(seg => encodeURIComponent(seg)).join('/')}`;
3311
+ // A folder named %5F… is served at the decoded name (`_x`), encoded as a
3312
+ // URL segment needs it.
3313
+ const decoded = (/** @type {string} */ seg) => {
3314
+ try {
3315
+ return decodeURIComponent(seg);
3316
+ } catch {
3317
+ return seg;
3318
+ }
3319
+ };
3320
+ return `${base}/${segs.map(seg => encodeURIComponent(decoded(seg))).join('/')}`;
3321
+ }
3322
+
3323
+ /**
3324
+ * Why a preview folder found in the routes folder is not served, or null.
3325
+ * @param {string} cwd
3326
+ * @param {string} dir
3327
+ * @returns {string | null}
3328
+ */
3329
+ function unservedWhy(cwd, dir) {
3330
+ const app = routesOf(cwd, {dir, app: null});
3331
+ if (!app) return null;
3332
+ // The same rules add keeps: src/app/ while app/ is what Next serves, and
3333
+ // a next.config whose page extensions leave out page.tsx.
3334
+ const served = [path.join(cwd, 'app'), path.join(cwd, 'src', 'app')].find(
3335
+ r => fs.existsSync(r) && fs.statSync(r).isDirectory(),
3336
+ );
3337
+ if (served && path.resolve(app) !== path.resolve(served))
3338
+ return `Next serves ${shown(cwd, served)}/ instead of ${shown(cwd, app)}/ when both are there`;
3339
+ try {
3340
+ const exts = readNextConfig(cwd).pageExtensions;
3341
+ if (exts && !exts.includes('tsx'))
3342
+ return `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx`;
3343
+ } catch {
3344
+ // A config this cannot read is not a reason to hide the URL.
3345
+ }
3346
+ // A [param] folder is served, with a value for it; only _private, @slot
3347
+ // and intercepting folders are not.
3348
+ const segs = path.relative(app, dir).split(path.sep);
3349
+ if (!segs.some(x => /^[_@]/.test(x) || INTERCEPT.test(x))) return null;
3350
+ return unroutedSegment(app, dir);
3347
3351
  }
3348
3352
 
3349
3353
  /**
@@ -3374,27 +3378,59 @@ function pageUrls(cwd, at, ids) {
3374
3378
  * @param {'colors' | 'components' | 'overview'} focus
3375
3379
  * @param {{code: string, cause: string} | null} [notChecked] why the change
3376
3380
  * could not be rendered
3381
+ * @param {{pictureProblem?: string | null, stale?: string[]}} [extra] this
3382
+ * result's picture problem (what kept --png from taking pictures) and its
3383
+ * previewStale entries (an in-app preview changed by hand)
3377
3384
  * @returns {string}
3378
3385
  */
3379
- export function seeLine(cwd, slug, focus, notChecked = null) {
3386
+ export function seeLine(cwd, slug, focus, notChecked = null, extra = {}) {
3380
3387
  /** @type {string[]} */
3381
3388
  const urls = [];
3382
3389
  /** Previews whose URL depends on the app's routing. @type {string[]} */
3383
3390
  const unplain = [];
3384
- // The previews recorded for the theme, and any found in the routes
3385
- // folders that wear it (a folder renamed by hand), as remove finds them.
3386
- const dirs = [
3387
- ...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)]),
3388
- ];
3391
+ /** Previews in a folder Next does not serve. @type {string[]} */
3392
+ const unserved = [];
3393
+ /** Their folders, as --path takes them. @type {string[]} */
3394
+ const unservedDirs = [];
3395
+ /** @type {string[]} */
3396
+ const stale = extra.stale ?? [];
3397
+ /** Previews whose route was changed by hand. @type {string[]} */
3398
+ const handEdited = [];
3399
+ /** Previews whose record is damaged. @type {string[]} */
3400
+ const damaged = [];
3401
+ const dirs = themePreviews(cwd, slug);
3389
3402
  for (const dir of dirs) {
3390
3403
  /** @type {any} */
3391
3404
  let data;
3392
3405
  try {
3393
- data = JSON.parse(fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'));
3394
- } catch {
3406
+ data = JSON.parse(readRegularFile(path.join(dir, PREVIEW_DATA), 'utf8'));
3407
+ } catch (e) {
3408
+ // A record that is there but damaged: the preview commands refuse
3409
+ // it until it is fixed, so no add tip, the repair instead.
3410
+ if (
3411
+ fs.existsSync(path.join(dir, PREVIEW_DATA)) &&
3412
+ !(/** @type {any} */ (e)?.code)
3413
+ )
3414
+ damaged.push(shownDir(cwd, dir));
3395
3415
  continue;
3396
3416
  }
3397
3417
  if (data?.theme !== slug) continue;
3418
+ const why = unservedWhy(cwd, dir);
3419
+ if (why) {
3420
+ unserved.push(`${shownDir(cwd, dir)}/ (${why})`);
3421
+ unservedDirs.push(shownDir(cwd, dir));
3422
+ continue;
3423
+ }
3424
+ if (
3425
+ stale.some(
3426
+ f =>
3427
+ f.startsWith(`${shownDir(cwd, dir)}/`) &&
3428
+ /changed by hand|could not be written/.test(f),
3429
+ )
3430
+ ) {
3431
+ handEdited.push(shownDir(cwd, dir));
3432
+ continue;
3433
+ }
3398
3434
  const ids = Array.isArray(data?.pages)
3399
3435
  ? data.pages.map((/** @type {any} */ x) => String(x?.id))
3400
3436
  : [];
@@ -3408,16 +3444,59 @@ export function seeLine(cwd, slug, focus, notChecked = null) {
3408
3444
  );
3409
3445
  }
3410
3446
  const f = themeFiles(cwd, slug);
3447
+ // What keeps --png from taking pictures, when this result's own picture
3448
+ // run failed (a file of yours named like a picture).
3449
+ // A command that only takes pictures, whatever this one was (an undo run
3450
+ // again undoes another change; new refuses a theme that exists).
3451
+ const pngNote = extra.pictureProblem
3452
+ ? `--png took no pictures: ${extra.pictureProblem}`
3453
+ : `${EDITOR} show ${slug} --png takes pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3411
3454
  const own = notChecked
3412
3455
  ? /could not be written/.test(notChecked.cause)
3413
3456
  ? `the change is saved, but ${notChecked.cause}; --png takes no pictures until that is fixed`
3414
3457
  : `the change is saved, but the components could not be rendered here (${notChecked.cause}), so ${shown(cwd, f.preview)} still shows the theme as it was and --png takes no pictures until that is fixed`
3415
- : `look without changing your app: open or screenshot ${shown(cwd, f.preview)} (one self-contained page, current after this change; ${EDITOR} show ${slug} also writes ${shown(cwd, f.sheet)}, every component), or run it with --png for pictures in ${shownDir(cwd, f.dir)}/ with no dev server (it needs a Playwright or a Chrome)`;
3458
+ : `look without changing your app: open or screenshot ${shown(cwd, f.preview)} (one self-contained page, current after this change; ${EDITOR} show ${slug} also writes ${shown(cwd, f.sheet)}, every component), or ${pngNote}`;
3459
+ const edited = handEdited.length
3460
+ ? `; the in-app preview in ${handEdited.slice(0, 2).join(', ')}/ ${stale.some(f => /could not be written/.test(f)) && !stale.some(f => /changed by hand/.test(f)) ? 'could not be written' : 'was changed by hand'}, so it does not follow this change (previewStale says what to move out, then ${PREVIEW} add writes it again)`
3461
+ : '';
3416
3462
  if (urls.length)
3417
- return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}`;
3463
+ return `${own}; in the running app: open ${urls.slice(0, 2).join(' or ')}${edited}`;
3418
3464
  if (unplain.length)
3419
- return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing`;
3420
- return `${own}; to see it inside your app, ${PREVIEW} add puts the preview pages there, each at its own URL`;
3465
+ return `${own}; the in-app preview is in ${unplain.slice(0, 2).join(', ')}, at a URL that depends on the app's routing${edited}`;
3466
+ if (unserved.length) {
3467
+ // What fixes it, by why it is not served: add's own answer for each.
3468
+ const why = unserved.join(' ');
3469
+ const fix = /Next serves .* when both are there/.test(why)
3470
+ ? `${PREVIEW} remove --path ${quoteCommandArgument(unservedDirs[0])}, then ${PREVIEW} add --theme ${slug} puts it in the folder Next serves`
3471
+ : /pageExtensions/.test(why)
3472
+ ? `add "tsx" to pageExtensions in next.config so Next serves the preview's page.tsx`
3473
+ : `move it back into a folder Next routes, or make one there with ${PREVIEW} add --theme ${slug} --path <a routed folder>`;
3474
+ return `${own}; the in-app preview is in ${unserved.slice(0, 2).join(', ')}, which the app does not serve: ${fix}${edited}`;
3475
+ }
3476
+ if (edited) return `${own}${edited}`;
3477
+ if (damaged.length)
3478
+ return `${own}; the in-app preview in ${damaged.slice(0, 2).join(', ')}/ has a damaged ${PREVIEW_DATA}, so it does not follow this change: fix it by hand, or give the folder a new name that starts with _ and run ${PREVIEW} add${editorThemeCount(cwd) > 1 ? ` --theme ${slug}` : ''}`;
3479
+ // With more than one editor theme, a bare add may wear another one.
3480
+ const many = editorThemeCount(cwd) > 1;
3481
+ // An add this app takes; else a new app of its own, with the preview.
3482
+ return addTakes(cwd, null)
3483
+ ? `${own}; to see it inside your app, ${PREVIEW} add${many ? ` --theme ${slug}` : ''} puts the preview pages there, each at its own URL`
3484
+ : `${own}; this app has no routes folder for the preview pages, so ${appCommand(freeAppFolder(cwd), slug)} makes a new app with them`;
3485
+ }
3486
+
3487
+ /**
3488
+ * How many editor themes the project has.
3489
+ * @param {string} cwd
3490
+ */
3491
+ function editorThemeCount(cwd) {
3492
+ const root = themeFiles(cwd, 'x').root;
3493
+ try {
3494
+ return fs
3495
+ .readdirSync(root)
3496
+ .filter(d => fs.existsSync(themeFiles(cwd, d).settings)).length;
3497
+ } catch {
3498
+ return 0;
3499
+ }
3421
3500
  }
3422
3501
 
3423
3502
  /**
@@ -3473,6 +3552,39 @@ function skipReason(s) {
3473
3552
  ].join(' and ');
3474
3553
  }
3475
3554
 
3555
+ /**
3556
+ * Up to `n` of these page templates that this app can show: each one's
3557
+ * packages installed and no StyleX compiler needed, as add itself checks.
3558
+ * The only pages a suggestion names.
3559
+ * @param {string} cwd
3560
+ * @param {string} appRoot the app whose packages a page needs
3561
+ * @param {string[]} ids in order of preference
3562
+ * @param {number} n
3563
+ * @returns {Promise<string[]>}
3564
+ */
3565
+ async function showablePages(cwd, appRoot, ids, n) {
3566
+ /** @type {string[]} */
3567
+ const out = [];
3568
+ for (const id of ids) {
3569
+ if (out.length >= n) break;
3570
+ try {
3571
+ const shownTemplate = /** @type {any} */ (
3572
+ await template(id, {cwd, type: 'page'})
3573
+ );
3574
+ const needs = pageNeeds(appRoot, shownTemplate.data.source);
3575
+ if (
3576
+ !needs.missingPackages.length &&
3577
+ !needs.notInstalled.length &&
3578
+ !needs.stylexCompiler
3579
+ )
3580
+ out.push(id);
3581
+ } catch {
3582
+ // A template that does not load is not suggested.
3583
+ }
3584
+ }
3585
+ return out;
3586
+ }
3587
+
3476
3588
  /**
3477
3589
  * The page templates for a description, best first, each with why: the
3478
3590
  * build ranking's picks, then the template search's, so a page the app
@@ -3485,9 +3597,20 @@ function skipReason(s) {
3485
3597
  * @param {string} cwd
3486
3598
  * @param {string[]} notes notes for the result
3487
3599
  * @param {string} flags the caller's other flags, for the suggestions
3600
+ * @param {string | null} [appRoot] the app whose packages a page needs
3601
+ * @param {{typed: string, why: string} | null} [cut] a long description
3602
+ * cut to its first words: as typed, and the sentence saying so, for a
3603
+ * refusal
3488
3604
  * @returns {Promise<Array<{name: string, displayName: string, why: string}>>}
3489
3605
  */
3490
- async function rankedPages(words, cwd, notes, flags) {
3606
+ async function rankedPages(
3607
+ words,
3608
+ cwd,
3609
+ notes,
3610
+ flags,
3611
+ appRoot = null,
3612
+ cut = null,
3613
+ ) {
3491
3614
  const kit =
3492
3615
  /** @type {import('../build/build.type.mjs').BuildKitResponse} */ (
3493
3616
  await build(words, {cwd})
@@ -3571,15 +3694,8 @@ async function rankedPages(words, cwd, notes, flags) {
3571
3694
  const label = name => listed.find(t => t.id === name)?.name ?? name;
3572
3695
  const suggest = (/** @type {string[]} */ list) =>
3573
3696
  list.slice(0, 3).map(n => `${PREVIEW} add --template ${n}${flags}`);
3574
- // With no page close, a few pages that need nothing more, and the list.
3575
- const fallback = [
3576
- ...suggest(
3577
- ['dashboard', 'settings', 'login'].filter(id =>
3578
- listed.some(t => t.id === id),
3579
- ),
3580
- ),
3581
- formatCliCommand('template --list --type page', cwd),
3582
- ];
3697
+ /** @param {string[]} ids */
3698
+ const showableOf = ids => showablePages(cwd, appRoot ?? cwd, ids, 3);
3583
3699
  // No page relates when the ranking fell back to a frame with no direct
3584
3700
  // match, and no page the search found matches three words of the request
3585
3701
  // or two fifths of them.
@@ -3604,19 +3720,34 @@ async function rankedPages(words, cwd, notes, flags) {
3604
3720
  !found.some(
3605
3721
  (/** @type {any} */ r) => !frames.has(r.name) && termsMatched(r) >= 2,
3606
3722
  )));
3607
- if (unrelated)
3723
+ if (unrelated) {
3724
+ // With no page close, a few pages this app can show, and the list.
3725
+ const offered = await showableOf(
3726
+ pages.length
3727
+ ? pages
3728
+ : [
3729
+ ...['dashboard', 'settings', 'login'],
3730
+ ...listed.map(t => t.id),
3731
+ ].filter(
3732
+ (id, i, all) =>
3733
+ all.indexOf(id) === i &&
3734
+ listed.some(t => t.id === id) &&
3735
+ !frames.has(id),
3736
+ ),
3737
+ );
3608
3738
  refuse(
3609
3739
  E.ERR_NOT_FOUND,
3610
- `No page template relates to "${words}". Name a page to add it anyway.`,
3740
+ cut
3741
+ ? `No page template relates to "${cut.typed}". ${cut.why}: put the words that name the page first, or name a page to add it anyway.`
3742
+ : `No page template relates to "${words}". Name a page to add it anyway.`,
3611
3743
  {
3612
- run: pages.length
3613
- ? [
3614
- ...suggest(pages),
3615
- formatCliCommand('template --list --type page', cwd),
3616
- ]
3617
- : fallback,
3744
+ run: [
3745
+ ...suggest(offered),
3746
+ formatCliCommand('template --list --type page', cwd),
3747
+ ],
3618
3748
  },
3619
3749
  );
3750
+ }
3620
3751
  if (skippedFrames.length)
3621
3752
  notes.push(
3622
3753
  `left out ${skippedFrames.join(', ')}: app frames, not pages (add one with --template <id>)`,
@@ -3847,6 +3978,19 @@ function wornTheme(cwd, slug, again, without) {
3847
3978
  .replace(/^\.?\/?themes\//, '')
3848
3979
  .replace(/\/+$/, '');
3849
3980
  const themes = editedThemes(cwd);
3981
+ // An empty name: the same preview command with each theme here, and
3982
+ // without --theme (its default), never a look at a theme instead.
3983
+ if (!name)
3984
+ refuse(
3985
+ code ?? E.ERR_INVALID_ARGUMENT,
3986
+ String(/** @type {any} */ (e)?.message).replace(
3987
+ /\s*Nothing was changed\.$/,
3988
+ '',
3989
+ ),
3990
+ {
3991
+ run: [...themes.map(t => again(t)), `${again(null)} # ${without}`],
3992
+ },
3993
+ );
3850
3994
  if (!themes.includes(name) && isPackageTheme(cwd, name)) {
3851
3995
  const missing =
3852
3996
  name !== 'neutral' && !installed(cwd, `@astryxdesign/theme-${name}`);
@@ -3866,6 +4010,17 @@ function wornTheme(cwd, slug, again, without) {
3866
4010
  },
3867
4011
  );
3868
4012
  }
4013
+ // A theme of a workspace app below (from the workspace root): the same
4014
+ // command, run from that app.
4015
+ const owners = nextAppsUnder(cwd).filter(a =>
4016
+ fs.existsSync(themeFiles(a.root, name).settings),
4017
+ );
4018
+ if (!themes.includes(name) && owners.length)
4019
+ refuse(
4020
+ E.ERR_UNKNOWN_THEME,
4021
+ `There is no theme "${slug}" under themes/ here; ${owners.map(a => `${shown(cwd, a.root)}/themes/${name}/`).join(', ')} ${owners.length > 1 ? 'hold' : 'holds'} it, in the app that uses it.`,
4022
+ {run: owners.map(a => `${cdTo(shown(cwd, a.root))} && ${again(name)}`)},
4023
+ );
3869
4024
  const near = themes.includes(name) ? [name] : nearest(name, themes);
3870
4025
  if (near.length)
3871
4026
  refuse(
@@ -3902,9 +4057,19 @@ const BASE_THEMES = path.join(CLI_PACKAGE, 'assets', 'templates', 'themes');
3902
4057
  * @param {string} cwd
3903
4058
  * @param {string} id
3904
4059
  * @param {string} flags the caller's other flags
4060
+ * @param {() => Promise<readonly string[]>} [defaults] the default pages it
4061
+ * can add now, which a typo may name (asked only for a refusal)
4062
+ * @param {string | null} [appRoot] the app whose packages a page needs: a
4063
+ * typo names only a page template it can add now
3905
4064
  * @returns {Promise<{name: string, displayName: string, why: string}>}
3906
4065
  */
3907
- async function namedTemplate(cwd, id, flags) {
4066
+ async function namedTemplate(
4067
+ cwd,
4068
+ id,
4069
+ flags,
4070
+ defaults = async () => DEFAULT_PAGE_IDS,
4071
+ appRoot = null,
4072
+ ) {
3908
4073
  const pages = await pageTemplates(cwd);
3909
4074
  // Page ids are lowercase: LOGIN names login.
3910
4075
  const hit =
@@ -3933,11 +4098,15 @@ async function namedTemplate(cwd, id, flags) {
3933
4098
  /** @type {any} */ (await template(undefined, {list: true, cwd})).data
3934
4099
  );
3935
4100
  const other = all.find(t => t.id === id);
3936
- const near = nearest(
3937
- id.toLowerCase(),
3938
- pages.map(t => t.id),
3939
- 5,
3940
- );
4101
+ // Every page --template adds now is a candidate: the default pages it can
4102
+ // add (which the template list never shows) and the page templates.
4103
+ // A page template the app cannot add now (a package it needs is missing)
4104
+ // is never offered: following it would be refused.
4105
+ const nearPages = pages.map(t => t.id).filter(n => typoNear(id, n));
4106
+ const near = [
4107
+ ...(await defaults()).filter(n => typoNear(id, n)),
4108
+ ...(await showablePages(cwd, appRoot ?? cwd, nearPages, nearPages.length)),
4109
+ ];
3941
4110
  refuse(
3942
4111
  E.ERR_UNKNOWN_TEMPLATE,
3943
4112
  other
@@ -4043,17 +4212,28 @@ function themeArg(v) {
4043
4212
  async function addPreview(description, options, box) {
4044
4213
  options = {...options, theme: themeArg(options.theme)};
4045
4214
  const {cwd = process.cwd()} = options;
4046
- if (isOutsideProject(cwd))
4047
- refuse(
4048
- E.ERR_PROJECT_REQUIRED,
4049
- 'No package.json here, so there is no app to put the preview in.',
4050
- {
4051
- run: [
4052
- `${PREVIEW} add # run in your app`,
4053
- `${PREVIEW} app <dir> # a new starter app with the preview in it`,
4054
- ],
4055
- },
4056
- );
4215
+ // A workspace root, or a package that does not use Core, gets the shared
4216
+ // app finder's answer (the workspace's app to cd into, or what to
4217
+ // install); only with no package.json at or above is there no project.
4218
+ if (isOutsideProject(cwd)) {
4219
+ let d = path.resolve(cwd);
4220
+ while (
4221
+ !fs.existsSync(path.join(d, 'package.json')) &&
4222
+ path.dirname(d) !== d
4223
+ )
4224
+ d = path.dirname(d);
4225
+ if (fs.existsSync(path.join(d, 'package.json'))) requireProject(cwd);
4226
+ else
4227
+ refuse(
4228
+ E.ERR_PROJECT_REQUIRED,
4229
+ 'No package.json here, so there is no app to put the preview in.',
4230
+ {
4231
+ run: [
4232
+ `${PREVIEW} app <dir> # a new starter app with the preview in it`,
4233
+ ],
4234
+ },
4235
+ );
4236
+ }
4057
4237
  const pf =
4058
4238
  options.path != null ? ` --path ${quoteCommandArgument(options.path)}` : '';
4059
4239
  const tf =
@@ -4062,9 +4242,8 @@ async function addPreview(description, options, box) {
4062
4242
  : '';
4063
4243
  // A default page's id (overview, components, colors), as `remove` takes
4064
4244
  // it, adds exactly that page back (or is refused, saying why).
4065
- const DEFAULT_IDS = ['overview', 'components', COLORS_PAGE.id];
4066
4245
  const isDefault = (/** @type {unknown} */ v) =>
4067
- typeof v === 'string' && DEFAULT_IDS.includes(v.trim().toLowerCase());
4246
+ typeof v === 'string' && DEFAULT_PAGE_IDS.includes(v.trim().toLowerCase());
4068
4247
  // Beside another page asked for, it is refused below (drop one).
4069
4248
  const blank = (/** @type {unknown} */ v) => v == null || !String(v).trim();
4070
4249
  const askedId = [description, options.template]
@@ -4075,6 +4254,19 @@ async function addPreview(description, options, box) {
4075
4254
  askedId != null &&
4076
4255
  (blank(description) || isDefault(description)) &&
4077
4256
  (blank(options.template) || isDefault(options.template));
4257
+ // The command without --top, as typed: a default page as a word or
4258
+ // with --template, else the page --template names, else the default
4259
+ // pages (what preview add does with nothing named), never an arbitrary
4260
+ // page.
4261
+ const withoutTop = `${PREVIEW} add${
4262
+ askedId != null
4263
+ ? isDefault(description)
4264
+ ? ` ${askedId}`
4265
+ : ` --template ${askedId}`
4266
+ : !blank(options.template)
4267
+ ? ` --template ${quoteCommandArgument(String(options.template).trim())}`
4268
+ : ''
4269
+ }`;
4078
4270
  if (again) {
4079
4271
  description = undefined;
4080
4272
  options = {...options, template: undefined};
@@ -4082,53 +4274,75 @@ async function addPreview(description, options, box) {
4082
4274
  const said = (description ?? '').trim();
4083
4275
  const named =
4084
4276
  options.template == null ? null : String(options.template).trim();
4277
+ // An empty --template falls back to what preview add does without it
4278
+ // (the description's pages, else the default pages), never an arbitrary
4279
+ // page.
4085
4280
  if (named === '')
4086
- refuse(E.ERR_INVALID_ARGUMENT, '--template needs a page template id.', {
4087
- run: [
4088
- `${PREVIEW} add --template dashboard${tf}${pf}`,
4089
- formatCliCommand('template --list --type page', cwd),
4090
- ],
4091
- });
4092
- if (said && named != null)
4093
4281
  refuse(
4094
4282
  E.ERR_INVALID_ARGUMENT,
4095
- '--template names the page; a description asks the ranking to pick one, so drop one of them.',
4283
+ `--template needs a page template id; without it, preview add adds ${said ? 'the pages the description names' : 'the default pages'}.`,
4096
4284
  {
4097
4285
  run: [
4098
- `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
4099
- `${PREVIEW} add ${quoteCommandArgument(said)}${tf}${pf}`,
4286
+ `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${tf}${pf}`,
4287
+ formatCliCommand('template --list --type page', cwd),
4100
4288
  ],
4101
4289
  },
4102
4290
  );
4103
- const top = options.top == null ? 1 : Number(String(options.top));
4104
- if (options.top != null && !/^[1-3]$/.test(String(options.top)))
4291
+ if (said && named != null) {
4292
+ // The page --template names is offered only when this app can add it
4293
+ // now (a default page, or a template whose packages it has), as a
4294
+ // typo's pages are.
4295
+ const addable =
4296
+ isDefault(named) ||
4297
+ (await showablePages(cwd, appRootOf(cwd, cwd), [named], 1)).length > 0;
4105
4298
  refuse(
4106
4299
  E.ERR_INVALID_ARGUMENT,
4107
- `--top takes 1, 2 or 3, not "${String(options.top)}".`,
4300
+ `--template names the page; a description asks the ranking to pick one, so drop one of them.${addable ? '' : ` The ${named} page cannot be added here as it is (a package it needs is missing, or no page template has that id).`}`,
4108
4301
  {
4109
4302
  run: [
4110
- `${PREVIEW} add ${quoteCommandArgument(said || 'a sales dashboard')} --top 2${tf}${pf}`,
4303
+ ...(addable
4304
+ ? [
4305
+ `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`,
4306
+ ]
4307
+ : []),
4308
+ `${PREVIEW} add ${quoteCommandArgument(said)}${tf}${pf}`,
4111
4309
  ],
4112
4310
  },
4113
4311
  );
4114
- if (options.top != null && !said)
4312
+ }
4313
+ const top = options.top == null ? 1 : Number(String(options.top));
4314
+ if (options.top != null && !/^[1-3]$/.test(String(options.top))) {
4315
+ // The way on is read from what was typed: its exact reading (3 for
4316
+ // "3.0", " 3" or "three"), the nearest bound for an amount out of
4317
+ // range, else the default.
4318
+ const typed = wholeNumberOf(options.top);
4319
+ const offer = typed == null ? 1 : Math.min(3, Math.max(1, typed));
4115
4320
  refuse(
4116
4321
  E.ERR_INVALID_ARGUMENT,
4117
- named != null
4118
- ? '--top says how many ranked pages to add; --template names one page, so drop --top.'
4119
- : '--top says how many pages to add for a description, and there is none.',
4322
+ `--top takes 1, 2 or 3, not "${String(options.top)}".`,
4120
4323
  {
4121
- run: [
4122
- named != null
4123
- ? `${PREVIEW} add --template ${quoteCommandArgument(named)}${tf}${pf}`
4124
- : `${PREVIEW} add 'a sales dashboard' --top ${String(options.top)}${tf}${pf}`,
4125
- ],
4324
+ run: said
4325
+ ? [
4326
+ `${PREVIEW} add ${quoteCommandArgument(said)}${offer === 1 ? '' : ` --top ${offer}`}${tf}${pf}`,
4327
+ ]
4328
+ : [`${withoutTop}${tf}${pf}`],
4126
4329
  },
4127
4330
  );
4331
+ }
4332
+ if (options.top != null && !said)
4333
+ refuse(
4334
+ E.ERR_INVALID_ARGUMENT,
4335
+ named != null || askedId != null
4336
+ ? `--top says how many ranked pages to add; ${askedId ?? '--template'} names one page, so drop --top.`
4337
+ : '--top says how many pages to add for a description, and there is none; without one, preview add adds the default pages.',
4338
+ {run: [`${withoutTop}${tf}${pf}`]},
4339
+ );
4128
4340
  /** @type {string[]} */
4129
4341
  const notes = [];
4130
4342
  let words = said;
4131
4343
  const allWords = said ? said.split(/\s+/) : [];
4344
+ /** A description cut to its first words: as typed, and what was read. @type {{typed: string, why: string} | null} */
4345
+ let cut = null;
4132
4346
  if (allWords.length > MAX_WORDS) {
4133
4347
  const seen = new Set();
4134
4348
  words = allWords
@@ -4143,10 +4357,18 @@ async function addPreview(description, options, box) {
4143
4357
  notes.push(
4144
4358
  `the description has ${allWords.length} words; the first ${MAX_WORDS} different ones picked the page`,
4145
4359
  );
4360
+ cut = {
4361
+ typed: said ?? '',
4362
+ why: `Only the first ${MAX_WORDS} different words of a description are read, and this one has ${allWords.length}`,
4363
+ };
4146
4364
  }
4147
4365
  const retry = (/** @type {string | null} */ p) =>
4148
- `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4149
- const at = previewDir(cwd, options.path, {write: true, retry});
4366
+ `${PREVIEW} add${said ? ` ${quoteCommandArgument(said)}` : ''}${named != null ? ` --template ${quoteCommandArgument(named)}` : ''}${options.top != null ? ` --top ${quoteCommandArgument(String(options.top))}` : ''}${tf}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4367
+ const at = previewDir(cwd, options.path, {
4368
+ write: true,
4369
+ retry,
4370
+ theme: options.theme ?? null,
4371
+ });
4150
4372
  const recovered = recoverPreview(cwd, at.dir);
4151
4373
  if (recovered) notes.push(recovered);
4152
4374
  const unstyled = coreStylesheetMissing(cwd, at);
@@ -4185,6 +4407,8 @@ async function addPreview(description, options, box) {
4185
4407
  wornTheme(cwd, options.theme, againWith, without);
4186
4408
  data.theme = options.theme;
4187
4409
  } else if (data.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
4410
+ // Not gone when the route imports it from outside this project folder.
4411
+ refuseThemeAway(cwd, at.dir, data.theme, retry);
4188
4412
  const themes = editedThemes(cwd);
4189
4413
  data.theme = themes.length === 1 ? themes[0] : null;
4190
4414
  notes.push(
@@ -4285,9 +4509,42 @@ async function addPreview(description, options, box) {
4285
4509
  }
4286
4510
  } else {
4287
4511
  const flags = `${tf}${pf}`;
4512
+ // The default pages a typo may name: those this preview can add now (the
4513
+ // Colors page only for a theme with generated colors), and not already
4514
+ // in it.
4515
+ const addable = async () => {
4516
+ const can = [
4517
+ 'overview',
4518
+ 'components',
4519
+ ...(data.theme && (await colorsPage(cwd, at.dir, data.theme)).colors
4520
+ ? [COLORS_PAGE.id]
4521
+ : []),
4522
+ ];
4523
+ return can.filter(id => {
4524
+ const there = data.pages.find(p => p.id === id);
4525
+ return !(
4526
+ there && fs.existsSync(path.join(at.dir, `${there.file}.tsx`))
4527
+ );
4528
+ });
4529
+ };
4288
4530
  const picks = explicit
4289
- ? [await namedTemplate(cwd, /** @type {string} */ (named), flags)]
4290
- : await rankedPages(words, cwd, notes, flags);
4531
+ ? [
4532
+ await namedTemplate(
4533
+ cwd,
4534
+ /** @type {string} */ (named),
4535
+ flags,
4536
+ addable,
4537
+ appRootOf(cwd, at.dir),
4538
+ ),
4539
+ ]
4540
+ : await rankedPages(
4541
+ words,
4542
+ cwd,
4543
+ notes,
4544
+ flags,
4545
+ appRootOf(cwd, at.dir),
4546
+ cut,
4547
+ );
4291
4548
  for (const [i, pick] of picks.entries()) {
4292
4549
  if (add.length >= (explicit ? 1 : top)) break;
4293
4550
  const shownTemplate =
@@ -4334,7 +4591,7 @@ async function addPreview(description, options, box) {
4334
4591
  if (!add.length)
4335
4592
  refuse(
4336
4593
  E.ERR_DEP_MISSING,
4337
- `No page was added: ${skipped.map(s => `the ${s.page} page ${s.reason}`).join('; ')}.`,
4594
+ `No page was added: ${skipped.map(s => `the ${s.page} page ${s.reason}`).join('; ')}.${cut ? ` ${cut.why}, so the pages were picked from those: put the words that name the page first.` : ''}`,
4338
4595
  {
4339
4596
  run: [
4340
4597
  ...new Set(runs),
@@ -4451,7 +4708,7 @@ async function addPreview(description, options, box) {
4451
4708
  !refreshed.includes(p.id) &&
4452
4709
  !rewrote.includes(p.id) &&
4453
4710
  fs.existsSync(path.join(at.dir, `${p.file}.tsx`)) &&
4454
- fs.readFileSync(path.join(at.dir, `${p.file}.tsx`), 'utf8') !==
4711
+ regularText(path.join(at.dir, `${p.file}.tsx`)) !==
4455
4712
  writes.get(`${p.file}.tsx`)?.text
4456
4713
  )
4457
4714
  refreshed.push(p.id);
@@ -4491,10 +4748,17 @@ async function addPreview(description, options, box) {
4491
4748
  } catch {
4492
4749
  // A theme that does not load is reported where it is used.
4493
4750
  }
4494
- if (again)
4495
- notes.push(
4496
- `a default page's id brings back the default pages that are missing, as ${PREVIEW} add does`,
4751
+ // What happened: only the page asked for; the others come with a bare
4752
+ // add.
4753
+ if (again) {
4754
+ const stillMissing = DEFAULT_PAGE_IDS.filter(
4755
+ id => !data.pages.some(p => p.id === id),
4497
4756
  );
4757
+ if (stillMissing.length)
4758
+ notes.push(
4759
+ `only ${askedId} was added; ${PREVIEW} add with no page brings back the other default pages that are missing (${stillMissing.join(', ')})`,
4760
+ );
4761
+ }
4498
4762
  notes.push(...typeScriptNotes(cwd, at.dir, added));
4499
4763
  if (
4500
4764
  askedId === COLORS_PAGE.id &&
@@ -4546,18 +4810,21 @@ export async function themeEditPreviewApp(dir, options = {}) {
4546
4810
  refuse(
4547
4811
  E.ERR_INVALID_ARGUMENT,
4548
4812
  'Name the folder for the new app: a new or empty folder inside the current one.',
4549
- {run: [`${PREVIEW} app theme-app`]},
4813
+ {run: [appCommand(freeAppFolder(cwd))]},
4550
4814
  );
4551
4815
  options = {...options, theme: themeArg(options.theme)};
4552
4816
  const slug = options.theme ?? null;
4817
+ // A theme the app wears is one of an app's own: from a folder that is no
4818
+ // app (a workspace root), the one app finder's answer (the `cd` to the
4819
+ // app) comes first, never a "no such theme".
4820
+ if (slug != null) requireProject(cwd);
4553
4821
  const theme =
4554
4822
  slug == null
4555
4823
  ? null
4556
4824
  : wornTheme(
4557
4825
  cwd,
4558
4826
  slug,
4559
- t =>
4560
- `${PREVIEW} app ${quoteCommandArgument(dir)}${t == null ? '' : ` --theme ${t}`}`,
4827
+ t => appCommand(dir, t),
4561
4828
  'leave out --theme and the app wears the neutral theme',
4562
4829
  );
4563
4830
  // A new app has no Core installed yet: its pages come from this CLI's own
@@ -4592,9 +4859,10 @@ export async function themeEditPreviewApp(dir, options = {}) {
4592
4859
  {run: [`${P} show ${slug}`]},
4593
4860
  );
4594
4861
  } else if (why) {
4595
- await buildTheme(ctx, slug, theme);
4862
+ const built = await buildTheme(ctx, slug, theme);
4596
4863
  notes.push(
4597
4864
  `built ${shown(cwd, from.dir)}/ first: its build was not current (${why}), and the app gets a current copy`,
4865
+ ...built.notes,
4598
4866
  );
4599
4867
  }
4600
4868
  const to = themeFiles('', slug);
@@ -4608,10 +4876,46 @@ export async function themeEditPreviewApp(dir, options = {}) {
4608
4876
  from.sheet,
4609
4877
  from.previewPng,
4610
4878
  from.sheetPng,
4879
+ // The record of pictures, none of which come along.
4880
+ from.pictures,
4611
4881
  ].map(f => path.basename(f)),
4612
4882
  );
4613
4883
  // The whole folder, tokens/ included, as bytes: a font or a picture
4614
4884
  // there must arrive as it is.
4885
+ const recorded = readWrittenRecord(cwd, slug);
4886
+ /** Links in the theme folder: never read through, so left out, and named. @type {string[]} */
4887
+ const links = [];
4888
+ /**
4889
+ * A file of the theme folder, read for the copy before anything is
4890
+ * written: one too large for a read, or one that cannot be read, is
4891
+ * refused by name (a read, never called a write).
4892
+ * @param {string} file
4893
+ */
4894
+ const readForCopy = file => {
4895
+ const {size} = fs.statSync(file);
4896
+ if (size > NODE_READ_MAX)
4897
+ refuse(
4898
+ E.ERR_INVALID_ARGUMENT,
4899
+ `${shown(cwd, file)} is ${(size / 1073741824).toFixed(1)} GB, more than one file read can take, so ${slug} cannot be copied into a new app.`,
4900
+ {
4901
+ fix: `move it out of ${shown(cwd, from.dir)}/ (a theme's build does not need it), then run the command again`,
4902
+ run: [appCommand(dir, slug)],
4903
+ },
4904
+ );
4905
+ try {
4906
+ return fs.readFileSync(file);
4907
+ } catch (e) {
4908
+ const code = /** @type {any} */ (e)?.code;
4909
+ refuse(
4910
+ E.ERR_READ_FAILED,
4911
+ `${shown(cwd, file)} could not be read (${code ?? String(e)}), so ${slug} cannot be copied into a new app.`,
4912
+ {
4913
+ fix: `make it readable (chmod u+r ${quoteCommandArgument(shown(cwd, file))}) or move it out of ${shown(cwd, from.dir)}/, then run the command again`,
4914
+ run: [appCommand(dir, slug)],
4915
+ },
4916
+ );
4917
+ }
4918
+ };
4615
4919
  /** @param {string} rel */
4616
4920
  const copyDir = rel => {
4617
4921
  for (const entry of fs.readdirSync(path.join(from.dir, rel), {
@@ -4619,19 +4923,83 @@ export async function themeEditPreviewApp(dir, options = {}) {
4619
4923
  })) {
4620
4924
  const sub = path.join(rel, entry.name);
4621
4925
  if (entry.isDirectory()) copyDir(sub);
4926
+ else if (
4927
+ entry.isSymbolicLink() &&
4928
+ !(rel === '' && skip.has(entry.name)) &&
4929
+ !(rel === '' && isEditorPage(entry.name, recorded))
4930
+ )
4931
+ links.push(shown(cwd, path.join(from.dir, sub)));
4622
4932
  else if (
4623
4933
  entry.isFile() &&
4624
4934
  !(rel === '' && skip.has(entry.name)) &&
4935
+ // No page or picture the editor wrote (dark pictures, section
4936
+ // sheets): the new app builds its own. A file of the user's named
4937
+ // like one (sheet-old.png) comes along.
4938
+ !(rel === '' && isEditorPage(entry.name, recorded)) &&
4625
4939
  // A temp file a stopped command left is no part of the theme.
4626
4940
  !isEditorTemp(entry.name)
4627
4941
  )
4628
4942
  themeCopy.push({
4629
4943
  rel: path.join(to.dir, sub),
4630
- text: fs.readFileSync(path.join(from.dir, sub)),
4944
+ text: readForCopy(path.join(from.dir, sub)),
4631
4945
  });
4632
4946
  }
4633
4947
  };
4634
4948
  copyDir('');
4949
+ if (links.length)
4950
+ notes.push(
4951
+ `left out ${links.join(', ')}: ${links.length === 1 ? 'a link' : 'links'}, which the editor never reads through; put a copy of the file there to bring it along`,
4952
+ );
4953
+ // A source file of the theme that imports a file outside its folder
4954
+ // would not build in the new app, where that file is not: refused,
4955
+ // naming the import, before anything is written.
4956
+ const outside = themeCopy.flatMap(c => {
4957
+ const rel = path.relative(to.dir, c.rel);
4958
+ if (!/\.(mjs|cjs|js|mts|cts|ts|tsx|jsx)$/.test(rel)) return [];
4959
+ const file = path.join(from.dir, rel);
4960
+ return importSpecifiers(file, String(c.text))
4961
+ .filter(spec => spec.startsWith('.'))
4962
+ .filter(spec => {
4963
+ const at = path.resolve(path.dirname(file), spec);
4964
+ return at !== from.dir && !at.startsWith(from.dir + path.sep);
4965
+ })
4966
+ .map(spec => `${shown(cwd, file)} imports '${spec}'`);
4967
+ });
4968
+ // A stylesheet's url() that leads out of the theme folder (an image in
4969
+ // the project's own folders) is resolved by the app's bundler as a
4970
+ // module: the new app does not have it, so its build would fail. Read
4971
+ // with the renderer's own url reader; a `/` url is the app's public/
4972
+ // folder, which the bundler leaves alone.
4973
+ for (const c of themeCopy) {
4974
+ const rel = path.relative(to.dir, c.rel);
4975
+ if (!/\.css$/.test(rel)) continue;
4976
+ const file = path.join(from.dir, rel);
4977
+ for (const m of String(c.text).matchAll(
4978
+ new RegExp(CSS_URL.source, 'g'),
4979
+ )) {
4980
+ const named = assetRef(cssUrlRef(m), {
4981
+ dir: path.dirname(file),
4982
+ root: cwd,
4983
+ });
4984
+ if (!named || named.kind === 'remote' || named.ref.startsWith('/'))
4985
+ continue;
4986
+ const at =
4987
+ named.kind === 'missing'
4988
+ ? path.resolve(path.dirname(file), named.ref)
4989
+ : named.file;
4990
+ if (at !== from.dir && !at.startsWith(from.dir + path.sep))
4991
+ outside.push(`${shown(cwd, file)} uses url(${named.ref})`);
4992
+ }
4993
+ }
4994
+ if (outside.length)
4995
+ refuse(
4996
+ E.ERR_INVALID_ARGUMENT,
4997
+ `${slug} cannot be copied into a new app: ${outside.slice(0, 3).join('; ')}, a file outside ${shown(cwd, from.dir)}/, which the new app does not have, so its theme would not build there.`,
4998
+ {
4999
+ fix: `move what it imports into ${shown(cwd, from.dir)}/ (and import it from there), then run the command again`,
5000
+ run: [appCommand(dir, slug)],
5001
+ },
5002
+ );
4635
5003
  if (theme.like && theme.like !== 'neutral')
4636
5004
  dependencies[`@astryxdesign/theme-${theme.like}`] = cliVersion();
4637
5005
  // The copied build was made on this project's Core and base theme: the
@@ -4662,17 +5030,43 @@ export async function themeEditPreviewApp(dir, options = {}) {
4662
5030
  };
4663
5031
  // The new app installs its own packages, so every open font the theme
4664
5032
  // names is added, at the version this project has, else a known one.
4665
- const fonts = fontPackages(ctx, theme);
5033
+ const fonts = fontPackages(ctx, theme, {forNewApp: true});
4666
5034
  for (const font of fonts)
4667
5035
  dependencies[font.pkg] =
4668
5036
  readVersion(project, font.pkg) ?? OPEN_FONT_RANGE;
5037
+ // A package the new app adds and this project has not installed: which
5038
+ // weights it ships is unknown here (Lato has no 500), and importing one
5039
+ // it lacks would stop the app's build. Its index sheet (weight 400)
5040
+ // loads; every other weight the theme uses is named, with the import
5041
+ // that loads it once installed.
5042
+ const used = (builtFontWeights(ctx, slug) ?? [400]).filter(w => w !== 400);
5043
+ for (const font of fonts) {
5044
+ const sheets = fontPackageSheets(ctx, slug, font.pkg);
5045
+ if (
5046
+ used.length &&
5047
+ sheets.length === 1 &&
5048
+ sheets[0] === `${font.pkg}/index.css`
5049
+ )
5050
+ notes.push(
5051
+ `the new app loads ${font.family} at weight 400 only (${font.pkg}/index.css): ${slug} also uses ${used.join(', ')}, which show as a bold drawn by the browser until loaded; after installing, import ${used.map(w => `'${font.pkg}/${w}.css'`).join(', ')} in its root layout (each weight the family ships)`,
5052
+ );
5053
+ }
5054
+ // A family the CLI cannot vouch for as an open font (and this project
5055
+ // has no package of) is not installed in the new app: said, with the
5056
+ // package that would load it.
5057
+ for (const family of familiesNothingLoads(ctx, theme, fonts)) {
5058
+ const s = fontsourceSuggestion(family);
5059
+ notes.push(
5060
+ `"${family}" is not a font the CLI knows to be open, and this project has no package of it, so the new app does not install it and shows the next font in the stack${s ? `; if Fontsource publishes it, ${installLine(cwd, [s.pkg])} in the new app installs it (then import '${s.pkg}' in its root layout)` : ''}`,
5061
+ );
5062
+ }
4669
5063
  routeTheme = {
4670
5064
  name: slug,
4671
5065
  module: fromRoute(to.js),
4672
5066
  css: [
4673
5067
  fromRoute(to.css),
4674
5068
  ...baseFontsCss(ctx, theme),
4675
- ...fonts.map(x => `${x.pkg}/index.css`),
5069
+ ...fonts.flatMap(x => fontPackageSheets(ctx, slug, x.pkg)),
4676
5070
  ],
4677
5071
  mode: themeImports(ctx, slug, theme, path.join(cwd, routeDir)).mode,
4678
5072
  };
@@ -4738,12 +5132,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4738
5132
  dependencies,
4739
5133
  slug,
4740
5134
  );
4741
- const files = writeStarterApp(
4742
- cwd,
4743
- plan,
4744
- d =>
4745
- `${PREVIEW} app ${quoteCommandArgument(d)}${slug == null ? '' : ` --theme ${quoteCommandArgument(slug)}`}`,
4746
- );
5135
+ const files = writeStarterApp(cwd, plan, d => appCommand(d, slug));
4747
5136
  const folder = shownDir(cwd, plan.root);
4748
5137
  if (
4749
5138
  plan.root !== cwd &&
@@ -4765,7 +5154,7 @@ export async function themeEditPreviewApp(dir, options = {}) {
4765
5154
  files,
4766
5155
  notes,
4767
5156
  // A folder named like a flag (`-`, `-k`) is a path to cd only with ./.
4768
- open: `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)} && npm install && npm run dev, then open /theme-preview`,
5157
+ open: `${cdTo(folder)} && npm install && npm run dev, then open /theme-preview`,
4769
5158
  },
4770
5159
  };
4771
5160
  }
@@ -4854,7 +5243,9 @@ export async function themeEditPreviewList(options = {}) {
4854
5243
  /** @type {string[]} */
4855
5244
  const notes = [];
4856
5245
  const themeMissing = Boolean(
4857
- data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
5246
+ data?.theme &&
5247
+ !fs.existsSync(themeFiles(cwd, data.theme).dir) &&
5248
+ !(at && themeElsewhere(cwd, at.dir, data.theme)),
4858
5249
  );
4859
5250
  if (at && fs.existsSync(path.join(at.dir, PENDING)))
4860
5251
  notes.push(
@@ -4943,7 +5334,116 @@ export async function themeEditPreviewList(options = {}) {
4943
5334
  * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditPreviewRemoveResponse>}
4944
5335
  */
4945
5336
  export async function themeEditPreviewRemove(page, options = {}) {
4946
- return reportingRecovery(box => removePreview(page, options, box));
5337
+ try {
5338
+ return await reportingRecovery(box => removePreview(page, options, box));
5339
+ } catch (e) {
5340
+ // Removing a page needs the theme the route wears; removing the whole
5341
+ // preview needs none. Every refusal over a theme that does not load
5342
+ // names it, wherever the theme was read.
5343
+ const err = /** @type {any} */ (e);
5344
+ const pf =
5345
+ options.path != null
5346
+ ? ` --path ${quoteCommandArgument(options.path)}`
5347
+ : '';
5348
+ const whole = `${PREVIEW} remove${pf}`;
5349
+ if (
5350
+ page != null &&
5351
+ [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5352
+ err?.code,
5353
+ ) &&
5354
+ !(err.suggestions ?? []).some((/** @type {any} */ x) => x?.name === whole)
5355
+ )
5356
+ err.suggestions = [
5357
+ {
5358
+ name: whole,
5359
+ reason:
5360
+ 'do this instead: removes the whole preview, which needs no theme',
5361
+ },
5362
+ ...(err.suggestions ?? []),
5363
+ ];
5364
+ throw e;
5365
+ }
5366
+ }
5367
+
5368
+ /**
5369
+ * Refuse a preview command run in a project folder below the one that holds
5370
+ * the theme the preview wears (a workspace app run from its own folder): the
5371
+ * theme is not gone, and no command rewrites it away. The refusal names
5372
+ * the same command, run from the folder that holds the theme.
5373
+ * @param {string} cwd
5374
+ * @param {string} dir the preview folder
5375
+ * @param {string} slug the theme the preview wears
5376
+ * @param {Retry} again the same command, with every argument it was given,
5377
+ * for a --path
5378
+ */
5379
+ function refuseThemeAway(cwd, dir, slug, again) {
5380
+ const away = themeElsewhere(cwd, dir, slug);
5381
+ if (!away) return;
5382
+ const root = path.dirname(path.dirname(away));
5383
+ refuse(
5384
+ E.ERR_INVALID_ARGUMENT,
5385
+ `The preview wears ${slug}, whose theme folder is ${away}/, outside this project folder (${cwd}). Run the command from the folder that holds themes/${slug}/.`,
5386
+ {
5387
+ run: [`${cdTo(root)} && ${again(path.relative(root, dir))}`],
5388
+ },
5389
+ );
5390
+ }
5391
+
5392
+ /**
5393
+ * The theme folder a preview's route imports when it is outside this
5394
+ * project's themes/ (a workspace app run from its own folder, its themes at
5395
+ * the workspace root), or null.
5396
+ * @param {string} cwd
5397
+ * @param {string} dir the preview folder
5398
+ * @param {string} slug
5399
+ * @returns {string | null}
5400
+ */
5401
+ function themeElsewhere(cwd, dir, slug) {
5402
+ if (fs.existsSync(themeFiles(cwd, slug).dir)) return null;
5403
+ /** @type {string} */
5404
+ let route;
5405
+ try {
5406
+ route = readRegularFile(path.join(dir, 'page.tsx'), 'utf8');
5407
+ } catch {
5408
+ return null;
5409
+ }
5410
+ const esc = slug.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5411
+ const m = new RegExp(`['"]([^'"]*themes/${esc})/${esc}[^'"]*['"]`).exec(
5412
+ route,
5413
+ );
5414
+ if (!m || !m[1].startsWith('.')) return null;
5415
+ const found = path.resolve(dir, m[1]);
5416
+ return fs.existsSync(path.join(found, `${slug}.settings.json`))
5417
+ ? found
5418
+ : null;
5419
+ }
5420
+
5421
+ /**
5422
+ * The previews a theme may have: the ones recorded with it (added with
5423
+ * --path) and every preview in the routes folders (one renamed by hand, or
5424
+ * one whose record was lost). The one list `see`, a change's refresh and
5425
+ * the preview commands read; each reads a preview's record for its theme.
5426
+ * @param {string} cwd
5427
+ * @param {string} slug
5428
+ * @returns {string[]}
5429
+ */
5430
+ function themePreviews(cwd, slug) {
5431
+ return [...new Set([...recordedPreviews(cwd, slug), ...previewsIn(cwd)])];
5432
+ }
5433
+
5434
+ /**
5435
+ * Every preview in the app, of any editor theme: the previews of each, by
5436
+ * {@link themePreviews}, that are there.
5437
+ * @param {string} cwd
5438
+ * @returns {string[]}
5439
+ */
5440
+ function allPreviews(cwd) {
5441
+ return [
5442
+ ...new Set([
5443
+ ...editedThemes(cwd).flatMap(t => themePreviews(cwd, t)),
5444
+ ...previewsIn(cwd),
5445
+ ]),
5446
+ ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
4947
5447
  }
4948
5448
 
4949
5449
  /**
@@ -4994,12 +5494,30 @@ async function removePreview(page, options, box) {
4994
5494
  const retry = (/** @type {string | null} */ p) =>
4995
5495
  `${PREVIEW} remove${page != null ? ` ${quoteCommandArgument(page)}` : ''}${p == null ? '' : ` --path ${quoteCommandArgument(p)}`}`;
4996
5496
  const at = previewDir(cwd, options.path, {retry});
5497
+ // A file given for the preview's folder: its folder when the file is a
5498
+ // preview's own, else the previews there are (as add refuses a file).
5499
+ if (fs.existsSync(at.dir) && !fs.statSync(at.dir).isDirectory()) {
5500
+ const parent = path.dirname(at.dir);
5501
+ const own = fs.existsSync(path.join(parent, PREVIEW_DATA));
5502
+ const others = previewsIn(cwd);
5503
+ refuse(
5504
+ E.ERR_INVALID_ARGUMENT,
5505
+ `${shown(cwd, at.dir)} is a file; a preview is a folder${own ? `, and this file is in the preview ${shownDir(cwd, parent)}/` : ''}.`,
5506
+ {
5507
+ run: own
5508
+ ? [retry(shownDir(cwd, parent))]
5509
+ : others.length
5510
+ ? others.slice(0, 3).map(d => retry(shownDir(cwd, d)))
5511
+ : [`${PREVIEW} list`],
5512
+ },
5513
+ );
5514
+ }
4997
5515
  // The pages a stopped change was removing, read before it is finished.
4998
5516
  /** @type {string[]} */
4999
5517
  let removing = [];
5000
5518
  try {
5001
5519
  const pend = JSON.parse(
5002
- fs.readFileSync(path.join(at.dir, PENDING), 'utf8'),
5520
+ readRegularFile(path.join(at.dir, PENDING), 'utf8'),
5003
5521
  );
5004
5522
  const ids = (/** @type {any} */ r) =>
5005
5523
  Array.isArray(r?.pages)
@@ -5130,11 +5648,17 @@ async function removePreview(page, options, box) {
5130
5648
  .map(f => path.join(at.dir, f.replace(/\.[a-z]+$/, '')))
5131
5649
  : []),
5132
5650
  ];
5133
- const {importers, tooBig} = pageImporters(cwd, data, at.dir, targets);
5651
+ const {importers, tooBig, limit} = pageImporters(
5652
+ cwd,
5653
+ data,
5654
+ at.dir,
5655
+ targets,
5656
+ {aliases: tsconfigAliases(cwd), limit: IMPORTER_SCAN_MAX},
5657
+ );
5134
5658
  if (tooBig)
5135
5659
  refuse(
5136
5660
  E.ERR_INVALID_ARGUMENT,
5137
- `This project holds more than ${IMPORTER_SCAN_MAX} source files, too many to check that none of them imports ${going.length > 1 ? 'the preview pages' : 'the page'}, so nothing was removed.`,
5661
+ `This project holds more than ${limit} source files, too many to check that none of them imports ${going.length > 1 ? 'the preview pages' : 'the page'}, so nothing was removed.`,
5138
5662
  {
5139
5663
  fix: `delete ${folder}/ by hand once nothing imports from it`,
5140
5664
  },
@@ -5179,6 +5703,7 @@ async function removePreview(page, options, box) {
5179
5703
  const wore = data.theme;
5180
5704
  /** @type {string | null} */
5181
5705
  let gone = null;
5706
+ if (wore) refuseThemeAway(cwd, at.dir, wore, retry);
5182
5707
  if (wore && !fs.existsSync(themeFiles(cwd, wore).dir)) {
5183
5708
  gone = wore;
5184
5709
  data.theme = null;
@@ -5214,26 +5739,10 @@ async function removePreview(page, options, box) {
5214
5739
  let planned;
5215
5740
  /** @type {Awaited<ReturnType<typeof routeTheme>>} */
5216
5741
  let theme;
5217
- try {
5218
- theme = await routeTheme(cwd, at.dir, data, {build: false});
5219
- planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5220
- } catch (e) {
5221
- const err = /** @type {any} */ (e);
5222
- if (
5223
- [E.ERR_THEME_INVALID, E.ERR_UNKNOWN_THEME, E.ERR_THEME_LOAD].includes(
5224
- err?.code,
5225
- )
5226
- )
5227
- err.suggestions = [
5228
- {
5229
- name: `${PREVIEW} remove${pf}`,
5230
- reason:
5231
- 'do this instead: removes the whole preview, which needs no theme',
5232
- },
5233
- ...(err.suggestions ?? []),
5234
- ];
5235
- throw e;
5236
- }
5742
+ // A theme that does not load is refused with the whole-preview remove
5743
+ // named (themeEditPreviewRemove adds it to every such refusal).
5744
+ theme = await routeTheme(cwd, at.dir, data, {build: false});
5745
+ planned = await routeWrites(cwd, at.dir, data, theme, {gone});
5237
5746
  const elsewhere = `${PREVIEW} remove${pf}`;
5238
5747
  /** @type {Map<string, {rel: string, text: string, keepHash?: boolean}>} */
5239
5748
  const writes = new Map(move.writes.map(w => [w.rel, w]));
@@ -5331,7 +5840,7 @@ async function removePreview(page, options, box) {
5331
5840
  );
5332
5841
  continue;
5333
5842
  }
5334
- plan.push({file, before: fs.readFileSync(file)});
5843
+ plan.push({file, before: readRegularFile(file)});
5335
5844
  }
5336
5845
  // theme-preview.json goes last, so an interrupted remove can run again.
5337
5846
  plan.sort(