@astryxdesign/cli 0.7.15-canary.g79b95eb → 0.7.15-canary.gbe99721

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 (135) 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 +2 -1
  11. package/api/doctor/_adapter.mjs +6 -1
  12. package/api/doctor/doctor.mjs +2 -2
  13. package/api/doctor/theme-checks.mjs +56 -21
  14. package/api/integration/add-helpers.mjs +5 -0
  15. package/api/integration/add-theme.mjs +15 -110
  16. package/api/integration/validate-integration.mjs +17 -3
  17. package/api/integration/validateIntegration.doc.mjs +1 -1
  18. package/api/theme/_adapter.d.mts +37 -5
  19. package/api/theme/_adapter.mjs +363 -50
  20. package/api/theme/_fork.d.mts +90 -0
  21. package/api/theme/_fork.mjs +246 -0
  22. package/api/theme/build/build.d.mts +25 -1
  23. package/api/theme/build/build.mjs +352 -41
  24. package/api/theme/eject/eject.mjs +36 -15
  25. package/api/theme/list/list.mjs +3 -6
  26. package/api/theme/palette/generate/generator.d.mts +13 -0
  27. package/api/theme/palette/generate/generator.mjs +32 -2
  28. package/api/theme/targets/targets.mjs +10 -3
  29. package/api/theme/template/template.mjs +48 -2
  30. package/api/theme/theme.type.d.mts +8 -0
  31. package/api/theme/theme.type.mjs +5 -1
  32. package/api/theme/themeBuild.doc.mjs +2 -2
  33. package/api/theme/themeRemove.doc.mjs +5 -2
  34. package/api/theme/themeTemplate.doc.mjs +2 -2
  35. package/api/theme/themeUse.doc.mjs +8 -2
  36. package/api/theme-edit/_adapter.mjs +157 -36
  37. package/api/theme-edit/_catalog.d.mts +1 -6
  38. package/api/theme-edit/_catalog.mjs +5 -268
  39. package/api/theme-edit/_check.d.mts +3 -1
  40. package/api/theme-edit/_check.mjs +733 -308
  41. package/api/theme-edit/_color.d.mts +19 -0
  42. package/api/theme-edit/_color.mjs +277 -33
  43. package/api/theme-edit/_compiler.d.mts +1 -0
  44. package/api/theme-edit/_compiler.mjs +25 -0
  45. package/api/theme-edit/_context.d.mts +2 -0
  46. package/api/theme-edit/_context.mjs +83 -9
  47. package/api/theme-edit/_css.d.mts +84 -0
  48. package/api/theme-edit/_css.mjs +700 -0
  49. package/api/theme-edit/_edit.mjs +370 -85
  50. package/api/theme-edit/_how-commands.d.mts +5 -0
  51. package/api/theme-edit/_how-commands.mjs +20 -13
  52. package/api/theme-edit/_how-question.d.mts +29 -0
  53. package/api/theme-edit/_how-question.mjs +1573 -182
  54. package/api/theme-edit/_how.mjs +306 -22
  55. package/api/theme-edit/_overview.mjs +2 -7
  56. package/api/theme-edit/_palette.d.mts +27 -5
  57. package/api/theme-edit/_palette.mjs +231 -97
  58. package/api/theme-edit/_parts.d.mts +42 -10
  59. package/api/theme-edit/_parts.mjs +224 -69
  60. package/api/theme-edit/_preview-app.d.mts +8 -0
  61. package/api/theme-edit/_preview-app.mjs +549 -96
  62. package/api/theme-edit/_preview.d.mts +7 -16
  63. package/api/theme-edit/_preview.mjs +77 -84
  64. package/api/theme-edit/_project.d.mts +20 -1
  65. package/api/theme-edit/_project.mjs +43 -13
  66. package/api/theme-edit/_settings.d.mts +96 -20
  67. package/api/theme-edit/_settings.mjs +646 -141
  68. package/api/theme-edit/_tables.d.mts +18 -12
  69. package/api/theme-edit/_tables.mjs +144 -147
  70. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  71. package/api/theme-edit/theme-edit.type.mjs +3 -1
  72. package/api/theme-edit/themeEditNew.doc.mjs +1 -1
  73. package/api/theme-edit/themeEditPreviewAdd.doc.mjs +1 -1
  74. package/api/theme-edit/themeEditPreviewApp.doc.mjs +1 -1
  75. package/api/theme-edit/themeEditPreviewList.doc.mjs +2 -2
  76. package/api/theme-edit/themeEditSet.doc.mjs +1 -1
  77. package/api/theme-edit/themeEditUndo.doc.mjs +1 -1
  78. package/assets/docs/tree/checks.doc.mjs +22 -1
  79. package/assets/docs/tree/publishing.doc.mjs +1 -0
  80. package/assets/docs.generated.json +2 -2
  81. package/assets/self-audit.generated.json +1 -1
  82. package/authoring/integration/integration.doc.mjs +8 -0
  83. package/authoring/integration/schema.d.mts +8 -0
  84. package/authoring/integration/schema.mjs +1 -0
  85. package/authoring/integration/type.ts +9 -0
  86. package/clients/cli/build-id.generated.json +1 -1
  87. package/clients/cli/commands/experimental/index.mjs +10 -10
  88. package/clients/cli/commands/experimental/theme.mjs +22 -3
  89. package/clients/cli/commands/experimental-theme-compile.doc.mjs +2 -2
  90. package/clients/cli/commands/experimental-theme-editor-new.doc.mjs +3 -3
  91. package/clients/cli/commands/experimental-theme-preview-add.doc.mjs +1 -1
  92. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  93. package/clients/cli/commands/integration.mjs +8 -0
  94. package/clients/cli/commands/theme-build.doc.mjs +2 -2
  95. package/clients/cli/commands/theme-list.doc.mjs +1 -1
  96. package/clients/cli/commands/theme-template.doc.mjs +1 -1
  97. package/clients/cli/commands/theme.mjs +325 -48
  98. package/clients/cli/index.mjs +18 -3
  99. package/clients/cli/lib/cli-error.mjs +118 -3
  100. package/clients/cli/manifest.generated.json +1 -1
  101. package/foundation/config/project.mjs +34 -8
  102. package/foundation/config/theme-state.d.mts +16 -0
  103. package/foundation/config/theme-state.mjs +84 -13
  104. package/foundation/discovery/template-needs.d.mts +13 -0
  105. package/foundation/discovery/template-needs.mjs +30 -15
  106. package/foundation/discovery/theme-discovery.mjs +14 -2
  107. package/foundation/discovery/theme-imports.d.mts +16 -0
  108. package/foundation/discovery/theme-imports.mjs +30 -2
  109. package/foundation/doc-compiler/import.mjs +10 -4
  110. package/foundation/fs/gather-cache.mjs +93 -26
  111. package/foundation/fs/jiti-cache.d.mts +21 -0
  112. package/foundation/fs/jiti-cache.mjs +66 -0
  113. package/foundation/fs/module-loader.mjs +7 -2
  114. package/foundation/fs/read-record.mjs +8 -2
  115. package/foundation/integrations/autolink.d.mts +1 -24
  116. package/foundation/integrations/autolink.mjs +7 -60
  117. package/foundation/integrations/declared-dependencies.d.mts +27 -0
  118. package/foundation/integrations/declared-dependencies.mjs +73 -0
  119. package/foundation/integrations/integrations.d.mts +8 -0
  120. package/foundation/integrations/integrations.mjs +4 -0
  121. package/foundation/integrations/may-have-integrations.d.mts +8 -0
  122. package/foundation/integrations/may-have-integrations.mjs +47 -0
  123. package/foundation/integrations/validate-contributions.d.mts +62 -1
  124. package/foundation/integrations/validate-contributions.mjs +452 -29
  125. package/foundation/release/cache.d.mts +21 -2
  126. package/foundation/release/cache.mjs +48 -8
  127. package/foundation/release/folder-lock.d.mts +7 -0
  128. package/foundation/release/folder-lock.mjs +60 -26
  129. package/foundation/release/lock-lease.d.mts +2 -1
  130. package/foundation/release/lock-lease.mjs +7 -2
  131. package/foundation/response/error-codes.doc.mjs +1 -1
  132. package/foundation/response/response-types.doc.mjs +5 -5
  133. package/package.json +6 -6
  134. package/api/theme-edit/_css-properties.d.mts +0 -10
  135. package/api/theme-edit/_css-properties.mjs +0 -556
