@astryxdesign/cli 0.7.14 → 0.7.15-canary.g06b7e61

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 (203) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/README.md +63 -63
  3. package/api/build/_adapter.d.mts +4 -0
  4. package/api/build/_adapter.mjs +28 -2
  5. package/api/build/blocks/blocks.d.mts +10 -1
  6. package/api/build/blocks/blocks.mjs +84 -7
  7. package/api/build/build.mjs +6 -1
  8. package/api/build/tree.d.mts +4 -0
  9. package/api/build/tree.mjs +9 -2
  10. package/api/doctor/_adapter.d.mts +3 -1
  11. package/api/doctor/_adapter.mjs +14 -1
  12. package/api/doctor/_authoring-audit.d.mts +42 -0
  13. package/api/doctor/_authoring-audit.mjs +106 -0
  14. package/api/doctor/doctor.d.mts +7 -0
  15. package/api/doctor/doctor.mjs +24 -39
  16. package/api/doctor/theme-checks.mjs +56 -21
  17. package/api/integration/add-helpers.mjs +5 -0
  18. package/api/integration/add-theme.mjs +15 -110
  19. package/api/integration/validate-integration.mjs +17 -3
  20. package/api/integration/validateIntegration.doc.mjs +1 -1
  21. package/api/search/_adapter.mjs +124 -3
  22. package/api/search/_candidate-score.mjs +63 -9
  23. package/api/search/_entries.d.mts +10 -0
  24. package/api/search/_entries.mjs +68 -1
  25. package/api/search/_gather-templates.d.mts +11 -0
  26. package/api/search/_gather-templates.mjs +22 -2
  27. package/api/search/_words.mjs +26 -6
  28. package/api/swizzle/copy/copy.mjs +1 -1
  29. package/api/theme/_adapter.d.mts +37 -5
  30. package/api/theme/_adapter.mjs +381 -57
  31. package/api/theme/_fork.d.mts +90 -0
  32. package/api/theme/_fork.mjs +246 -0
  33. package/api/theme/build/build.d.mts +40 -2
  34. package/api/theme/build/build.mjs +477 -66
  35. package/api/theme/eject/eject.mjs +36 -15
  36. package/api/theme/list/list.mjs +3 -6
  37. package/api/theme/palette/generate/generator.d.mts +13 -0
  38. package/api/theme/palette/generate/generator.mjs +32 -2
  39. package/api/theme/targets/targets.d.mts +8 -0
  40. package/api/theme/targets/targets.mjs +24 -4
  41. package/api/theme/template/template.mjs +48 -2
  42. package/api/theme/theme.type.d.mts +8 -0
  43. package/api/theme/theme.type.mjs +5 -1
  44. package/api/theme/themeBuild.doc.mjs +7 -4
  45. package/api/theme/themeEject.doc.mjs +3 -3
  46. package/api/theme/themeRemove.doc.mjs +5 -2
  47. package/api/theme/themeTargets.doc.mjs +1 -1
  48. package/api/theme/themeTemplate.doc.mjs +2 -2
  49. package/api/theme/themeUse.doc.mjs +8 -2
  50. package/api/theme-edit/_adapter.d.mts +46 -3
  51. package/api/theme-edit/_adapter.mjs +496 -112
  52. package/api/theme-edit/_catalog.d.mts +1 -6
  53. package/api/theme-edit/_catalog.mjs +5 -268
  54. package/api/theme-edit/_check.d.mts +9 -4
  55. package/api/theme-edit/_check.mjs +1232 -229
  56. package/api/theme-edit/_color.d.mts +19 -0
  57. package/api/theme-edit/_color.mjs +280 -34
  58. package/api/theme-edit/_compiler.d.mts +3 -1
  59. package/api/theme-edit/_compiler.mjs +52 -13
  60. package/api/theme-edit/_context.d.mts +4 -1
  61. package/api/theme-edit/_context.mjs +126 -13
  62. package/api/theme-edit/_css.d.mts +84 -0
  63. package/api/theme-edit/_css.mjs +700 -0
  64. package/api/theme-edit/_edit.d.mts +9 -3
  65. package/api/theme-edit/_edit.mjs +806 -103
  66. package/api/theme-edit/_how-commands.d.mts +38 -7
  67. package/api/theme-edit/_how-commands.mjs +64 -45
  68. package/api/theme-edit/_how-question.d.mts +33 -0
  69. package/api/theme-edit/_how-question.mjs +2553 -381
  70. package/api/theme-edit/_how.mjs +402 -31
  71. package/api/theme-edit/_overview.mjs +2 -7
  72. package/api/theme-edit/_palette.d.mts +60 -13
  73. package/api/theme-edit/_palette.mjs +826 -295
  74. package/api/theme-edit/_parts.d.mts +42 -10
  75. package/api/theme-edit/_parts.mjs +280 -69
  76. package/api/theme-edit/_png.d.mts +4 -4
  77. package/api/theme-edit/_png.mjs +4 -2
  78. package/api/theme-edit/_preview-app.d.mts +14 -0
  79. package/api/theme-edit/_preview-app.mjs +1675 -235
  80. package/api/theme-edit/_preview.d.mts +7 -16
  81. package/api/theme-edit/_preview.mjs +79 -86
  82. package/api/theme-edit/_project.d.mts +32 -2
  83. package/api/theme-edit/_project.mjs +80 -19
  84. package/api/theme-edit/_settings.d.mts +199 -52
  85. package/api/theme-edit/_settings.mjs +1422 -217
  86. package/api/theme-edit/_tables.d.mts +19 -6
  87. package/api/theme-edit/_tables.mjs +150 -92
  88. package/api/theme-edit/theme-edit.type.d.mts +20 -1
  89. package/api/theme-edit/theme-edit.type.mjs +6 -3
  90. package/api/theme-edit/themeEditHow.doc.mjs +6 -0
  91. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  92. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  93. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  94. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  95. package/api/theme-edit/themeEditPreviewRemove.doc.mjs +5 -1
  96. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  97. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  98. package/api/upgrade/_adapter.d.mts +1 -0
  99. package/assets/codemods/run-codemod.mjs +61 -0
  100. package/assets/codemods/runner.mjs +5 -4
  101. package/assets/codemods/transforms/v0.0.14/rename-status-variants.mjs +3 -0
  102. package/assets/codemods/transforms/v0.1.8/rename-avatar-size-scale.mjs +5 -1
  103. package/assets/codemods/transforms/v0.6.4/migrate-native-picker-to-presentation.mjs +3 -0
  104. package/assets/codemods/transforms/v0.7.0/migrate-deprecated-theme-surface.mjs +4 -0
  105. package/assets/codemods/transforms/v0.7.0/rename-empty-search-results-text.mjs +17 -12
  106. package/assets/codemods/transforms/v0.7.2/migrate-list-edge-compensation-to-edge.mjs +3 -0
  107. package/assets/codemods/transforms/v0.7.5/migrate-codeblock-tokenizer-to-language.mjs +3 -0
  108. package/assets/codemods/transforms/v0.7.8/promote-tokenizer-presentation.mjs +3 -0
  109. package/assets/docs/tree/calendars.doc.mjs +1 -3
  110. package/assets/docs/tree/checks.doc.mjs +22 -1
  111. package/assets/docs/tree/publishing.doc.mjs +1 -0
  112. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  113. package/assets/docs.generated.json +2 -1
  114. package/assets/preview-app/next.config.mjs +7 -1
  115. package/assets/self-audit.generated.json +1 -0
  116. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.doc.mjs +14 -0
  117. package/assets/templates/blocks/components/Theme/useThemeNameHookUsage.tsx +31 -0
  118. package/assets/templates/components.generated.json +1 -1
  119. package/authoring/integration/integration.doc.mjs +8 -0
  120. package/authoring/integration/schema.d.mts +8 -0
  121. package/authoring/integration/schema.mjs +1 -0
  122. package/authoring/integration/type.ts +9 -0
  123. package/clients/cli/bin/astryx.mjs +19 -15
  124. package/clients/cli/build-id.generated.json +1 -0
  125. package/clients/cli/commands/ensure-core-built.mjs +12 -5
  126. package/clients/cli/commands/experimental/index.mjs +10 -10
  127. package/clients/cli/commands/experimental/theme.mjs +200 -81
  128. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  129. package/clients/cli/commands/experimental-theme-editor-how.doc.mjs +1 -1
  130. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  131. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +1 -2
  132. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  133. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  134. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  135. package/clients/cli/commands/experimental-theme-eject.doc.mjs +3 -3
  136. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  137. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  138. package/clients/cli/commands/experimental-theme-preview-list.doc.mjs +1 -1
  139. package/clients/cli/commands/experimental-theme-preview-remove.doc.mjs +1 -1
  140. package/clients/cli/commands/experimental-theme-remove.doc.mjs +1 -1
  141. package/clients/cli/commands/experimental-theme-template.doc.mjs +4 -3
  142. package/clients/cli/commands/integration.mjs +8 -0
  143. package/clients/cli/commands/manifest.mjs +5 -2
  144. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  145. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  146. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  147. package/clients/cli/commands/theme.mjs +439 -66
  148. package/clients/cli/index.mjs +27 -6
  149. package/clients/cli/lib/cli-error.mjs +118 -3
  150. package/clients/cli/lib/manifest.mjs +37 -0
  151. package/clients/cli/lib/resolve-theme.mjs +2 -1
  152. package/clients/cli/manifest.generated.json +1 -0
  153. package/foundation/config/project.mjs +34 -8
  154. package/foundation/config/theme-state.d.mts +16 -0
  155. package/foundation/config/theme-state.mjs +84 -13
  156. package/foundation/discovery/module-exports.mjs +16 -2
  157. package/foundation/discovery/stored-self-audit.d.mts +31 -0
  158. package/foundation/discovery/stored-self-audit.mjs +119 -0
  159. package/foundation/discovery/template-adapter.d.mts +48 -2
  160. package/foundation/discovery/template-adapter.mjs +51 -19
  161. package/foundation/discovery/template-needs.d.mts +19 -0
  162. package/foundation/discovery/template-needs.mjs +50 -16
  163. package/foundation/discovery/template-source-tree.d.mts +7 -0
  164. package/foundation/discovery/template-source-tree.mjs +15 -0
  165. package/foundation/discovery/theme-discovery.d.mts +2 -1
  166. package/foundation/discovery/theme-discovery.mjs +16 -10
  167. package/foundation/discovery/theme-imports.d.mts +16 -0
  168. package/foundation/discovery/theme-imports.mjs +30 -2
  169. package/foundation/discovery/theme-module-extensions.d.mts +18 -0
  170. package/foundation/discovery/theme-module-extensions.mjs +30 -0
  171. package/foundation/doc-compiler/import.mjs +22 -15
  172. package/foundation/doc-compiler/stored-docs.d.mts +18 -12
  173. package/foundation/doc-compiler/stored-docs.mjs +52 -19
  174. package/foundation/env/private-dir.d.mts +17 -0
  175. package/foundation/env/private-dir.mjs +42 -0
  176. package/foundation/fs/gather-cache.d.mts +108 -0
  177. package/foundation/fs/gather-cache.mjs +783 -0
  178. package/foundation/fs/jiti-cache.d.mts +21 -0
  179. package/foundation/fs/jiti-cache.mjs +66 -0
  180. package/foundation/fs/module-loader.mjs +14 -3
  181. package/foundation/fs/read-record.d.mts +31 -1
  182. package/foundation/fs/read-record.mjs +100 -7
  183. package/foundation/integrations/autolink.d.mts +1 -24
  184. package/foundation/integrations/autolink.mjs +7 -60
  185. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  186. package/foundation/integrations/declared-dependencies.mjs +73 -0
  187. package/foundation/integrations/integrations.d.mts +8 -0
  188. package/foundation/integrations/integrations.mjs +4 -0
  189. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  190. package/foundation/integrations/may-have-integrations.mjs +47 -0
  191. package/foundation/integrations/validate-contributions.d.mts +62 -1
  192. package/foundation/integrations/validate-contributions.mjs +476 -40
  193. package/foundation/release/cache.d.mts +32 -4
  194. package/foundation/release/cache.mjs +105 -16
  195. package/foundation/release/folder-lock.d.mts +28 -0
  196. package/foundation/release/folder-lock.mjs +205 -0
  197. package/foundation/release/lock-lease.d.mts +2 -1
  198. package/foundation/release/lock-lease.mjs +7 -2
  199. package/foundation/response/error-codes.doc.mjs +1 -1
  200. package/foundation/response/response-types.doc.mjs +5 -5
  201. package/package.json +8 -6
  202. package/api/theme-edit/_css-properties.d.mts +0 -10
  203. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -33,40 +33,62 @@
