@astryxdesign/cli 0.7.15 → 0.7.16-canary.g07c77c0

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 (159) hide show
  1. package/README.md +5 -3
  2. package/api/build/_adapter.d.mts +1 -0
  3. package/api/build/blocks/blocks.d.mts +1 -0
  4. package/api/build/blocks/blocks.mjs +18 -1
  5. package/api/component/_adapter.d.mts +1 -1
  6. package/api/component/_adapter.mjs +28 -1
  7. package/api/doctor/_adapter.d.mts +17 -0
  8. package/api/doctor/_adapter.mjs +43 -0
  9. package/api/doctor/built-checks.mjs +1 -1
  10. package/api/doctor/doctor.mjs +18 -4
  11. package/api/doctor/theme-checks.mjs +1 -1
  12. package/api/integration/add-contribution.mjs +3 -3
  13. package/api/integration/pack-check.mjs +14 -8
  14. package/api/integration/validate-integration.mjs +1 -1
  15. package/api/search/_adapter.mjs +15 -16
  16. package/api/search/_entries.d.mts +2 -1
  17. package/api/search/_entries.mjs +28 -1
  18. package/api/swizzle/_moduleGraph.mjs +1 -1
  19. package/api/theme/_adapter.d.mts +5 -2
  20. package/api/theme/_adapter.mjs +43 -12
  21. package/api/theme/_fork.mjs +1 -1
  22. package/api/theme/build/build.d.mts +116 -32
  23. package/api/theme/build/build.mjs +449 -102
  24. package/api/theme/eject/eject.mjs +22 -1
  25. package/api/theme/template/template.d.mts +19 -0
  26. package/api/theme/template/template.mjs +102 -25
  27. package/api/theme/theme.type.d.mts +5 -1
  28. package/api/theme/theme.type.mjs +2 -1
  29. package/api/theme/themeBuild.doc.mjs +3 -3
  30. package/api/theme/themeEject.doc.mjs +1 -1
  31. package/api/theme/themeTemplate.doc.mjs +9 -3
  32. package/api/theme-edit/_adapter.d.mts +32 -2
  33. package/api/theme-edit/_adapter.mjs +213 -36
  34. package/api/theme-edit/_check.d.mts +69 -3
  35. package/api/theme-edit/_check.mjs +1517 -218
  36. package/api/theme-edit/_color.d.mts +2 -8
  37. package/api/theme-edit/_color.mjs +292 -219
  38. package/api/theme-edit/_compiler.d.mts +1 -0
  39. package/api/theme-edit/_compiler.mjs +20 -1
  40. package/api/theme-edit/_context.d.mts +29 -0
  41. package/api/theme-edit/_context.mjs +426 -40
  42. package/api/theme-edit/_css.d.mts +60 -1
  43. package/api/theme-edit/_css.mjs +404 -28
  44. package/api/theme-edit/_edit.d.mts +9 -0
  45. package/api/theme-edit/_edit.mjs +1300 -135
  46. package/api/theme-edit/_how-commands.d.mts +11 -26
  47. package/api/theme-edit/_how-commands.mjs +30 -2
  48. package/api/theme-edit/_how-question.d.mts +7 -0
  49. package/api/theme-edit/_how-question.mjs +1304 -176
  50. package/api/theme-edit/_how.mjs +144 -30
  51. package/api/theme-edit/_overview.mjs +2 -0
  52. package/api/theme-edit/_palette.d.mts +11 -0
  53. package/api/theme-edit/_palette.mjs +194 -65
  54. package/api/theme-edit/_parts.d.mts +33 -0
  55. package/api/theme-edit/_parts.mjs +138 -9
  56. package/api/theme-edit/_png.d.mts +18 -0
  57. package/api/theme-edit/_png.mjs +95 -14
  58. package/api/theme-edit/_preview-app.d.mts +9 -0
  59. package/api/theme-edit/_preview-app.mjs +1191 -71
  60. package/api/theme-edit/_preview.d.mts +16 -3
  61. package/api/theme-edit/_preview.mjs +335 -30
  62. package/api/theme-edit/_project.d.mts +11 -0
  63. package/api/theme-edit/_project.mjs +46 -12
  64. package/api/theme-edit/_settings.d.mts +240 -5
  65. package/api/theme-edit/_settings.mjs +2561 -115
  66. package/api/theme-edit/_tables.d.mts +24 -0
  67. package/api/theme-edit/_tables.mjs +211 -149
  68. package/api/theme-edit/_vet.d.mts +42 -0
  69. package/api/theme-edit/_vet.mjs +144 -0
  70. package/api/theme-edit/theme-edit.type.d.mts +2 -1
  71. package/api/theme-edit/theme-edit.type.mjs +1 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditShow.doc.mjs +11 -3
  74. package/api/upgrade/registry/registry.mjs +6 -1
  75. package/assets/codemods/parse.mjs +2 -2
  76. package/assets/docs/tree/single-component.doc.mjs +11 -2
  77. package/assets/docs/tree/tokens-and-setup.doc.mjs +39 -3
  78. package/assets/docs.generated.json +2 -2
  79. package/assets/preview-app/next.config.mjs +7 -1
  80. package/assets/preview-app/package.json +1 -0
  81. package/assets/preview-app/src/app/globals.css +1 -0
  82. package/assets/self-audit.generated.json +1 -1
  83. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.doc.mjs +14 -0
  84. package/assets/templates/blocks/components/Table/ColumnsVirtualizationHookUsage.tsx +53 -0
  85. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.doc.mjs +14 -0
  86. package/assets/templates/blocks/components/Table/InfiniteScrollHookUsage.tsx +33 -0
  87. package/assets/templates/components.generated.json +1 -1
  88. package/assets/templates/pages/dashboard/page.tsx +1 -1
  89. package/authoring/doctypes/_schema.d.mts +52 -5
  90. package/authoring/doctypes/_schema.mjs +62 -7
  91. package/authoring/doctypes/base/type.ts +10 -0
  92. package/authoring/doctypes/component/component.doc.mjs +1 -1
  93. package/authoring/doctypes/function/function.doc.mjs +6 -0
  94. package/authoring/doctypes/function/type.ts +3 -0
  95. package/authoring/doctypes/legacy.mjs +5 -1
  96. package/authoring/index.d.ts +1 -0
  97. package/authoring/shadcn/source-variants.d.mts +1 -1
  98. package/authoring/shadcn/source-variants.mjs +32 -10
  99. package/clients/cli/build-id.generated.json +1 -1
  100. package/clients/cli/commands/doctor.doc.mjs +2 -2
  101. package/clients/cli/commands/experimental/theme.mjs +237 -45
  102. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  103. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +2 -2
  104. package/clients/cli/commands/experimental-theme-editor-set.doc.mjs +2 -2
  105. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +3 -3
  106. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +2 -2
  107. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  108. package/clients/cli/commands/experimental-theme-eject.doc.mjs +1 -1
  109. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  110. package/clients/cli/commands/experimental-theme-template.doc.mjs +2 -2
  111. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  112. package/clients/cli/commands/theme-eject.doc.mjs +1 -1
  113. package/clients/cli/commands/theme-template.doc.mjs +3 -1
  114. package/clients/cli/commands/theme.mjs +190 -46
  115. package/clients/cli/formatters/index.mjs +7 -4
  116. package/clients/cli/lib/cli-error.mjs +9 -3
  117. package/clients/cli/lib/component-format.mjs +27 -9
  118. package/clients/cli/lib/json-shim.mjs +72 -2
  119. package/clients/cli/manifest.generated.json +1 -1
  120. package/clients/cli/run.mjs +49 -0
  121. package/foundation/agent-docs/agent-docs-target.d.mts +2 -6
  122. package/foundation/agent-docs/agent-docs-target.mjs +9 -17
  123. package/foundation/agent-docs/agent-docs.mjs +3 -2
  124. package/foundation/config/config-writer.mjs +2 -2
  125. package/foundation/config/project.mjs +60 -14
  126. package/foundation/discovery/component-discovery.mjs +5 -17
  127. package/foundation/discovery/icon-set-writer.mjs +1 -1
  128. package/foundation/discovery/module-exports.mjs +1 -15
  129. package/foundation/discovery/template-adapter.mjs +44 -19
  130. package/foundation/discovery/template-source-tree.mjs +3 -16
  131. package/foundation/discovery/theme-discovery.d.mts +5 -1
  132. package/foundation/discovery/theme-discovery.mjs +30 -35
  133. package/foundation/fs/exact-codec.d.mts +35 -0
  134. package/foundation/fs/exact-codec.mjs +148 -0
  135. package/foundation/fs/gather-cache.d.mts +15 -5
  136. package/foundation/fs/gather-cache.mjs +123 -30
  137. package/foundation/fs/paths.d.mts +39 -0
  138. package/foundation/fs/paths.mjs +44 -11
  139. package/foundation/fs/read-record.mjs +11 -1
  140. package/foundation/integrations/contribution-fixes.mjs +1 -16
  141. package/foundation/integrations/may-have-integrations.mjs +3 -2
  142. package/foundation/integrations/public-imports.mjs +1 -1
  143. package/foundation/render/embedded-imports.mjs +1 -1
  144. package/foundation/render/host-exit.d.mts +8 -0
  145. package/foundation/render/host-exit.mjs +11 -0
  146. package/foundation/render/page-host.mjs +56 -10
  147. package/foundation/render/page-worker.mjs +14 -0
  148. package/foundation/render/render-page.mjs +37 -2
  149. package/foundation/response/error-codes.d.mts +2 -1
  150. package/foundation/response/error-codes.d.ts +1 -0
  151. package/foundation/response/error-codes.doc.mjs +5 -0
  152. package/foundation/response/error-codes.mjs +3 -0
  153. package/foundation/response/json.d.mts +15 -0
  154. package/foundation/response/json.mjs +52 -1
  155. package/foundation/response/response-types.doc.mjs +1 -1
  156. package/foundation/runtime/lazy-dependencies.d.mts +14 -0
  157. package/foundation/runtime/lazy-dependencies.mjs +82 -0
  158. package/foundation/xle/browser.d.mts +2 -2
  159. package/package.json +7 -6