@@ -10,7 +10,6 @@
10
10
  * @position api/theme-edit — imported only by _adapter.mjs
11
11
  */
12
12
 
13
- import {createHash} from 'node:crypto';
14
13
  import {parse as parseModule} from '@babel/parser';
15
14
  import * as fs from 'node:fs';
16
15
  import * as path from 'node:path';
@@ -22,6 +21,7 @@ import {
22
21
  PathSafetyError,
23
22
  } from '../../foundation/fs/path-safety.mjs';
24
23
  import {baseResolved, installLine, openProject} from './_project.mjs';
24
+ import {P} from './_tables.mjs';
25
25
  import {
26
26
  buildTheme,
27
27
  editedThemes,
@@ -33,6 +33,7 @@ import {
33
33
  shown,
34
34
  staleBuild,
35
35
  themeFiles,
36
+ windowsReserved,
36
37
  } from './_settings.mjs';
37
38
  import {
38
39
  colorsPageSource,
@@ -42,10 +43,12 @@ import {
42
43
  themeImports,
43
44
  } from './_preview.mjs';
44
45
  import {
46
+ PALETTE_STAND_IN,
45
47
  paletteFiles,
46
48
  paletteMapping,
47
49
  tempFor,
48
50
  writeWhole,
51
+ refuseIfLockLost,
49
52
  } from './_palette.mjs';
50
53
  import {build} from '../build/build.mjs';
51
54
  import {search} from '../search/search.mjs';
@@ -58,6 +61,8 @@ import {detectStylingSystem} from '../../foundation/agent-docs/agent-docs.mjs';
58
61
  import {requireProject, context} from './_context.mjs';
59
62
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
60
63
  import {quoteCommandArgument} from '../../foundation/env/package-manager.mjs';
64
+ import {sha256} from '../../foundation/render/source-block.mjs';
65
+ import {findNodeModulesPackage} from '../../foundation/fs/paths.mjs';
61
66
 
62
67
  const E = ERROR_CODES;
63
68
 
@@ -129,11 +134,255 @@ function checkFolderName(where, what, retry) {
129
134
  );
130
135
  }
131
136
 
137
+ /**
138
+ * A note when the app never imports Core's stylesheet, or null: without
139
+ * it, components render unstyled, and some show nothing. Read from the
140
+ * files of the routes folder and src/ (best effort).
141
+ * @param {string} cwd
142
+ * @param {{dir: string, app: string | null}} at
143
+ * @returns {string | null}
144
+ */
145
+ function coreStylesheetMissing(cwd, at) {
146
+ if (!at.app) return null;
147
+ const SHEET = /@astryxdesign\/core\/astryx\.css/;
148
+ let seen = 0;
149
+ /** @param {string} folder @returns {boolean} */
150
+ const imports = folder => {
151
+ /** @type {fs.Dirent[]} */
152
+ let entries;
153
+ try {
154
+ entries = fs.readdirSync(folder, {withFileTypes: true});
155
+ } catch {
156
+ return false;
157
+ }
158
+ for (const e of entries) {
159
+ const full = path.join(folder, e.name);
160
+ if (e.isDirectory()) {
161
+ if (
162
+ e.name === 'node_modules' ||
163
+ e.name.startsWith('.') ||
164
+ full === at.dir
165
+ )
166
+ continue;
167
+ if (imports(full)) return true;
168
+ } else if (
169
+ /\.(tsx|ts|jsx|js|mjs|css|scss)$/.test(e.name) &&
170
+ ++seen < 2000
171
+ )
172
+ try {
173
+ if (SHEET.test(fs.readFileSync(full, 'utf8'))) return true;
174
+ } catch {
175
+ // Unreadable: skip it.
176
+ }
177
+ }
178
+ return false;
179
+ };
180
+ const src = path.join(cwd, 'src');
181
+ if (
182
+ imports(at.app) ||
183
+ (at.app.startsWith(src + path.sep) ? false : imports(src))
184
+ )
185
+ return null;
186
+ const layout = ['tsx', 'ts', 'jsx', 'js']
187
+ .map(x => path.join(at.app ?? '', `layout.${x}`))
188
+ .find(f => fs.existsSync(f));
189
+ return `the app does not import Core's stylesheet, so the preview's components render unstyled and some show nothing; add import '@astryxdesign/core/astryx.css'; to ${layout ? shown(cwd, layout) : "the app's root layout"}`;
190
+ }
191
+
192
+ /**
193
+ * What next.config sets, read from its syntax tree: `pageExtensions`,
194
+ * `basePath` and `distDir`, each a literal value, `undefined` when it is
195
+ * not set, or `null` when it is set in a way only running the config tells
196
+ * (a spread, a function config, a value from code). Comments say nothing.
197
+ * @param {string} cwd
198
+ * @returns {{file: string | null, pageExtensions: string[] | null | undefined, basePath: string | null | undefined, distDir: string | null | undefined}}
199
+ */
200
+ function readNextConfig(cwd) {
201
+ const none = {
202
+ file: null,
203
+ pageExtensions: undefined,
204
+ basePath: undefined,
205
+ distDir: undefined,
206
+ };
207
+ for (const name of [
208
+ 'next.config.mjs',
209
+ 'next.config.js',
210
+ 'next.config.ts',
211
+ 'next.config.cjs',
212
+ ]) {
213
+ /** @type {string} */
214
+ let text;
215
+ try {
216
+ text = fs.readFileSync(path.join(cwd, name), 'utf8');
217
+ } catch {
218
+ continue;
219
+ }
220
+ const unknown = {
221
+ file: name,
222
+ pageExtensions: null,
223
+ basePath: null,
224
+ distDir: null,
225
+ };
226
+ /** @type {any} */
227
+ let file;
228
+ try {
229
+ file = parseModule(text, {
230
+ sourceType: 'unambiguous',
231
+ plugins: ['typescript'],
232
+ errorRecovery: true,
233
+ });
234
+ } catch {
235
+ return unknown;
236
+ }
237
+ const body = /** @type {any[]} */ (file.program.body);
238
+ /** Top-level constants, by name. @type {Map<string, any>} */
239
+ const consts = new Map();
240
+ for (const st of body)
241
+ if (st.type === 'VariableDeclaration' && st.kind === 'const')
242
+ for (const d of st.declarations)
243
+ if (d.id?.type === 'Identifier' && d.init)
244
+ consts.set(d.id.name, d.init);
245
+ /** @param {any} n @param {number} depth @returns {any} */
246
+ const resolve = (n, depth = 0) => {
247
+ while (
248
+ n &&
249
+ /^TS(As|Satisfies|NonNull)Expression$|^ParenthesizedExpression$/.test(
250
+ n.type,
251
+ )
252
+ )
253
+ n = n.expression;
254
+ if (n?.type === 'Identifier' && depth < 4 && consts.has(n.name))
255
+ return resolve(consts.get(n.name), depth + 1);
256
+ return n;
257
+ };
258
+ /** The config object: exported, or passed to a wrapper such as withX(config). @param {any} n @returns {any} */
259
+ const configOf = n => {
260
+ n = resolve(n);
261
+ if (n?.type === 'ObjectExpression') return n;
262
+ if (n?.type === 'CallExpression')
263
+ for (const a of n.arguments) {
264
+ const o = configOf(a);
265
+ if (o) return o;
266
+ }
267
+ return null;
268
+ };
269
+ /** @type {any} */
270
+ let exported = null;
271
+ for (const st of body) {
272
+ if (st.type === 'ExportDefaultDeclaration') exported = st.declaration;
273
+ if (
274
+ st.type === 'ExpressionStatement' &&
275
+ st.expression.type === 'AssignmentExpression' &&
276
+ st.expression.left.type === 'MemberExpression' &&
277
+ st.expression.left.object?.name === 'module' &&
278
+ st.expression.left.property?.name === 'exports'
279
+ )
280
+ exported = st.expression.right;
281
+ }
282
+ const config = exported && configOf(exported);
283
+ if (!config) return exported ? unknown : none;
284
+ // The config's keys in order, with a spread of a constant object read
285
+ // in place; a spread of anything else may set any key (`null`).
286
+ /** @type {Array<{key: string, value: any} | null>} */
287
+ const entries = [];
288
+ /** @param {any} obj @param {number} depth */
289
+ const flatten = (obj, depth) => {
290
+ for (const x of obj.properties) {
291
+ if (x.type === 'SpreadElement') {
292
+ const inner = resolve(x.argument);
293
+ if (inner?.type === 'ObjectExpression' && depth < 4)
294
+ flatten(inner, depth + 1);
295
+ else entries.push(null);
296
+ } else if (
297
+ (x.type === 'ObjectProperty' || x.type === 'ObjectMethod') &&
298
+ !x.computed
299
+ )
300
+ entries.push({key: x.key.name ?? x.key.value, value: x.value});
301
+ else entries.push(null);
302
+ }
303
+ };
304
+ flatten(config, 0);
305
+ /** The entry that sets a key last; null when an unreadable spread may; undefined when nothing does. @param {string} key */
306
+ const prop = key => {
307
+ for (let i = entries.length - 1; i >= 0; i--) {
308
+ const e = entries[i];
309
+ if (e === null) return null;
310
+ if (e.key === key) return e;
311
+ }
312
+ return undefined;
313
+ };
314
+ /** @param {any} n @returns {string | null} */
315
+ const str = n => {
316
+ n = resolve(n);
317
+ if (n?.type === 'StringLiteral') return n.value;
318
+ if (n?.type === 'TemplateLiteral' && !n.expressions.length)
319
+ return n.quasis[0].value.cooked;
320
+ return null;
321
+ };
322
+ /** @param {string} key @param {(n: any) => any} read */
323
+ const value = (key, read) => {
324
+ const p = prop(key);
325
+ return p ? read(p.value) : p;
326
+ };
327
+ return {
328
+ file: name,
329
+ pageExtensions: value('pageExtensions', n => {
330
+ n = resolve(n);
331
+ if (n?.type !== 'ArrayExpression') return null;
332
+ const out = n.elements.map((/** @type {any} */ e) => str(e));
333
+ return out.every((/** @type {any} */ e) => e != null) ? out : null;
334
+ }),
335
+ basePath: value('basePath', n => {
336
+ const v = str(n);
337
+ return v == null ? null : v.replace(/\/+$/, '');
338
+ }),
339
+ distDir: value('distDir', n => {
340
+ const v = str(n);
341
+ return v == null
342
+ ? null
343
+ : (v.replace(/^\.?\//, '').split('/')[0] ?? null);
344
+ }),
345
+ };
346
+ }
347
+ return none;
348
+ }
349
+
350
+ /**
351
+ * The `basePath` next.config sets: '' when it sets none, null when only
352
+ * running the config tells. Every URL of the app starts with it.
353
+ * @param {string} cwd
354
+ * @returns {string | null}
355
+ */
356
+ function nextBasePath(cwd) {
357
+ const v = readNextConfig(cwd).basePath;
358
+ return v === undefined ? '' : v;
359
+ }
360
+
361
+ /**
362
+ * Notes on next.config values the preview depends on that only running
363
+ * the config tells: the page extensions (the route is page.tsx) and the
364
+ * base path of its URL.
365
+ * @param {string} cwd
366
+ * @returns {string[]}
367
+ */
368
+ function nextConfigNotes(cwd) {
369
+ const c = readNextConfig(cwd);
370
+ /** @type {string[]} */
371
+ const notes = [];
372
+ if (c.pageExtensions === null)
373
+ notes.push(
374
+ `${c.file} sets pageExtensions in a way only running it tells; the preview's route is page.tsx, so "tsx" must be in it`,
375
+ );
376
+ return notes;
377
+ }
378
+
132
379
  /**
133
380
  * Why a folder is no place for files this command writes, or null: themes
134
381
  * live in themes/ (and a preview app's whole tree would ship with the
135
- * theme), packages in node_modules/, and Next serves every file under a
136
- * Pages Router folder (`pages/` or `src/pages/`) as a page.
382
+ * theme), packages in node_modules/, Next empties its build folder
383
+ * (`.next/`, `out/` or the `distDir` next.config names) on every build,
384
+ * and Next serves every file under a Pages Router folder (`pages/` or
385
+ * `src/pages/`) as a page.
137
386
  * @param {string} cwd
138
387
  * @param {string} dir
139
388
  */
@@ -145,10 +394,12 @@ function reservedFolder(cwd, dir) {
145
394
  return 'node_modules/ belongs to the package manager, which replaces it';
146
395
  if (segs[0] === 'public')
147
396
  return 'Next serves every file in public/ as it is, at the site root, so anyone could download it';
148
- const odd = segs.find(
149
- seg =>
150
- /^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(seg) || /^\.+$/.test(seg),
151
- );
397
+ const built = [
398
+ ...new Set(['.next', 'out', readNextConfig(cwd).distDir]),
399
+ ].find(d => d && segs[0] === d);
400
+ if (built)
401
+ return `${built}/ is where Next writes its build, and the next build empties it`;
402
+ const odd = segs.find(seg => windowsReserved(seg) || /^\.+$/.test(seg));
152
403
  if (odd)
153
404
  return `${odd} is a name Windows does not allow for a folder, so the project could not be checked out there`;
154
405
  if (segs[0] === 'pages' || (segs[0] === 'src' && segs[1] === 'pages'))
@@ -185,35 +436,16 @@ const urlSegments = (app, dir) =>
185
436
  .split(path.sep)
186
437
  .filter(seg => seg && !/^\(.*\)$/.test(seg));
187
438
 
188
- /**
189
- * The `pageExtensions` next.config sets, read as text (best effort), or
190
- * null when it sets none.
191
- * @param {string} cwd
192
- * @returns {string[] | null}
193
- */
194
- function pageExtensions(cwd) {
195
- for (const name of [
196
- 'next.config.mjs',
197
- 'next.config.js',
198
- 'next.config.ts',
199
- 'next.config.cjs',
200
- ]) {
201
- /** @type {string} */
202
- let text;
203
- try {
204
- text = fs.readFileSync(path.join(cwd, name), 'utf8');
205
- } catch {
206
- continue;
207
- }
208
- const m = /pageExtensions\s*:\s*\[([^\]]*)\]/.exec(text);
209
- return m ? [...m[1].matchAll(/['"`]([^'"`]+)['"`]/g)].map(x => x[1]) : null;
210
- }
211
- return null;
212
- }
439
+ /** An optional catch-all route folder, `[[...slug]]`: it also serves its parent folder's URL (a required `[...slug]` does not). */
440
+ const CATCH_ALL = /^\[\[\.\.\.[^\]]+\]\]$/;
441
+
442
+ /** A file Next serves a URL from: a page or a route handler. */
443
+ const ROUTE_FILE = /^(page\.(tsx|ts|jsx|js|mdx)|route\.(tsx|ts|jsx|js))$/;
213
444
 
214
445
  /**
215
- * A page of the app that Next serves at the same URL as `dir`, which would
216
- * stop the whole app from building, or null.
446
+ * A page or route handler of the app that Next serves at the same URL as
447
+ * `dir`, or null: beside the preview, Next refuses to build (a route and a
448
+ * page), or the preview takes that URL from it.
217
449
  * @param {string} cwd
218
450
  * @param {string} app the routes folder
219
451
  * @param {string} dir
@@ -236,15 +468,32 @@ function sameUrlPage(cwd, app, dir) {
236
468
  continue;
237
469
  const hit = walk(full);
238
470
  if (hit) return hit;
239
- } else if (
240
- folder !== dir &&
241
- /^page\.(tsx|ts|jsx|js|mdx)$/.test(e.name) &&
242
- urlSegments(app, folder).join('/') === url
243
- )
244
- return full;
471
+ } else if (ROUTE_FILE.test(e.name) && servesUrl(folder)) return full;
245
472
  }
246
473
  return null;
247
474
  };
475
+ /** A folder served at the URL, or at the URLs under it through a catch-all. @param {string} folder */
476
+ const servesUrl = folder => {
477
+ const segs = urlSegments(app, folder);
478
+ return (
479
+ segs.join('/') === url ||
480
+ (CATCH_ALL.test(segs.at(-1) ?? '') && segs.slice(0, -1).join('/') === url)
481
+ );
482
+ };
483
+ // The preview's own folder: a route handler, a page other than the
484
+ // page.tsx the preview writes, or a catch-all route in it.
485
+ try {
486
+ for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
487
+ if (!e.isDirectory()) {
488
+ if (ROUTE_FILE.test(e.name) && e.name !== 'page.tsx')
489
+ return path.join(dir, e.name);
490
+ } else if (CATCH_ALL.test(e.name))
491
+ for (const name of fs.readdirSync(path.join(dir, e.name)))
492
+ if (ROUTE_FILE.test(name)) return path.join(dir, e.name, name);
493
+ }
494
+ } catch {
495
+ // No folder yet.
496
+ }
248
497
  const inApp = walk(app);
249
498
  if (inApp) return inApp;
250
499
  for (const pages of [path.join(cwd, 'pages'), path.join(cwd, 'src', 'pages')])
@@ -268,15 +517,21 @@ function sameUrlPage(cwd, app, dir) {
268
517
  function nestedRootLayouts(app) {
269
518
  const LAYOUT = /^layout\.(tsx|ts|jsx|js)$/;
270
519
  if (fs.readdirSync(app).some(f => LAYOUT.test(f))) return [];
271
- return fs
272
- .readdirSync(app, {withFileTypes: true})
273
- .filter(
274
- e =>
275
- e.isDirectory() &&
276
- fs.readdirSync(path.join(app, e.name)).some(f => LAYOUT.test(f)),
277
- )
278
- .map(e => path.join(app, e.name))
279
- .sort();
520
+ /** @type {string[]} */
521
+ const out = [];
522
+ /** A folder with a layout counts; a route group without one is looked into. @param {string} dir @param {boolean} top */
523
+ const look = (dir, top) => {
524
+ for (const e of fs.readdirSync(dir, {withFileTypes: true})) {
525
+ if (!e.isDirectory()) continue;
526
+ const sub = path.join(dir, e.name);
527
+ const group = /^\(.+\)$/.test(e.name);
528
+ if (!top && !group) continue;
529
+ if (fs.readdirSync(sub).some(f => LAYOUT.test(f))) out.push(sub);
530
+ else if (group) look(sub, false);
531
+ }
532
+ };
533
+ look(app, true);
534
+ return out.sort();
280
535
  }
281
536
 
282
537
  /**
@@ -373,13 +628,42 @@ function checkPlacement(cwd, dir, where, retry) {
373
628
  : [fallback],
374
629
  },
375
630
  );
376
- const exts = pageExtensions(cwd);
377
- if (exts && !exts.includes('tsx'))
631
+ const exts = readNextConfig(cwd).pageExtensions;
632
+ if (exts && !exts.includes('tsx')) {
633
+ let free = 'theme-app';
634
+ for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
635
+ free = `theme-app-${n}`;
378
636
  refuse(
379
637
  E.ERR_INVALID_ARGUMENT,
380
638
  `next.config sets pageExtensions to ${exts.join(', ')}, so Next does not serve page.tsx, the route file the preview writes.`,
381
- {fix: 'add "tsx" to pageExtensions to use the preview in this app'},
639
+ {
640
+ fix: 'add "tsx" to pageExtensions to use the preview in this app',
641
+ run: [
642
+ `${retry(shown(cwd, dir))} # once "tsx" is in pageExtensions`,
643
+ `${PREVIEW} app ${free} # or a new app of its own, with the preview`,
644
+ ],
645
+ },
646
+ );
647
+ }
648
+ if (
649
+ served &&
650
+ !rootLayouts.length &&
651
+ !fs.readdirSync(served).some(f => /^layout\.(tsx|ts|jsx|js)$/.test(f))
652
+ ) {
653
+ let free = 'theme-app';
654
+ for (let n = 2; fs.existsSync(path.join(cwd, free)); n++)
655
+ free = `theme-app-${n}`;
656
+ refuse(
657
+ E.ERR_INVALID_ARGUMENT,
658
+ `${shown(cwd, served)}/ has no root layout (no layout.tsx in it or in a route group), so Next cannot build a page in ${where}.`,
659
+ {
660
+ fix: `add a root layout to ${shown(cwd, served)}/ to use the preview in this app`,
661
+ run: [
662
+ `${PREVIEW} app ${free} # a new app with its own root layout and the preview`,
663
+ ],
664
+ },
382
665
  );
666
+ }
383
667
  if (rootLayouts.length && !rootLayout)
384
668
  refuse(
385
669
  E.ERR_INVALID_ARGUMENT,
@@ -396,7 +680,7 @@ function checkPlacement(cwd, dir, where, retry) {
396
680
  for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
397
681
  refuse(
398
682
  E.ERR_FILE_EXISTS,
399
- `${shown(cwd, clash)} already serves /${urlSegments(app, dir).join('/')}, so a preview in ${where} would stop the app from building.`,
683
+ `${shown(cwd, clash)} already serves /${urlSegments(app, dir).join('/')} or the URLs under it, so a preview in ${where} would stop the app from building, or take that URL from it.`,
400
684
  {run: [retry(shown(cwd, free))]},
401
685
  );
402
686
  }
@@ -455,6 +739,7 @@ function previewDir(cwd, where, opts = {}) {
455
739
  ...new Set(editedThemes(cwd).flatMap(t => recordedPreviews(cwd, t))),
456
740
  ].filter(d => fs.existsSync(path.join(d, PREVIEW_DATA)));
457
741
  if (recorded.length === 1) {
742
+ inProjectOrRefuse(cwd, recorded[0], retry);
458
743
  if (opts.write)
459
744
  checkPlacement(cwd, recorded[0], shownDir(cwd, recorded[0]), retry);
460
745
  return {dir: recorded[0], app: appOf(recorded[0])};
@@ -492,10 +777,45 @@ function previewDir(cwd, where, opts = {}) {
492
777
  ],
493
778
  },
494
779
  );
780
+ inProjectOrRefuse(cwd, dir, retry);
495
781
  if (opts.write) checkPlacement(cwd, dir, `${shownDir(cwd, dir)}/`, retry);
496
782
  return {dir, app: appOf(dir)};
497
783
  }
498
784
 
785
+ /**
786
+ * Refuse a preview folder that reaches outside the project through a link,
787
+ * as `--path` refuses one: every file the preview writes would land there.
788
+ * @param {string} cwd
789
+ * @param {string} dir
790
+ * @param {Retry} retry
791
+ */
792
+ function inProjectOrRefuse(cwd, dir, retry) {
793
+ /** @param {string} d */
794
+ const within = d => {
795
+ try {
796
+ assertWithin(d, cwd, {allowAbsolute: true, label: 'the preview folder'});
797
+ return true;
798
+ } catch (e) {
799
+ if (e instanceof PathSafetyError) return false;
800
+ throw e;
801
+ }
802
+ };
803
+ if (within(dir)) return;
804
+ let free = `${dir}-2`;
805
+ for (let n = 3; fs.existsSync(free); n++) free = `${dir}-${n}`;
806
+ refuse(
807
+ E.ERR_PATH_TRAVERSAL,
808
+ `${shownDir(cwd, dir)}/ leads outside the project through a link; the preview stays inside the folder you run the command from.`,
809
+ {
810
+ run: [
811
+ within(path.dirname(dir))
812
+ ? retry(shown(cwd, free))
813
+ : `${PREVIEW} app theme-app # a new app of its own, inside this folder`,
814
+ ],
815
+ },
816
+ );
817
+ }
818
+
499
819
  const CLI_PACKAGE = path.resolve(
500
820
  path.dirname(fileURLToPath(import.meta.url)),
501
821
  '../..',
@@ -514,18 +834,26 @@ function confined(file, root, what) {
514
834
  return assertWithin(file, root, {allowAbsolute: true, label: what});
515
835
  } catch (e) {
516
836
  if (e instanceof PathSafetyError) {
517
- /** @type {string | null} */
837
+ // The link that leads out: the file itself, or a folder on its way.
838
+ /** @type {{at: string, to: string} | null} */
518
839
  let link = null;
519
- try {
520
- if (fs.lstatSync(file).isSymbolicLink()) link = fs.readlinkSync(file);
521
- } catch {
522
- // Not there: the path itself leads out.
523
- }
840
+ for (
841
+ let at = file;
842
+ at.startsWith(root + path.sep) && !link;
843
+ at = path.dirname(at)
844
+ )
845
+ try {
846
+ if (fs.lstatSync(at).isSymbolicLink())
847
+ link = {at, to: fs.readlinkSync(at)};
848
+ } catch {
849
+ // Not there: look at its folder.
850
+ }
524
851
  refuse(
525
852
  E.ERR_PATH_TRAVERSAL,
526
853
  link == null
527
- ? `${what} ${file} is outside ${root}.`
528
- : `${what} ${file}, which is a link to ${link}, outside ${root}.`,
854
+ ? `${what} names ${file}, which is outside ${root}.`
855
+ : `${link.at} is a link to ${link.to}, outside ${root}; the preview never writes through a link.`,
856
+ {run: [`${PREVIEW} list`]},
529
857
  );
530
858
  }
531
859
  throw e;
@@ -925,8 +1253,7 @@ function readPreview(cwd, dir, pf = '') {
925
1253
  }
926
1254
 
927
1255
  /** A short hash of a file's text. @param {string | Buffer} text */
928
- const digest = text =>
929
- createHash('sha256').update(text).digest('hex').slice(0, 16);
1256
+ const digest = text => sha256(Buffer.from(text)).slice(0, 16);
930
1257
 
931
1258
  /**
932
1259
  * A file's text as a formatter could have left it: white space outside
@@ -1278,6 +1605,9 @@ function checkWrite(cwd, dir, data, w, elsewhere) {
1278
1605
  run: [elsewhere],
1279
1606
  },
1280
1607
  );
1608
+ // A file another command wrote while this one was stopped is not a hand
1609
+ // edit: say the lock was taken.
1610
+ refuseIfLockLost();
1281
1611
  if (editedByHand(dir, data, w.rel))
1282
1612
  refuse(
1283
1613
  E.ERR_FILE_EXISTS,
@@ -1481,6 +1811,63 @@ function commitStep(step) {
1481
1811
  if (stopAt?.(step)) throw STOPPED;
1482
1812
  }
1483
1813
 
1814
+ /**
1815
+ * Page files in the preview folder that theme-preview.json does not list:
1816
+ * a stopped change can leave one behind when its step record is damaged.
1817
+ * @param {string} dir
1818
+ * @returns {string[]} paths relative to the preview folder
1819
+ */
1820
+ function unrecordedPages(dir) {
1821
+ /** @type {string[]} */
1822
+ let listed = [];
1823
+ try {
1824
+ const files = JSON.parse(
1825
+ fs.readFileSync(path.join(dir, PREVIEW_DATA), 'utf8'),
1826
+ )?.files;
1827
+ if (Array.isArray(files)) listed = files.map(String);
1828
+ } catch {
1829
+ // No record, or a damaged one: every page file is unrecorded.
1830
+ }
1831
+ /** @type {string[]} */
1832
+ const out = [];
1833
+ for (const sub of [PAGES_DIR, LEGACY_PAGES_DIR]) {
1834
+ /** @type {string[]} */
1835
+ let names;
1836
+ try {
1837
+ names = fs.readdirSync(path.join(dir, sub));
1838
+ } catch {
1839
+ continue;
1840
+ }
1841
+ for (const name of names.sort()) {
1842
+ const rel = `${sub}/${name}`;
1843
+ if (name.endsWith('.tsx') && !listed.includes(rel)) out.push(rel);
1844
+ }
1845
+ }
1846
+ return out;
1847
+ }
1848
+
1849
+ /**
1850
+ * Whether a step record names a path that leads out of the preview folder
1851
+ * (a hand edit, a damaged file): such a record is not followed.
1852
+ * @param {string} dir
1853
+ * @param {any} p
1854
+ */
1855
+ function pendingEscapes(dir, p) {
1856
+ const rels = [
1857
+ ...(Array.isArray(p?.temps) ? p.temps : []),
1858
+ ...(Array.isArray(p?.record?.files) ? p.record.files : []),
1859
+ ...(Array.isArray(p?.old?.files) ? p.old.files : []),
1860
+ ].filter(x => typeof x === 'string');
1861
+ return rels.some(rel => {
1862
+ try {
1863
+ assertWithin(path.join(dir, rel), dir, {allowAbsolute: true});
1864
+ return false;
1865
+ } catch {
1866
+ return true;
1867
+ }
1868
+ });
1869
+ }
1870
+
1484
1871
  /**
1485
1872
  * Finish a preview change that was stopped part way (a kill), from the
1486
1873
  * step record it left: its leftover temp files go; each file it was writing
@@ -1498,13 +1885,11 @@ function recoverPreview(cwd, dir) {
1498
1885
  const pendingFile = path.join(dir, PENDING);
1499
1886
  /** @type {any} */
1500
1887
  let p;
1501
- try {
1502
- p = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
1503
- } catch (e) {
1504
- if (/** @type {any} */ (e)?.code === 'ENOENT') return null;
1505
- // Unreadable: the change is treated as never started. Its temp files
1506
- // are found by the names only the editor makes, when their process is
1507
- // gone.
1888
+ // Unreadable, or naming a path outside the folder: the change is
1889
+ // treated as never started.
1890
+ const abandon = () => {
1891
+ // Its temp files are found by the names only the editor makes, when
1892
+ // their process is gone.
1508
1893
  for (const sub of ['', PAGES_DIR, LEGACY_PAGES_DIR]) {
1509
1894
  /** @type {string[]} */
1510
1895
  let names;
@@ -1520,8 +1905,18 @@ function recoverPreview(cwd, dir) {
1520
1905
  }
1521
1906
  }
1522
1907
  fs.rmSync(pendingFile, {force: true});
1523
- return `removed ${shown(cwd, pendingFile)}, a damaged step record of a preview change that was stopped`;
1908
+ const strays = unrecordedPages(dir).map(rel =>
1909
+ shown(cwd, path.join(dir, rel)),
1910
+ );
1911
+ 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'}` : ''}`;
1912
+ };
1913
+ try {
1914
+ p = JSON.parse(fs.readFileSync(pendingFile, 'utf8'));
1915
+ } catch (e) {
1916
+ if (/** @type {any} */ (e)?.code === 'ENOENT') return null;
1917
+ return abandon();
1524
1918
  }
1919
+ if (pendingEscapes(dir, p)) return abandon();
1525
1920
  const inside = (/** @type {string} */ rel) =>
1526
1921
  confined(path.join(dir, rel), dir, PENDING);
1527
1922
  for (const t of Array.isArray(p?.temps) ? p.temps : [])
@@ -1918,6 +2313,25 @@ async function routeWrites(cwd, dir, data, theme, opts = {}) {
1918
2313
  return out;
1919
2314
  }
1920
2315
 
2316
+ /**
2317
+ * The theme's palette module, written as an empty stand-in when the theme
2318
+ * has no generated colors left and a kept Colors page still imports it.
2319
+ * Null when the module is there.
2320
+ * @param {string} cwd
2321
+ * @param {string} slug
2322
+ * @returns {string | null} the module, as shown
2323
+ */
2324
+ function paletteStandIn(cwd, slug) {
2325
+ const file = path.join(cwd, paletteFiles(slug).palette);
2326
+ if (fs.existsSync(file)) return null;
2327
+ fs.mkdirSync(path.dirname(file), {recursive: true});
2328
+ writeWhole(
2329
+ file,
2330
+ `${PALETTE_STAND_IN}\nexport const palette = {} as const;\n`,
2331
+ );
2332
+ return shown(cwd, file);
2333
+ }
2334
+
1921
2335
  /**
1922
2336
  * Rewrite the in-app preview routes of a theme when their imports changed, so
1923
2337
  * a font package installed after `set` loads on the next change or `show`,
@@ -1965,7 +2379,15 @@ export async function refreshPreviewRoute(cwd, slug) {
1965
2379
  if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === w.text)
1966
2380
  return false;
1967
2381
  if (editedByHand(dir, data, w.rel)) {
1968
- stale.push(shown(cwd, file));
2382
+ const standIn =
2383
+ w.rel === `${COLORS_PAGE.file}.tsx` &&
2384
+ fs.readFileSync(file, 'utf8').includes(`${slug}.palette`) &&
2385
+ paletteStandIn(cwd, slug);
2386
+ stale.push(
2387
+ standIn
2388
+ ? `${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)`
2389
+ : shown(cwd, file),
2390
+ );
1969
2391
  return false;
1970
2392
  }
1971
2393
  return true;
@@ -2047,7 +2469,8 @@ function openLine(cwd, at) {
2047
2469
  : encodeURIComponent(seg),
2048
2470
  )
2049
2471
  .join('/');
2050
- return `open /${url} in the running app${params.length ? `, with a value for ${params.join(', ')}` : ''}`;
2472
+ const base = nextBasePath(cwd);
2473
+ return `open ${base ?? ''}/${url} in the running app${params.length ? `, with a value for ${params.join(', ')}` : ''}${base == null ? ', after the basePath next.config sets from code (it goes in front)' : ''}`;
2051
2474
  }
2052
2475
  const routes = ['app', path.join('src', 'app')].filter(r =>
2053
2476
  fs.existsSync(path.join(cwd, r)),
@@ -2296,11 +2719,7 @@ async function pageTemplates(cwd) {
2296
2719
  * @param {string} pkg
2297
2720
  */
2298
2721
  function installed(cwd, pkg) {
2299
- for (let dir = cwd; ; dir = path.dirname(dir)) {
2300
- if (fs.existsSync(path.join(dir, 'node_modules', pkg, 'package.json')))
2301
- return true;
2302
- if (path.dirname(dir) === dir) return false;
2303
- }
2722
+ return findNodeModulesPackage(cwd, pkg) != null;
2304
2723
  }
2305
2724
 
2306
2725
  /**
@@ -2659,6 +3078,9 @@ async function addPreview(description, options, box) {
2659
3078
  const at = previewDir(cwd, options.path, {write: true, retry});
2660
3079
  const recovered = recoverPreview(cwd, at.dir);
2661
3080
  if (recovered) notes.push(recovered);
3081
+ const unstyled = coreStylesheetMissing(cwd, at);
3082
+ if (unstyled) notes.push(unstyled);
3083
+ notes.push(...nextConfigNotes(cwd));
2662
3084
  box.note = recovered;
2663
3085
  const existing = readPreview(cwd, at.dir, pf);
2664
3086
  /** @type {PreviewData} */
@@ -2972,31 +3394,22 @@ export async function themeEditPreviewApp(dir, options = {}) {
2972
3394
  if (slug != null && theme) {
2973
3395
  const from = themeFiles(cwd, slug);
2974
3396
  const ctx = await context(cwd);
2975
- const mtime = (/** @type {string} */ f) => {
2976
- try {
2977
- return fs.statSync(f).mtimeMs;
2978
- } catch {
2979
- return -1;
2980
- }
2981
- };
2982
- const built = Math.min(mtime(from.js), mtime(from.css));
2983
- // The editor writes the settings a moment after the build, so only a
2984
- // settings file clearly newer than the build means the build is stale.
2985
- // Without the theme's lock (it cannot be taken), a change may be in
2986
- // progress: nothing is built, and only a build that matches its
3397
+ // The build is judged by its content (staleBuild), never by file
3398
+ // times. Without the theme's lock (it cannot be taken), a change may be
3399
+ // in progress: nothing is built, and only a build that matches its
2987
3400
  // settings is copied.
3401
+ const why = staleBuild(cwd, slug, theme);
2988
3402
  if (/** @type {any} */ (options).readOnly) {
2989
- const why = staleBuild(cwd, slug, theme);
2990
3403
  if (why)
2991
3404
  refuse(
2992
3405
  E.ERR_THEME_BUSY,
2993
3406
  `The lock for ${slug} could not be taken, and its build is not current (${why}), so it is not copied. Nothing was changed.`,
2994
- {run: [`astryx experimental theme editor show ${slug}`]},
3407
+ {run: [`${P} show ${slug}`]},
2995
3408
  );
2996
- } else if (built < 0 || mtime(from.settings) > built + 2000) {
3409
+ } else if (why) {
2997
3410
  await buildTheme(ctx, slug, theme);
2998
3411
  notes.push(
2999
- `built ${shown(cwd, from.dir)}/ first: its build was ${built < 0 ? 'missing' : 'older than its settings'}, and the app gets a current copy`,
3412
+ `built ${shown(cwd, from.dir)}/ first: its build was not current (${why}), and the app gets a current copy`,
3000
3413
  );
3001
3414
  }
3002
3415
  const to = themeFiles('', slug);
@@ -3126,7 +3539,8 @@ export async function themeEditPreviewApp(dir, options = {}) {
3126
3539
  pages: data.pages.map(x => x.id),
3127
3540
  files,
3128
3541
  notes,
3129
- open: `cd ${quoteCommandArgument(folder)} && npm install && npm run dev, then open /theme-preview`,
3542
+ // A folder named like a flag (`-`, `-k`) is a path to cd only with ./.
3543
+ open: `cd ${quoteCommandArgument(folder.startsWith('-') ? `./${folder}` : folder)} && npm install && npm run dev, then open /theme-preview`,
3130
3544
  },
3131
3545
  };
3132
3546
  }
@@ -3150,6 +3564,29 @@ function readVersion(project, pkg) {
3150
3564
  }
3151
3565
  }
3152
3566
 
3567
+ /**
3568
+ * Why the in-app preview's record is damaged, with how to fix it, or null
3569
+ * (no preview, or a sound one). For answers that would suggest a preview
3570
+ * command, which the damage refuses.
3571
+ * @param {string} cwd
3572
+ * @returns {string | null}
3573
+ */
3574
+ export function previewRecordProblem(cwd) {
3575
+ try {
3576
+ const at = previewDir(cwd, undefined, {
3577
+ optional: true,
3578
+ retry: () => `${PREVIEW} add`,
3579
+ });
3580
+ if (at) readPreview(cwd, at.dir);
3581
+ return null;
3582
+ } catch (e) {
3583
+ const err = /** @type {any} */ (e);
3584
+ if (err?.code !== E.ERR_THEME_INVALID) return null;
3585
+ const fix = err.fix;
3586
+ return `${String(err.message).replace(/ Nothing was changed\.$/, '')}${fix ? ` To fix it: ${fix}.` : ''}`;
3587
+ }
3588
+ }
3589
+
3153
3590
  /**
3154
3591
  * The pages of the in-app theme preview. With no preview, and with no
3155
3592
  * routes folder for one, the list is empty; a damaged theme-preview.json is
@@ -3171,7 +3608,10 @@ export async function themeEditPreviewList(options = {}) {
3171
3608
  const data = at && readPreview(cwd, at.dir, pf);
3172
3609
  /** @type {string[]} */
3173
3610
  const notes = [];
3174
- if (data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir)) {
3611
+ const themeMissing = Boolean(
3612
+ data?.theme && !fs.existsSync(themeFiles(cwd, data.theme).dir),
3613
+ );
3614
+ if (data?.theme && themeMissing) {
3175
3615
  const themes = editedThemes(cwd);
3176
3616
  notes.push(
3177
3617
  `the preview wears ${data.theme}, which is gone, so its route does not build; ${PREVIEW} add${pf} switches it to ${themes.length === 1 ? themes[0] : "the app's own theme"}`,
@@ -3182,6 +3622,7 @@ export async function themeEditPreviewList(options = {}) {
3182
3622
  data: {
3183
3623
  folder: at && data ? shownDir(cwd, at.dir) : null,
3184
3624
  theme: data?.theme ?? null,
3625
+ themeMissing,
3185
3626
  pages: (data?.pages ?? []).map(x => ({id: x.id, label: x.label})),
3186
3627
  notes,
3187
3628
  },
@@ -3397,6 +3838,7 @@ async function removePreview(page, options, box) {
3397
3838
  // The whole preview: every entry is checked before the first delete. A
3398
3839
  // route changed by hand would be kept and still import the pages, so it
3399
3840
  // stops the remove instead.
3841
+ refuseIfLockLost();
3400
3842
  if (data.files.includes('page.tsx') && editedByHand(at.dir, data, 'page.tsx'))
3401
3843
  refuse(
3402
3844
  E.ERR_FILE_EXISTS,
@@ -3471,6 +3913,17 @@ async function removePreview(page, options, box) {
3471
3913
  );
3472
3914
  }
3473
3915
  tidyPageFolders(at.dir);
3916
+ // Files the record does not list stay: the preview never deletes what it
3917
+ // has no record of writing. Each is named, so the folder left is no
3918
+ // surprise.
3919
+ for (const rel of unrecordedPages(at.dir)) {
3920
+ const name = shown(cwd, path.join(at.dir, rel));
3921
+ if (kept.includes(name)) continue;
3922
+ kept.push(name);
3923
+ notes.push(
3924
+ `${name} is kept: the preview has no record of writing it, so it may hold your work`,
3925
+ );
3926
+ }
3474
3927
  try {
3475
3928
  fs.rmdirSync(at.dir);
3476
3929
  // Route group folders, such as (tools)/, that only held the preview.