33
33
 
34
34
  import {createHash} from 'node:crypto';
35
35
  import * as fs from 'node:fs';
36
- import * as os from 'node:os';
37
36
  import * as path from 'node:path';
38
37
  import * as edit from './_edit.mjs';
38
+ import {themeCacheRoot} from './_project.mjs';
39
39
  import * as preview from './_preview-app.mjs';
40
40
  import {AstryxError} from '../error.mjs';
41
41
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
42
42
  import {
43
43
  findAstryxProject,
44
44
  findPackageRoot,
45
- findProjectCoreDir,
46
45
  } from '../../foundation/fs/paths.mjs';
47
46
  import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
48
- import {tryLock} from '../../foundation/release/cache.mjs';
49
- import {q} from './_settings.mjs';
47
+ import {withFolderLock} from '../../foundation/release/folder-lock.mjs';
48
+ import {
49
+ getCliInvocation,
50
+ quoteCommandArgument,
51
+ } from '../../foundation/env/package-manager.mjs';
52
+ import {LIKE, P} from './_tables.mjs';
53
+ import {camel} from './_settings.mjs';
54
+ import {LOCAL_THEME_ROOT} from '../../foundation/config/theme-state.mjs';
50
55
 
51
- export {themeEditHow, parsePoints} from './_how.mjs';
52
- import {isPicture as howPicture} from './_how.mjs';
56
+ export {parsePoints} from './_how.mjs';
57
+ import {themeEditHow as howAt} from './_how.mjs';
53
58
 