@@ -8,14 +8,26 @@
8
8
  * @position api/theme-edit — imported only by the adapter's operation helpers
9
9
  */
10
10
 
11
+ import {createHash} from 'node:crypto';
11
12
  import * as fs from 'node:fs';
12
13
  import {createRequire} from 'node:module';
13
14
  import * as path from 'node:path';
15
+ import {pathToFileURL} from 'node:url';
14
16
  import {AstryxError} from '../error.mjs';
15
- import {isOutsideProject} from '../../foundation/env/project-scope.mjs';
17
+ import {EDITOR_STAMP, withPngText} from './_png.mjs';
18
+ import {
19
+ findDeclaredWorkspaceRoot,
20
+ findNodeModulesPackage,
21
+ homeFolder,
22
+ } from '../../foundation/fs/paths.mjs';
23
+ import {
24
+ detectPackageManager,
25
+ quoteCommandArgument,
26
+ } from '../../foundation/env/package-manager.mjs';
16
27
  import {
17
28
  CLOSEST_OPEN_FONT,
18
29
  FONT_ROLES,
30
+ FONTS,
19
31
  OPEN_FONTS,
20
32
  isDesktopFamily,
21
33
  oneSystemOf,
@@ -32,7 +44,11 @@ import {
32
44
  modesOf,
33
45
  nearest,
34
46
  refuse,
47
+ adoptOlderPicture,
48
+ editorWrote,
49
+ recordWritten,
35
50
  themeFiles,
51
+ refuseThemesNotFolder,
36
52
  } from './_settings.mjs';
37
53
  import {SHOWCASE_GROUPS, renderPreview, screenshot} from './_preview.mjs';
38
54
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -45,10 +61,13 @@ const E = ERROR_CODES;
45
61
  * @param {string} cwd
46
62
  */
47
63
  export function requireProject(cwd) {
48
- if (!isOutsideProject(cwd)) return;
49
- const pkg = path.join(cwd, 'package.json');
50
- // Yarn Plug'n'Play has no node_modules for the editor to read Core from.
51
- if (fs.existsSync(path.join(cwd, '.pnp.cjs')))
64
+ // One rule: the app is the nearest folder at or above cwd whose
65
+ // package.json lists @astryxdesign/core.
66
+ const app = coreApp(cwd);
67
+ if (!app) refuseNoApp(cwd);
68
+ // Yarn Plug'n'Play has no node_modules for the editor to read Core from:
69
+ // its .pnp.cjs sits at the app or at the workspace root above it.
70
+ if (pnpAbove(app))
52
71
  throw new AstryxError(
53
72
  "This app uses Yarn Plug'n'Play, which astryx experimental theme does not support: it reads the installed Core from node_modules. Set `nodeLinker: node-modules` in .yarnrc.yml and run yarn install. Nothing was written.",
54
73
  [
@@ -59,21 +78,11 @@ export function requireProject(cwd) {
59
78
  ],
60
79
  E.ERR_PROJECT_REQUIRED,
61
80
  );
62
- // A package.json with no Core: an app (or a workspace root) that needs it.
63
- if (fs.existsSync(pkg))
64
- throw new AstryxError(
65
- `@astryxdesign/core is not installed in this app (package.json here does not use it). astryx experimental theme checks every change against the installed Core: install it, or run the command from the package that uses it. Nothing was written.`,
66
- [{name: 'npm install @astryxdesign/core', reason: 'do this first'}],
67
- E.ERR_PROJECT_REQUIRED,
68
- );
81
+ if (findNodeModulesPackage(app, '@astryxdesign/core')) return;
82
+ // The app lists Core but it is not installed.
69
83
  throw new AstryxError(
70
- 'No package.json found. astryx experimental theme works inside an app project, which it writes the theme into and whose installed Core it checks every change against. Nothing was written.',
71
- [
72
- {
73
- name: 'npm init -y',
74
- reason: 'make a package.json here, then install @astryxdesign/core',
75
- },
76
- ],
84
+ `${path.relative(path.resolve(cwd), app) || 'This app'}'s package.json lists @astryxdesign/core, but it is not installed. astryx experimental theme checks every change against the installed Core: install the app's packages, then run the command again. Nothing was written.`,
85
+ [{name: installAll(app), reason: 'do this first, in the app'}],
77
86
  E.ERR_PROJECT_REQUIRED,
78
87
  );
79
88
  }
@@ -86,6 +95,7 @@ export function requireProject(cwd) {
86
95
  */
87
96
  export async function context(cwd) {
88
97
  requireProject(cwd);
98
+ refuseThemesNotFolder(cwd);
89
99
  const project = await openProject(cwd);
90
100
  /** @type {import('./_parts.mjs').PartData} */
91
101
  let parts;
@@ -114,22 +124,221 @@ export async function context(cwd) {
114
124
  parts,
115
125
  unchecked,
116
126
  uncheckedCode,
127
+ derived: await derivedVars(project.coreDir),
117
128
  };
118
129
  }
119
130
 
131
+ /**
132
+ * Core's registry of the variables a part's plain border-radius or padding
133
+ * also writes (a card's inner corners), or empty on a Core without it.
134
+ * @param {string} coreDir
135
+ * @returns {Promise<Record<string, Array<{property: string, vars?: string[], replaces?: boolean, expand?: string}>>>}
136
+ */
137
+ async function derivedVars(coreDir) {
138
+ const file = path.join(coreDir, 'dist', 'theme', 'derivedVarRegistry.js');
139
+ if (!fs.existsSync(file)) return {};
140
+ try {
141
+ const mod = await import(pathToFileURL(file).href);
142
+ return mod.derivedVarRegistry ?? {};
143
+ } catch {
144
+ return {};
145
+ }
146
+ }
147
+
120
148
  /** @param {unknown} e */
121
149
  const isRenderFailure = e =>
122
150
  e instanceof AstryxError &&
123
151
  (e.code === E.ERR_RENDER_FAILED ||
124
152
  e.code === E.ERR_RENDER_MISSING_DEPENDENCY);
125
153
 
154
+ /**
155
+ * The app a folder belongs to: the nearest folder at or above it whose
156
+ * package.json lists @astryxdesign/core (dependencies, devDependencies or
157
+ * peerDependencies), never the home folder; null when there is none.
158
+ * @param {string} cwd
159
+ * @returns {string | null}
160
+ */
161
+ export function coreApp(cwd) {
162
+ const home = homeFolder();
163
+ let dir = path.resolve(cwd);
164
+ // An installed package is never the app: resume above the outermost
165
+ // node_modules.
166
+ const nm = dir.split(path.sep).indexOf('node_modules');
167
+ if (nm > 0) dir = dir.split(path.sep).slice(0, nm).join(path.sep) || path.sep;
168
+ // A repository below the home folder is its own project: the home folder
169
+ // is the app only when the search did not come up out of another repo.
170
+ let crossedRepo = false;
171
+ for (;;) {
172
+ const listsCore = usesCore(readJson(path.join(dir, 'package.json')));
173
+ if (home && dir === home) return listsCore && !crossedRepo ? dir : null;
174
+ if (listsCore) return dir;
175
+ if (fs.existsSync(path.join(dir, '.git'))) crossedRepo = true;
176
+ const up = path.dirname(dir);
177
+ if (up === dir) return null;
178
+ dir = up;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Whether a Yarn Plug'n'Play loader (.pnp.cjs) is at the app folder or above
184
+ * it, up to its workspace root (or, outside a workspace, the repository
185
+ * root).
186
+ * @param {string} app
187
+ */
188
+ function pnpAbove(app) {
189
+ const root = findDeclaredWorkspaceRoot(app);
190
+ for (let dir = app; ; dir = path.dirname(dir)) {
191
+ if (fs.existsSync(path.join(dir, '.pnp.cjs'))) return true;
192
+ if (dir === root || (!root && fs.existsSync(path.join(dir, '.git'))))
193
+ return false;
194
+ if (path.dirname(dir) === dir) return false;
195
+ }
196
+ }
197
+
198
+ /**
199
+ * The command that installs an app's packages, in its package manager.
200
+ * @param {string} dir
201
+ */
202
+ function installAll(dir) {
203
+ const pm = detectPackageManager(dir);
204
+ return pm === 'npm' || pm === 'npx' ? 'npm install' : `${pm} install`;
205
+ }
206
+
207
+ /**
208
+ * Refuse a folder no app above lists Core for: say where Core resolves
209
+ * from (when it does) and, inside a workspace, name the folders below its
210
+ * root whose package.json lists Core, each with the `cd` to run from.
211
+ * @param {string} cwd
212
+ * @returns {never}
213
+ */
214
+ function refuseNoApp(cwd) {
215
+ const start = path.resolve(cwd);
216
+ // A repository inside a home-folder app (a submodule, a vendored clone) is
217
+ // its own project: name the app above instead of claiming there is none.
218
+ const home = homeFolder();
219
+ if (
220
+ home &&
221
+ !path.relative(home, start).startsWith('..') &&
222
+ usesCore(readJson(path.join(home, 'package.json')))
223
+ ) {
224
+ const rel = path.relative(start, home) || '.';
225
+ throw new AstryxError(
226
+ `This folder is inside its own repository, below the app at ${rel} (your home folder): the theme editor does not reach out of a repository into an app around it. Run the command from the app. Nothing was written.`,
227
+ [
228
+ {
229
+ name: `cd ${quoteCommandArgument(rel)}`,
230
+ reason: 'run the command from the app',
231
+ },
232
+ ],
233
+ E.ERR_PROJECT_REQUIRED,
234
+ );
235
+ }
236
+ // Where Core resolves from: the nearest node_modules above that holds it.
237
+ const resolved =
238
+ findNodeModulesPackage(start, '@astryxdesign/core')?.packageDir ?? null;
239
+ const root = findDeclaredWorkspaceRoot(start);
240
+ const where = resolved
241
+ ? ` @astryxdesign/core resolves from ${path.relative(start, resolved) || '.'}, but the theme editor needs the app's package.json to list it.`
242
+ : '';
243
+ if (root) {
244
+ const apps = appsBelow(root)
245
+ .map(a => path.relative(start, a) || '.')
246
+ .sort();
247
+ throw new AstryxError(
248
+ `${path.relative(start, root) || 'This folder'} is a workspace root${root === start ? '' : ` (${path.relative(root, start)} is not an app that uses @astryxdesign/core)`}, not an app: a theme belongs in an app whose package.json lists @astryxdesign/core.${where}${apps.length ? ` The workspace's apps that use it: ${apps.join(', ')}.` : ''} Run the command from the app that uses it. Nothing was written.`,
249
+ apps.slice(0, 4).map(a => ({
250
+ name: `cd ${quoteCommandArgument(a.startsWith('-') ? `./${a}` : a)}`,
251
+ reason: 'run the command from this app',
252
+ })),
253
+ E.ERR_PROJECT_REQUIRED,
254
+ );
255
+ }
256
+ if (fs.existsSync(path.join(start, 'package.json')) || resolved)
257
+ throw new AstryxError(
258
+ `${fs.existsSync(path.join(start, 'package.json')) ? '@astryxdesign/core is not installed in this app (package.json here does not use it).' : 'No package.json at or above this folder lists @astryxdesign/core.'}${where} astryx experimental theme checks every change against the installed Core: install it, or run the command from the package that uses it. Nothing was written.`,
259
+ [
260
+ {
261
+ name: installLine(start, ['@astryxdesign/core']),
262
+ reason: 'do this first',
263
+ },
264
+ ],
265
+ E.ERR_PROJECT_REQUIRED,
266
+ );
267
+ throw new AstryxError(
268
+ 'No package.json found. astryx experimental theme works inside an app project, which it writes the theme into and whose installed Core it checks every change against. Nothing was written.',
269
+ [
270
+ {
271
+ name: 'npm init -y',
272
+ reason: 'make a package.json here, then install @astryxdesign/core',
273
+ },
274
+ ],
275
+ E.ERR_PROJECT_REQUIRED,
276
+ );
277
+ }
278
+
279
+ /**
280
+ * The folders below a workspace root, up to three levels deep (node_modules
281
+ * and dot folders skipped), whose package.json lists Core.
282
+ * @param {string} root
283
+ * @returns {string[]}
284
+ */
285
+ function appsBelow(root) {
286
+ /** @type {string[]} */
287
+ const out = [];
288
+ /** @param {string} dir @param {number} depth */
289
+ const walk = (dir, depth) => {
290
+ if (depth > 6) return;
291
+ /** @type {fs.Dirent[]} */
292
+ let entries;
293
+ try {
294
+ entries = fs.readdirSync(dir, {withFileTypes: true});
295
+ } catch {
296
+ return;
297
+ }
298
+ for (const e of entries) {
299
+ if (
300
+ !e.isDirectory() ||
301
+ e.name === 'node_modules' ||
302
+ e.name.startsWith('.')
303
+ )
304
+ continue;
305
+ const sub = path.join(dir, e.name);
306
+ if (usesCore(readJson(path.join(sub, 'package.json')))) out.push(sub);
307
+ walk(sub, depth + 1);
308
+ }
309
+ };
310
+ walk(root, 1);
311
+ return out;
312
+ }
313
+
314
+ /** @param {string} file */
315
+ function readJson(file) {
316
+ try {
317
+ return JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
318
+ } catch {
319
+ return null;
320
+ }
321
+ }
322
+
323
+ /** Whether a package.json lists @astryxdesign/core itself. */
324
+ function usesCore(/** @type {any} */ json) {
325
+ if (!json || typeof json !== 'object') return false;
326
+ return ['dependencies', 'devDependencies', 'peerDependencies'].some(
327
+ k =>
328
+ json[k] != null &&
329
+ typeof json[k] === 'object' &&
330
+ !Array.isArray(json[k]) &&
331
+ Object.prototype.hasOwnProperty.call(json[k], '@astryxdesign/core'),
332
+ );
333
+ }
334
+
126
335
  /**
127
336
  * Why the components did not render, with the likely cause: two copies of
128
337
  * React (the app's and the one Core resolves) break every hook.
129
338
  * @param {import('./_project.mjs').ThemeProject} project
130
339
  * @param {string} message
131
340
  */
132
- function renderCause(project, message) {
341
+ export function renderCause(project, message) {
133
342
  /** @param {(id: string) => string} resolve */
134
343
  const reactOf = resolve => {
135
344
  try {
@@ -141,10 +350,15 @@ function renderCause(project, message) {
141
350
  const app = reactOf(project.req.resolve);
142
351
  let core = null;
143
352
  try {
144
- core = reactOf(
145
- createRequire(project.req.resolve('@astryxdesign/core/package.json'))
146
- .resolve,
147
- );
353
+ // Core's exports keep its package.json private: its folder is found by
354
+ // walking up from the entry the app resolves.
355
+ let dir = path.dirname(project.req.resolve('@astryxdesign/core'));
356
+ while (!fs.existsSync(path.join(dir, 'package.json'))) {
357
+ const up = path.dirname(dir);
358
+ if (up === dir) throw new Error('no package.json');
359
+ dir = up;
360
+ }
361
+ core = reactOf(createRequire(path.join(dir, 'package.json')).resolve);
148
362
  } catch {
149
363
  // No Core package file: nothing to compare.
150
364
  }
@@ -172,24 +386,78 @@ export async function pictures(project, shots, modes) {
172
386
  const files = [];
173
387
  /** @type {string[]} */
174
388
  const cut = [];
389
+ /** @param {string} png @param {'light' | 'dark'} m */
390
+ const outOf = (png, m) =>
391
+ modes.length > 1 && m === 'dark' ? png.replace(/\.png$/, '-dark.png') : png;
392
+ /** The theme a picture's folder is, when it is a theme folder. @param {string} out */
393
+ const themeOf = out => {
394
+ const slug = path.basename(path.dirname(out));
395
+ return path.resolve(path.dirname(out)) ===
396
+ path.resolve(themeFiles(project.cwd, slug).dir)
397
+ ? slug
398
+ : null;
399
+ };
400
+ // A picture is written only over a picture the editor took, unchanged
401
+ // since: a file of the user's by that name blocks every picture, and is
402
+ // named.
403
+ /** Pictures an older editor took, now recorded. @type {string[]} */
404
+ const adopted = [];
405
+ const blocked = shots
406
+ .flatMap(({png}) => modes.map(m => outOf(png, m)))
407
+ .filter(out => {
408
+ const slug = themeOf(out);
409
+ if (!slug || !fs.existsSync(out) || editorWrote(project.cwd, slug, out))
410
+ return false;
411
+ if (adoptOlderPicture(project.cwd, slug, out)) {
412
+ adopted.push(path.relative(project.cwd, out));
413
+ return false;
414
+ }
415
+ return true;
416
+ });
417
+ if (blocked.length)
418
+ return {
419
+ files,
420
+ problem: `${blocked.map(f => path.relative(project.cwd, f)).join(', ')} ${blocked.length === 1 ? 'is a file' : 'are files'} the editor did not write (or changed since it did), so no picture was taken and ${blocked.length === 1 ? 'it is' : 'they are'} left as ${blocked.length === 1 ? 'it is' : 'they are'}`,
421
+ };
175
422
  for (const {html, png} of shots) {
176
423
  for (const m of modes) {
177
- const out =
178
- modes.length > 1 && m === 'dark'
179
- ? png.replace(/\.png$/, '-dark.png')
180
- : png;
424
+ const out = outOf(png, m);
181
425
  const r = await screenshot(project, html, out, m);
182
426
  if (!r.ok) return {files, problem: r.reason};
183
427
  files.push(r.file);
428
+ // A picture in a theme folder is recorded as the editor's, so a later
429
+ // change removes it and never a picture of the user's.
430
+ const slug = themeOf(out);
431
+ if (slug) {
432
+ // Stamped with the editor's mark and the theme, then recorded.
433
+ try {
434
+ fs.writeFileSync(
435
+ out,
436
+ withPngText(fs.readFileSync(out), EDITOR_STAMP, slug),
437
+ );
438
+ } catch {
439
+ // An unstamped picture is still recorded below.
440
+ }
441
+ recordWritten(project.cwd, slug, [out]);
442
+ }
184
443
  if (r.cut) cut.push(r.file);
185
444
  }
186
445
  }
446
+ const adoptedNote = adopted.length
447
+ ? `${adopted.join(', ')} ${adopted.length === 1 ? 'was' : 'were'} taken by an earlier version of the editor and ${adopted.length === 1 ? 'is' : 'are'} now recorded as its own`
448
+ : null;
187
449
  return {
188
450
  files,
189
451
  // A picture of the window shows the top of a longer page only.
190
- problem: cut.length
191
- ? `${cut.join(', ')} show${cut.length === 1 ? 's' : ''} the top 2400 pixels of the page only (Chrome takes the window, not the whole page); open the .html beside ${cut.length === 1 ? 'it' : 'them'} to see all of it, or install Playwright (${installLine(project.cwd, ['playwright'])}) for whole-page pictures`
192
- : null,
452
+ problem:
453
+ [
454
+ adoptedNote,
455
+ cut.length
456
+ ? `${cut.join(', ')} show${cut.length === 1 ? 's' : ''} the top 2400 pixels of the page only (Chrome takes the window, not the whole page); open the .html beside ${cut.length === 1 ? 'it' : 'them'} to see all of it, or install Playwright (${installLine(project.cwd, ['playwright'])}) for whole-page pictures`
457
+ : null,
458
+ ]
459
+ .filter(Boolean)
460
+ .join('; ') || null,
193
461
  };
194
462
  }
195
463
 
@@ -219,6 +487,18 @@ export function fontNotes(ctx, data) {
219
487
  : `${family} is not installed, so it does not load: the previews and the app show the next font in the stack. Install it: ${installLine(ctx.project.cwd, [pkg])}. Then the preview imports it on the next set or show, and the app imports it once: import '${pkg}'; Until then, the closest font that needs no install is ${near}: ${P} set ${data.name} font ${near}`,
220
488
  );
221
489
  }
490
+ // A family the editor's own presets lead with, where the preset gets no
491
+ // note (Comic Sans MS, of comic), is no more a font to load typed by name.
492
+ const presetFamily = (/** @type {string} */ family) => {
493
+ const f = family.replace(/["']/g, '').trim().toLowerCase();
494
+ // A one-system font keeps its note, preset or not.
495
+ if (oneSystemOf(family.replace(/["']/g, '').trim())) return false;
496
+ return Object.entries(FONTS).some(
497
+ ([k, [first]]) =>
498
+ (SYSTEM_FONTS.includes(k) || k === 'comic' || k === 'rounded') &&
499
+ first.replace(/["']/g, '').trim().toLowerCase() === f,
500
+ );
501
+ };
222
502
  for (const s of data.settings) {
223
503
  if (
224
504
  s.thing !== 'font' ||
@@ -228,7 +508,8 @@ export function fontNotes(ctx, data) {
228
508
  fontOf(s.value).pkg ||
229
509
  packages.some(x => x.of === s) ||
230
510
  s.value === 'rounded' ||
231
- s.value === 'comic'
511
+ s.value === 'comic' ||
512
+ presetFamily(fontOf(s.value).family)
232
513
  )
233
514
  continue;
234
515
  const family = fontOf(s.value).family.replace(/["']/g, '').toLowerCase();
@@ -314,8 +595,17 @@ export function styledChanges(before, after) {
314
595
  `typography ${role}: ${
315
596
  x
316
597
  ? Object.entries(x)
317
- .map(([k, v]) => `${k} ${v}`)
318
- .join(', ')
598
+ .map(
599
+ ([k, v]) =>
600
+ `${k} ${
601
+ v && typeof v === 'object'
602
+ ? Object.entries(v)
603
+ .map(([a, b]) => `${a}: ${b}`)
604
+ .join(', ')
605
+ : v
606
+ }`,
607
+ )
608
+ .join('; ')
319
609
  : '(removed)'
320
610
  }`,
321
611
  );
@@ -356,7 +646,21 @@ export async function previewAfter(ctx, slug, data, png) {
356
646
  const f = themeFiles(ctx.project.cwd, slug);
357
647
  // The sheet of every component is made by show only: after a change it
358
648
  // says, at its top, that it shows the theme as it was.
359
- const sheetStale = markSheetStale(f.sheet, slug);
649
+ const sheetStale = markSheetStale(f.sheet, slug, ctx.project.cwd);
650
+ // Section sheets the editor made (they carry its stamp) go out of date the
651
+ // same way; any other file is left as it is.
652
+ const sectionsStale = (
653
+ fs.existsSync(f.dir) ? fs.readdirSync(f.dir) : []
654
+ ).filter(n => {
655
+ if (!/^sheet-[a-z-]+\.html$/.test(n)) return false;
656
+ const file = path.join(f.dir, n);
657
+ try {
658
+ if (!SHEET_STAMP.test(fs.readFileSync(file, 'utf8'))) return false;
659
+ } catch {
660
+ return false;
661
+ }
662
+ return markSheetStale(file, slug, ctx.project.cwd);
663
+ });
360
664
  const shots =
361
665
  png && preview
362
666
  ? await pictures(
@@ -370,31 +674,113 @@ export async function previewAfter(ctx, slug, data, png) {
370
674
  pictures: shots.files,
371
675
  pictureProblem: shots.problem,
372
676
  notChecked: notChecked(cause),
373
- ...(sheetStale
677
+ ...(sheetStale && !sectionsStale.length
374
678
  ? {
375
679
  sheetStale: `sheet.html shows ${slug} as it was before this change; ${P} show ${slug} makes it again`,
376
680
  }
377
- : {}),
681
+ : sectionsStale.length
682
+ ? {
683
+ sheetStale: `${[...(sheetStale ? ['sheet.html'] : []), ...sectionsStale].join(', ')} show ${slug} as it was before this change; ${[
684
+ ...(sheetStale
685
+ ? [`${P} show ${slug} makes sheet.html again`]
686
+ : []),
687
+ ...sectionsStale.map(
688
+ n =>
689
+ `${P} show ${slug} --section ${n.replace(/^sheet-|\.html$/g, '')} makes ${n} again`,
690
+ ),
691
+ ].join(', ')}`,
692
+ }
693
+ : {}),
378
694
  };
379
695
  }
380
696
 
381
697
  const STALE_MARK = '<!-- astryx: sheet older than the theme -->';
382
698
 
699
+ /** The build a full sheet was made from, recorded in the sheet. */
700
+ const SHEET_STAMP = /<!-- astryx: sheet of build ([0-9a-f]{16}) -->/;
701
+
702
+ /** @param {string} s */
703
+ const escapeForRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
704
+
705
+ /**
706
+ * A hash of a theme's built stylesheet and module, or null when either is
707
+ * missing.
708
+ * @param {string} cwd
709
+ * @param {string} slug
710
+ */
711
+ function buildHash(cwd, slug) {
712
+ const f = themeFiles(cwd, slug);
713
+ try {
714
+ return createHash('sha256')
715
+ .update(fs.readFileSync(f.css))
716
+ .update('\0')
717
+ .update(fs.readFileSync(f.js))
718
+ .digest('hex')
719
+ .slice(0, 16);
720
+ } catch {
721
+ return null;
722
+ }
723
+ }
724
+
725
+ /**
726
+ * Record in a freshly made full sheet the build it shows.
727
+ * @param {string} file
728
+ * @param {string} slug
729
+ * @param {string} cwd
730
+ */
731
+ export function stampSheet(file, slug, cwd) {
732
+ const hash = buildHash(cwd, slug);
733
+ if (!hash) return;
734
+ try {
735
+ const html = fs.readFileSync(file, 'utf8').replace(SHEET_STAMP, '');
736
+ // At the end: a comment before the doctype would put the page in
737
+ // quirks mode.
738
+ writeWhole(
739
+ file,
740
+ `${html.trimEnd()}\n<!-- astryx: sheet of build ${hash} -->\n`,
741
+ );
742
+ } catch (e) {
743
+ if (/** @type {any} */ (e)?.lockLost) throw e;
744
+ }
745
+ }
746
+
383
747
  /**
384
748
  * Put a notice at the top of a sheet the last change made out of date
385
- * (once). Returns whether there is such a sheet.
749
+ * (once), or take it off a sheet made from the build there is now.
750
+ * Returns whether the sheet is out of date.
386
751
  * @param {string} file
387
752
  * @param {string} slug
753
+ * @param {string} cwd
388
754
  */
389
- function markSheetStale(file, slug) {
755
+ function markSheetStale(file, slug, cwd) {
390
756
  let html;
391
757
  try {
392
758
  html = fs.readFileSync(file, 'utf8');
393
759
  } catch {
394
760
  return false;
395
761
  }
762
+ // A sheet made from the build there is now (a change, then its undo)
763
+ // shows the theme as it is: no banner, and the result says nothing.
764
+ const made = SHEET_STAMP.exec(html)?.[1];
765
+ if (made && made === buildHash(cwd, slug)) {
766
+ if (html.includes(STALE_MARK)) {
767
+ const clean = html.replace(
768
+ new RegExp(`${escapeForRegExp(STALE_MARK)}<div[^>]*>[\\s\\S]*?</div>`),
769
+ '',
770
+ );
771
+ try {
772
+ writeWhole(file, clean);
773
+ } catch (e) {
774
+ if (/** @type {any} */ (e)?.lockLost) throw e;
775
+ }
776
+ }
777
+ return false;
778
+ }
396
779
  if (html.includes(STALE_MARK)) return true;
397
- const banner = `${STALE_MARK}<div style="position:sticky;top:0;z-index:9999;padding:8px 12px;background:#fff3cd;color:#3d2c00;font:14px system-ui,sans-serif;border-bottom:1px solid #e0c870">This sheet shows ${slug} as it was before the last change. Run ${P} show ${slug} to make it again.</div>`;
780
+ // A section's sheet is made again by its own show.
781
+ const section = /^sheet-([a-z-]+)\.html$/.exec(path.basename(file))?.[1];
782
+ const again = `${P} show ${slug}${section ? ` --section ${section}` : ''}`;
783
+ const banner = `${STALE_MARK}<div style="position:sticky;top:0;z-index:9999;padding:8px 12px;background:#fff3cd;color:#3d2c00;font:14px system-ui,sans-serif;border-bottom:1px solid #e0c870">This sheet shows ${slug} as it was before the last change. Run ${again} to make it again.</div>`;
398
784
  const at = html.search(/<body[^>]*>/i);
399
785
  const next =
400
786
  at < 0 ? banner + html : html.replace(/<body[^>]*>/i, m => `${m}${banner}`);