54
59
  /**
55
- * Whether `how`'s first word names a picture, as the API decides it, for
56
- * the command line's own argument checks. The file system is read here.
57
- * @param {string} word
58
- * @param {string} [cwd]
60
+ * `how`, run at the project root like the other editor commands, so a
61
+ * subfolder finds the app's themes. A picture named from the subfolder
62
+ * keeps pointing where it was named.
63
+ * @param {string} subject
64
+ * @param {import('./theme-edit.type.mjs').ThemeEditHowOptions} [options]
65
+ * @returns {Promise<import('./theme-edit.type.mjs').ThemeEditHowResponse>}
59
66
  */
60
- export const isHowPicture = (word, cwd = process.cwd()) =>
61
- howPicture(word, cwd);
67
+ export async function themeEditHow(subject, options = {}) {
68
+ const from = options.cwd ?? process.cwd();
69
+ const o = atRoot(options);
70
+ /** A file named from the subfolder, as a path from anywhere. @param {unknown} name */
71
+ const here = name =>
72
+ typeof name === 'string' &&
73
+ name !== '' &&
74
+ !path.isAbsolute(name) &&
75
+ path.resolve(from) !== o.cwd &&
76
+ fs.existsSync(path.resolve(from, name)) &&
77
+ fs.statSync(path.resolve(from, name)).isFile()
78
+ ? path.resolve(from, name)
79
+ : name;
80
+ // The CLI passes the words as typed: the first may be that picture too.
81
+ const words = o.words?.length
82
+ ? [String(here(o.words[0])), ...o.words.slice(1)]
83
+ : o.words;
84
+ return howAt(/** @type {string} */ (here(subject)), {
85
+ ...o,
86
+ ...(words ? {words} : {}),
87
+ });
88
+ }
62
89
 
63
- /**
64
- * Whether a file named on the command line exists, read here.
65
- * @param {string} file
66
- * @param {string} [cwd]
67
- */
68
- export const fileExists = (file, cwd = process.cwd()) =>
69
- fs.existsSync(path.resolve(cwd, file));
90
+ /** The built-in themes a theme can build on (`--like`). */
91
+ export const builtInThemes = () => [...LIKE];
70
92
 
71
93
  /**
72
94
  * The project a command acts on: the Astryx project at or above `cwd`, found
@@ -93,7 +115,12 @@ export function projectRoot(cwd) {
93
115
  } catch {
94
116
  throw new AstryxError(
95
117
  `${path.relative(start, file) || 'package.json'} is not valid JSON, so the app it belongs to is unknown. Fix it, then run the command again. Nothing was written.`,
96
- [],
118
+ [
119
+ {
120
+ name: runLine(start, 'doctor'),
121
+ reason: 'names the file and what is wrong in it',
122
+ },
123
+ ],
97
124
  ERROR_CODES.ERR_PROJECT_REQUIRED,
98
125
  );
99
126
  }
@@ -109,7 +136,7 @@ export function projectRoot(cwd) {
109
136
  `${path.relative(start, file) || 'package.json'} is a package that does not use Astryx; the app that does is ${path.relative(start, project) || '.'}. Run the command from there, so the theme lands in that app. Nothing was written.`,
110
137
  [
111
138
  {
112
- name: `cd ${q(path.relative(start, project))}`,
139
+ name: `cd ${quoteCommandArgument(path.relative(start, project))}`,
113
140
  reason: 'do this first',
114
141
  },
115
142
  ],
@@ -119,12 +146,6 @@ export function projectRoot(cwd) {
119
146
  return project ?? start;
120
147
  }
121
148
 
122
- /** The locks this process holds now. */
123
- const HELD = new Set();
124
-
125
- /** @param {number} ms */
126
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
127
-
128
149
  /**
129
150
  * Where a project's locks are: the `.cache` of the node_modules holding
130
151
  * the Core the command reads (the project's own, or a workspace root's), shared by
@@ -139,10 +160,9 @@ function lockDir(root) {
139
160
  // The Core the command reads decides where; outside a project there is
140
161
  // none, and no lock.
141
162
  if (isOutsideProject(root)) return null;
142
- const core = findProjectCoreDir(root);
143
- if (!core) return null;
144
- const modules = path.dirname(path.dirname(core));
145
- const dir = path.join(modules, '.cache', 'astryx-theme', 'locks');
163
+ const cache = themeCacheRoot(root);
164
+ if (!cache) return null;
165
+ const dir = path.join(cache, 'locks');
146
166
  try {
147
167
  fs.mkdirSync(dir, {recursive: true});
148
168
  fs.accessSync(dir, fs.constants.W_OK);
@@ -150,7 +170,12 @@ function lockDir(root) {
150
170
  } catch (e) {
151
171
  throw new AstryxError(
152
172
  `Could not write ${path.relative(root, dir)} (${/** @type {any} */ (e).code ?? String(e)}), where the lock that keeps two commands on one theme apart is kept. Fix its permission, then run the command again. Nothing was changed.`,
153
- [],
173
+ [
174
+ {
175
+ name: `ls -ld ${quoteCommandArgument(dir)}`,
176
+ reason: 'see who owns the lock folder',
177
+ },
178
+ ],
154
179
  ERROR_CODES.ERR_WRITE_FAILED,
155
180
  );
156
181
  }
@@ -165,97 +190,100 @@ function lockDir(root) {
165
190
  * @template T
166
191
  * @param {string} root
167
192
  * @param {string} name
168
- * @param {() => Promise<T>} fn
193
+ * @param {(locked: boolean) => Promise<T>} fn called with whether the lock
194
+ * is held
195
+ * @param {boolean} [bestEffort] a command that can run read-only runs
196
+ * without the lock when it cannot be taken (a read-only node_modules),
197
+ * told so, and then writes nothing
169
198
  * @returns {Promise<T>}
170
199
  */
171
- async function withLock(root, name, fn) {
172
- const dir = lockDir(root);
173
- if (!dir) return fn();
174
- const key = createHash('sha256').update(root).digest('hex').slice(0, 16);
175
- const lock = path.join(dir, `${key}-${name}.lock`);
176
- const ownerFile = path.join(lock, 'owner.json');
177
- /** @returns {any} */
178
- const owner = () => {
179
- try {
180
- return JSON.parse(fs.readFileSync(ownerFile, 'utf8'));
181
- } catch {
182
- return null;
183
- }
184
- };
185
- // A lock naming this very process on this computer, that this process
186
- // does not hold, is left from a process that had this pid before (a
187
- // container restarted).
188
- const held = owner();
189
- if (
190
- held?.pid === process.pid &&
191
- held?.host === os.hostname() &&
192
- !HELD.has(lock)
193
- )
194
- fs.rmSync(lock, {recursive: true, force: true});
200
+ async function withLock(root, name, fn, bestEffort = false) {
201
+ /** @type {string | null} */
202
+ let dir;
195
203
  try {
196
- // The release cache's lock: made with mkdir (one taker wins), and a
197
- // holder that stopped is taken over by a rename (one taker wins).
198
- for (let waited = 0; !tryLock(lock); waited += 50) {
199
- if (waited > 30_000) {
200
- const o = owner();
201
- throw new AstryxError(
202
- `Another command is changing ${name.replace(/^theme-/, '')} and did not finish within 30 seconds${o ? ` (process ${o.pid} on ${o.host}, for ${Math.round((Date.now() - Number(o.at)) / 1000)} s)` : ''}. Nothing was changed; run this command again. If no astryx command is running, the lock is left from one that stopped: remove the folder ${lock}.`,
203
- [],
204
- ERROR_CODES.ERR_THEME_BUSY,
205
- );
206
- }
207
- await sleep(50);
208
- }
204
+ dir = lockDir(root);
209
205
  } catch (e) {
210
- if (e instanceof AstryxError) throw e;
211
- throw new AstryxError(
212
- `Could not take the lock ${lock} (${/** @type {any} */ (e).code ?? String(e)}). Nothing was changed; fix the folder, then run the command again.`,
213
- [],
214
- ERROR_CODES.ERR_WRITE_FAILED,
215
- );
206
+ if (bestEffort) return fn(false);
207
+ throw e;
216
208
  }
217
- HELD.add(lock);
218
- const mine = fs.existsSync(ownerFile)
219
- ? fs.readFileSync(ownerFile, 'utf8')
220
- : null;
221
- // Only this command's own lock is removed, never one another took over.
222
- const release = () => {
209
+ if (!dir) return fn(true);
210
+ // The lock is named for the project as seen from the lock folder (which
211
+ // lives in the project's own node_modules), not by the path this command
212
+ // was given: one project reached through two paths (a bind mount, a
213
+ // devcontainer) has one lock.
214
+ /** @param {string} p */
215
+ const real = p => {
223
216
  try {
224
- const now = fs.existsSync(ownerFile)
225
- ? fs.readFileSync(ownerFile, 'utf8')
226
- : null;
227
- if (now === mine) fs.rmSync(lock, {recursive: true, force: true});
217
+ return fs.realpathSync(p);
228
218
  } catch {
229
- // Gone already.
219
+ return path.resolve(p);
230
220
  }
231
221
  };
232
- // Stopped by a signal, the lock still goes.
233
- const onSignal = (/** @type {NodeJS.Signals} */ sig) => {
234
- release();
235
- process.kill(process.pid, sig);
236
- };
237
- process.once('exit', release);
238
- process.once('SIGINT', onSignal);
239
- process.once('SIGTERM', onSignal);
222
+ const key = createHash('sha256')
223
+ .update(path.relative(real(dir), real(root)).split(path.sep).join('/'))
224
+ .digest('hex')
225
+ .slice(0, 16);
226
+ const lock = path.join(dir, `${key}-${name}.lock`);
227
+ // The release cache's lock, held with its lease while the command runs
228
+ // (foundation/release/folder-lock.mjs). A lock naming this pid is never
229
+ // taken over on that ground alone: two containers on one checkout can
230
+ // both be pid 1.
231
+ let started = false;
240
232
  try {
241
- return await fn();
233
+ return await withFolderLock(
234
+ lock,
235
+ async () => {
236
+ started = true;
237
+ return fn(true);
238
+ },
239
+ {
240
+ onBusy: (o, held) => {
241
+ throw new AstryxError(
242
+ `Another command has been changing ${name.replace(/^theme-/, '')} for 30 seconds${o ? ` (process ${o.pid} on ${o.host}${held != null ? `, holding it ${held} s` : ''})` : ''}. Nothing was changed; run this command again. If no astryx command is running, the lock is left from one that stopped: remove the folder ${lock}.`,
243
+ // A look that takes no lock: the last build as it is.
244
+ [
245
+ {
246
+ name: name.startsWith('theme-')
247
+ ? `${P} show ${name.replace(/^theme-/, '')}`
248
+ : 'astryx experimental theme preview list',
249
+ reason: 'see it as it is now',
250
+ },
251
+ ],
252
+ ERROR_CODES.ERR_THEME_BUSY,
253
+ );
254
+ },
255
+ },
256
+ );
242
257
  } catch (e) {
258
+ if (e instanceof AstryxError) throw e;
259
+ const code = /** @type {any} */ (e)?.code;
260
+ if (!started) {
261
+ if (bestEffort) return fn(false);
262
+ throw new AstryxError(
263
+ `Could not take the lock ${lock} (${code ?? String(e)}). Nothing was changed; fix the folder, then run the command again.`,
264
+ [
265
+ {
266
+ name: `ls -ld ${quoteCommandArgument(path.dirname(lock))}`,
267
+ reason: 'see who owns the lock folder',
268
+ },
269
+ ],
270
+ ERROR_CODES.ERR_WRITE_FAILED,
271
+ );
272
+ }
243
273
  // A folder that cannot be written (no permission, a full or read-only
244
274
  // disk) is a documented refusal, not a crash.
245
- const code = /** @type {any} */ (e)?.code;
246
- if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS'].includes(code))
275
+ if (['EACCES', 'EPERM', 'ENOSPC', 'EROFS', 'EIO'].includes(code))
247
276
  throw new AstryxError(
248
- `Could not write ${path.relative(root, /** @type {any} */ (e).path ?? '') || 'the theme files'}: ${code === 'ENOSPC' ? 'the disk is full' : code === 'EROFS' ? 'the disk is read-only' : 'no permission'}. Free the space or fix the permission, then run the command again; a refused change is undone.`,
249
- [],
277
+ `Could not write ${path.relative(root, /** @type {any} */ (e).path ?? '') || 'the theme files'}: ${code === 'ENOSPC' ? 'the disk is full' : code === 'EROFS' ? 'the disk is read-only' : code === 'EIO' ? 'the disk could not be read or written' : 'no permission'}. ${code === 'EROFS' ? 'Make the folder writable' : code === 'EIO' ? 'Check the disk' : 'Free the space or fix the permission'}, then run the command again; a refused change is undone.`,
278
+ [
279
+ {
280
+ name: `ls -ld ${quoteCommandArgument(path.dirname(/** @type {any} */ (e).path ?? path.join(root, 'themes', 'x')))}`,
281
+ reason: 'see who owns the folder and whether it is writable',
282
+ },
283
+ ],
250
284
  ERROR_CODES.ERR_WRITE_FAILED,
251
285
  );
252
286
  throw e;
253
- } finally {
254
- release();
255
- HELD.delete(lock);
256
- process.removeListener('exit', release);
257
- process.removeListener('SIGINT', onSignal);
258
- process.removeListener('SIGTERM', onSignal);
259
287
  }
260
288
  }
261
289
 
@@ -320,13 +348,92 @@ function absolute(result, root, from) {
320
348
  * @param {(o: O & {cwd: string}) => Promise<T>} fn
321
349
  * @returns {Promise<T>}
322
350
  */
323
- async function inProject(options, lock, fn) {
351
+ async function inProject(options, lock, fn, bestEffort = false) {
324
352
  const from = options.cwd ?? process.cwd();
325
353
  const o = atRoot(options);
326
- const r = lock ? await withLock(o.cwd, lock, () => fn(o)) : await fn(o);
327
- return absolute(r, o.cwd, from);
354
+ try {
355
+ // Without the lock (it cannot be taken), a read-only command writes
356
+ // nothing.
357
+ const r = lock
358
+ ? await withLock(
359
+ o.cwd,
360
+ lock,
361
+ locked => fn(locked ? o : {...o, readOnly: true}),
362
+ bestEffort,
363
+ )
364
+ : await fn(o);
365
+ return absolute(r, o.cwd, from);
366
+ } catch (e) {
367
+ throw fromCaller(e, o.cwd, from);
368
+ }
369
+ }
370
+
371
+ /**
372
+ * A refusal whose suggested preview commands name folders as the person
373
+ * types them where they ran the command: a `--path` and a `preview app`
374
+ * folder, read from the project root, are written from the caller's
375
+ * folder.
376
+ * @param {any} e
377
+ * @param {string} root
378
+ * @param {string} from
379
+ */
380
+ function fromCaller(e, root, from) {
381
+ if (path.resolve(from) === root || !Array.isArray(e?.suggestions)) return e;
382
+ const ARG = String.raw`('(?:[^']|'\\'')*'|"[^"]*"|[^\s'"]+)`;
383
+ /** @param {string} v */
384
+ const unquote = v =>
385
+ v.startsWith("'")
386
+ ? v.slice(1, -1).replace(/'\\''/g, "'")
387
+ : v.startsWith('"')
388
+ ? v.slice(1, -1)
389
+ : v;
390
+ /** @param {string} v */
391
+ const rel = v =>
392
+ /^<.*>$/.test(v)
393
+ ? v
394
+ : quoteCommandArgument(
395
+ path.relative(path.resolve(from), path.resolve(root, unquote(v))) ||
396
+ '.',
397
+ );
398
+ for (const s of e.suggestions) {
399
+ if (typeof s?.name !== 'string') continue;
400
+ if (!s.name.startsWith('astryx experimental theme preview ')) continue;
401
+ s.name = s.name
402
+ .replace(
403
+ new RegExp(`(--path )${ARG}`, 'g'),
404
+ (
405
+ /** @type {string} */ _m,
406
+ /** @type {string} */ flag,
407
+ /** @type {string} */ v,
408
+ ) => flag + rel(v),
409
+ )
410
+ .replace(
411
+ new RegExp(`^(astryx experimental theme preview app )${ARG}`),
412
+ (
413
+ /** @type {string} */ _m,
414
+ /** @type {string} */ cmd,
415
+ /** @type {string} */ v,
416
+ ) => cmd + rel(v),
417
+ );
418
+ }
419
+ return e;
328
420
  }
329
421
 
422
+ /**
423
+ * Options for a preview command, with a way to hold a theme's lock while
424
+ * the preview builds that theme.
425
+ * @template {{cwd: string}} O
426
+ * @param {O} o
427
+ * @returns {any}
428
+ */
429
+ const withThemeLock = o => ({
430
+ ...o,
431
+ lockTheme: (
432
+ /** @type {string} */ slug,
433
+ /** @type {() => Promise<any>} */ fn,
434
+ ) => withLock(o.cwd, lockName(slug), fn),
435
+ });
436
+
330
437
  /** @type {typeof edit.themeEditNew} */
331
438
  export const themeEditNew = (name, options = {}) =>
332
439
  inProject(options, lockName(name), o => edit.themeEditNew(name, o));
@@ -340,11 +447,11 @@ export const themeEditUndo = (theme, options = {}) =>
340
447
  inProject(options, lockName(theme), o => edit.themeEditUndo(theme, o));
341
448
  /** @type {typeof edit.themeEditShow} */
342
449
  export const themeEditShow = (theme, options = {}) =>
343
- inProject(options, lockName(theme), o => edit.themeEditShow(theme, o));
450
+ inProject(options, lockName(theme), o => edit.themeEditShow(theme, o), true);
344
451
  /** @type {typeof preview.themeEditPreviewAdd} */
345
452
  export const themeEditPreviewAdd = (description, options = {}) =>
346
453
  inProject(options, 'preview', o =>
347
- preview.themeEditPreviewAdd(description, o),
454
+ preview.themeEditPreviewAdd(description, withThemeLock(o)),
348
455
  );
349
456
  /**
350
457
  * `preview app` runs from the project root, with `dir` kept pointing where
@@ -364,6 +471,7 @@ export const themeEditPreviewApp = (dir, options = {}) => {
364
471
  : dir,
365
472
  o,
366
473
  ),
474
+ true,
367
475
  );
368
476
  };
369
477
  /** @type {typeof preview.themeEditPreviewList} */
@@ -371,4 +479,280 @@ export const themeEditPreviewList = (options = {}) =>
371
479
  inProject(options, null, async o => preview.themeEditPreviewList(o));
372
480
  /** @type {typeof preview.themeEditPreviewRemove} */
373
481
  export const themeEditPreviewRemove = (page, options = {}) =>
374
- inProject(options, 'preview', o => preview.themeEditPreviewRemove(page, o));
482
+ inProject(options, 'preview', o =>
483
+ preview.themeEditPreviewRemove(page, withThemeLock(o)),
484
+ );
485
+
486
+ /**
487
+ * The editor theme a path or a name names, with its project, or null: a
488
+ * name is a theme in `root`'s themes/ folder; a path is one in the themes/
489
+ * folder of the project the file belongs to (found from the file, so a
490
+ * path from another folder still names it, and a `src/themes/<slug>` fork
491
+ * does not).
492
+ * @param {string} root
493
+ * @param {string} word a path or a name
494
+ * @returns {{root: string, slug: string} | null}
495
+ */
496
+ function editorThemeAt(root, word) {
497
+ const has = (/** @type {string} */ r, /** @type {string} */ slug) =>
498
+ fs.existsSync(path.join(r, 'themes', slug, `${slug}.settings.json`));
499
+ if (/^[a-z][a-z0-9-]*$/.test(word))
500
+ return has(root, word) ? {root, slug: word} : null;
501
+ // Through a link, the real path decides (a linked theme folder is the
502
+ // same folder).
503
+ /** @type {string} */
504
+ let abs = path.resolve(root, word);
505
+ try {
506
+ abs = fs.realpathSync(abs);
507
+ } catch {
508
+ try {
509
+ abs = path.join(fs.realpathSync(path.dirname(abs)), path.basename(abs));
510
+ } catch {
511
+ // Not there: the path as given.
512
+ }
513
+ }
514
+ // The folder above the last themes/<slug>/ in the path, when that folder
515
+ // is a project's root (src/themes/<slug> is not: its project is above).
516
+ const m = /^(.*)[\\/]themes[\\/]([a-z][a-z0-9-]*)(?:[\\/]|$)/.exec(abs);
517
+ if (!m || !has(m[1], m[2])) return null;
518
+ /** @type {string} */
519
+ let top;
520
+ try {
521
+ top = projectRoot(m[1]);
522
+ } catch {
523
+ top = m[1];
524
+ }
525
+ return path.resolve(top) === path.resolve(m[1])
526
+ ? {root: m[1], slug: m[2]}
527
+ : null;
528
+ }
529
+
530
+ /**
531
+ * Whether a file in an editor theme's folder is one of the editor's own
532
+ * (its theme source or settings), which the editor guards; another file
533
+ * there (a template written into the folder) is compiled as any file.
534
+ * @param {string} slug
535
+ * @param {string} file
536
+ */
537
+ function editorOwnFile(slug, file) {
538
+ return [
539
+ `${slug}.theme.ts`,
540
+ `${slug}.settings.ts`,
541
+ `${slug}.settings.json`,
542
+ ].includes(path.basename(file));
543
+ }
544
+
545
+ /**
546
+ * The editor theme a path or name names in `root`, or null.
547
+ * @param {string} root
548
+ * @param {string} word
549
+ */
550
+ function editorThemeOf(root, word) {
551
+ return editorThemeAt(root, word)?.slug ?? null;
552
+ }
553
+
554
+ /**
555
+ * A suggested command, started the way this project runs the CLI.
556
+ * @param {string} cwd
557
+ * @param {string} rest the words after `astryx`
558
+ */
559
+ function runLine(cwd, rest) {
560
+ return `${getCliInvocation(cwd)} ${rest}`;
561
+ }
562
+
563
+ /**
564
+ * A clearer refusal for a theme the editor made, named to list, add, use,
565
+ * remove or eject: those commands work on package themes, and the editor
566
+ * theme is used by importing its module. Null for any other refusal.
567
+ * @param {AstryxError} err
568
+ * @param {string} cwd
569
+ * @returns {AstryxError | null}
570
+ */
571
+ export function editorThemeRefusal(err, cwd) {
572
+ // A refused compile ends here: its theme locks go now, not at exit.
573
+ void releaseCompileHold?.();
574
+ if (
575
+ err.code !== ERROR_CODES.ERR_UNKNOWN_THEME &&
576
+ !/unknown theme|is not added|not a theme package/i.test(err.message)
577
+ )
578
+ return null;
579
+ const root = projectRoot(cwd);
580
+ const named = /"([a-z][a-z0-9-]*)"|'([a-z][a-z0-9-]*)'/.exec(err.message);
581
+ const slug = named ? editorThemeOf(root, named[1] ?? named[2]) : null;
582
+ if (!slug) return null;
583
+ // A local theme of that name (a fork in the app's own themes folder) is
584
+ // one the stable commands take: their own message stands.
585
+ if (fs.existsSync(path.join(root, LOCAL_THEME_ROOT, slug))) return null;
586
+ const id = `${camel(slug)}Theme`;
587
+ const key = /^[a-z][a-z0-9]*$/i.test(slug) ? slug : JSON.stringify(slug);
588
+ return new AstryxError(
589
+ `${slug} is a theme the editor made (themes/${slug}/), not a theme package, so list, add, use, remove and eject do not take it. To use it, import its module and its stylesheet in a file of your own (import {${id}} from './themes/${slug}/${slug}.js'; import './themes/${slug}/${slug}.css';) and merge it into the themes there ({...themes, ${key}: ${id}}); do not add it to src/astryx-themes.ts, which add, use and remove write again. Change it with the editor.`,
590
+ [
591
+ {
592
+ name: runLine(cwd, `experimental theme editor show ${slug}`),
593
+ reason: 'see the theme',
594
+ },
595
+ ],
596
+ ERROR_CODES.ERR_UNKNOWN_THEME,
597
+ );
598
+ }
599
+
600
+ /**
601
+ * A refusal before `compile` runs on an editor theme's files, or null: the
602
+ * editor's generated settings are not a theme source, `--family` does not
603
+ * take an editor theme, and `--check` checks an editor theme by the editor's
604
+ * own rules (waiting for a change in progress).
605
+ * @param {string[]} files
606
+ * @param {{cwd: string, check?: boolean, family?: boolean}} options
607
+ * @returns {Promise<AstryxError | null>}
608
+ */
609
+ export async function editorCompileProblem(files, {cwd, check, family}) {
610
+ const cwdRoot = projectRoot(cwd);
611
+ for (const file of files) {
612
+ const at = editorThemeAt(cwdRoot, path.resolve(cwd, file));
613
+ if (!at || !editorOwnFile(at.slug, file)) continue;
614
+ const {root, slug} = at;
615
+ const source = `themes/${slug}/${slug}.theme.ts`;
616
+ if (/\.settings\.(ts|json)$/.test(file))
617
+ return new AstryxError(
618
+ `${file} is the editor's own settings for ${slug}, not a theme source; compile the theme source.`,
619
+ [
620
+ {
621
+ name: runLine(
622
+ cwd,
623
+ `experimental theme compile ${quoteCommandArgument(path.relative(cwd, path.join(root, source)) || source)}`,
624
+ ),
625
+ reason: 'do this instead',
626
+ },
627
+ ],
628
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
629
+ );
630
+ if (family)
631
+ return new AstryxError(
632
+ `${slug} is a theme the editor made; --family builds package theme families, not editor themes. Compile it on its own.`,
633
+ [
634
+ {
635
+ name: runLine(
636
+ cwd,
637
+ `experimental theme compile ${quoteCommandArgument(path.relative(cwd, path.join(root, source)) || source)}`,
638
+ ),
639
+ reason: 'do this instead',
640
+ },
641
+ ],
642
+ ERROR_CODES.ERR_INVALID_ARGUMENT,
643
+ );
644
+ {
645
+ // A check waits for a change in progress, so it never reads one half
646
+ // written. A plain compile builds the theme source, which reads the
647
+ // generated settings: when those no longer match the settings, it
648
+ // would report ok without them.
649
+ // `compile` holds the lock already while it runs (editorThemeHold).
650
+ /** @type {string | null} */
651
+ let why;
652
+ try {
653
+ why = COMPILE_HELD.has(`${root}\0${slug}`)
654
+ ? await edit.editorStale(root, slug)
655
+ : await withLock(root, lockName(slug), () =>
656
+ edit.editorStale(root, slug),
657
+ );
658
+ } catch (e) {
659
+ // A settings file damaged by hand is refused like any refusal,
660
+ // never as a raw error.
661
+ if (e instanceof AstryxError) return e;
662
+ throw e;
663
+ }
664
+ if (why && !check)
665
+ return new AstryxError(
666
+ `${slug}'s generated settings do not match its settings (${why}), so compile would build the old ones. The editor builds it from its settings.`,
667
+ [
668
+ {
669
+ name: runLine(cwd, `experimental theme editor show ${slug}`),
670
+ reason: 'do this instead',
671
+ },
672
+ ],
673
+ ERROR_CODES.ERR_THEME_INVALID,
674
+ );
675
+ if (why)
676
+ return new AstryxError(
677
+ `${slug} is not up to date: ${why}. The editor builds it again from its settings.`,
678
+ [
679
+ {
680
+ name: runLine(cwd, `experimental theme editor show ${slug}`),
681
+ reason: 'build it again',
682
+ },
683
+ ],
684
+ ERROR_CODES.ERR_THEME_INVALID,
685
+ );
686
+ }
687
+ }
688
+ return null;
689
+ }
690
+
691
+ /** The editor themes a running `compile` holds the lock of, by project and name. */
692
+ const COMPILE_HELD = new Set();
693
+
694
+ /** @type {(() => Promise<void>) | null} The release of the running compile's hold. */
695
+ let releaseCompileHold = null;
696
+
697
+ /**
698
+ * Hold the theme lock of every editor theme among the files while
699
+ * `compile` builds or checks them, so it never reads a change half
700
+ * written. Resolves to the release.
701
+ * @param {string[]} files
702
+ * @param {{cwd: string}} options
703
+ * @returns {Promise<() => Promise<void>>}
704
+ */
705
+ export async function editorThemeHold(files, {cwd}) {
706
+ // Two compiles of one theme in one process: the second waits for the
707
+ // lock like any other command.
708
+ const cwdRoot = projectRoot(cwd);
709
+ const found = new Map();
710
+ for (const f of files) {
711
+ const at = editorThemeAt(cwdRoot, path.resolve(cwd, f));
712
+ if (at && editorOwnFile(at.slug, f))
713
+ found.set(`${at.root}\0${at.slug}`, at);
714
+ }
715
+ const themes = [...found.keys()].sort().map(k => found.get(k));
716
+ /** @type {Array<() => Promise<void>>} */
717
+ const releases = [];
718
+ const releaseAll = async () => {
719
+ if (releaseCompileHold === releaseAll) releaseCompileHold = null;
720
+ for (const r of releases.splice(0).reverse()) await r();
721
+ };
722
+ releaseCompileHold = releaseAll;
723
+ for (const {
724
+ root,
725
+ slug,
726
+ } of /** @type {Array<{root: string, slug: string}>} */ (themes)) {
727
+ /** @type {() => void} */
728
+ let release = () => {};
729
+ const held = new Promise(r => {
730
+ release = () => r(undefined);
731
+ });
732
+ /** @type {(e?: unknown) => void} */
733
+ let ready = () => {};
734
+ const got = new Promise(r => {
735
+ ready = r;
736
+ });
737
+ const key = `${root}\0${slug}`;
738
+ const done = withLock(root, lockName(slug), async () => {
739
+ COMPILE_HELD.add(key);
740
+ ready();
741
+ try {
742
+ await held;
743
+ } finally {
744
+ COMPILE_HELD.delete(key);
745
+ }
746
+ }).catch(e => ready(e));
747
+ const err = await got;
748
+ if (err) {
749
+ await releaseAll();
750
+ throw err;
751
+ }
752
+ releases.push(async () => {
753
+ release();
754
+ await done;
755
+ });
756
+ }
757
+ return releaseAll;
758
+ }