@stagepass/cli 2.3.0 → 2.4.0

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 (42) hide show
  1. package/README.md +35 -24
  2. package/package.json +1 -1
  3. package/src/cli.js +48 -5
  4. package/src/commands/daemon.js +18 -2
  5. package/src/commands/dev.js +14 -0
  6. package/src/commands/link.js +11 -1
  7. package/src/commands/new.js +39 -16
  8. package/src/commands/npm-run.js +14 -0
  9. package/src/commands/reload.js +5 -1
  10. package/src/commands/start.js +1 -1
  11. package/src/commands/upgrade.js +84 -32
  12. package/src/lib/autostart.js +66 -8
  13. package/src/lib/build-script-upgrade.js +244 -0
  14. package/src/lib/caddy-version.js +31 -0
  15. package/src/lib/caddyfile.js +76 -36
  16. package/src/lib/doctor-site.js +15 -10
  17. package/src/lib/doctor.js +131 -30
  18. package/src/lib/migrate.js +29 -2
  19. package/src/lib/package-versions.js +1 -1
  20. package/src/lib/paths.js +5 -0
  21. package/src/lib/php-runtime.js +249 -0
  22. package/src/lib/scaffold.js +22 -16
  23. package/templates/project/README.md.tmpl +8 -6
  24. package/templates/project/api/README.md.tmpl +172 -5
  25. package/templates/project/api/action.php +100 -0
  26. package/templates/project/api/actions/boom.php +21 -0
  27. package/templates/project/api/actions/contact.php +46 -0
  28. package/templates/project/api/actions/ping.php +23 -0
  29. package/templates/project/api/actions.php +59 -0
  30. package/templates/project/api/env.example +25 -0
  31. package/templates/project/api/lib/bootstrap.php +44 -0
  32. package/templates/project/api/lib/config.php +180 -0
  33. package/templates/project/api/lib/request.php +94 -0
  34. package/templates/project/api/lib/response.php +97 -0
  35. package/templates/project/api/lib/security.php +114 -0
  36. package/templates/project/api/lib/validate.php +69 -0
  37. package/templates/project/gitignore +4 -0
  38. package/templates/project/php-private/config.php +24 -0
  39. package/templates/project/scripts/build.mjs +114 -8
  40. package/templates/project/examples/php/README.md.tmpl +0 -18
  41. package/templates/project/examples/php/form.php +0 -105
  42. package/templates/project/examples/php/proxy.php +0 -171
@@ -26,6 +26,10 @@ import {
26
26
  readStagepassJson,
27
27
  resolveUpgradeModules,
28
28
  } from '../lib/project-sync.js';
29
+ import {
30
+ defaultBuildScriptTemplatePath,
31
+ planBuildScriptUpgrade,
32
+ } from '../lib/build-script-upgrade.js';
29
33
 
30
34
  const STAGEPASS_SCOPE = '@stagepass/';
31
35
 
@@ -166,7 +170,8 @@ export function applyStagepassVersions(pkg, target) {
166
170
  /**
167
171
  * Upgrade @stagepass/* deps in the current project's package.json and sync
168
172
  * the declared modules into stagepass.json, AGENTS.md, the Cursor rule and
169
- * tsconfig/jsconfig types.
173
+ * tsconfig/jsconfig types. Replaces scripts/build.mjs when it is still an
174
+ * unmodified scaffold from an earlier CLI.
170
175
  *
171
176
  * @param {object} [options]
172
177
  * @param {boolean} [options.dryRun]
@@ -270,6 +275,22 @@ export async function upgrade(options = {}, deps = {}) {
270
275
  if (!rl) rl = deps.createReadline?.() || readline.createInterface({ input, output });
271
276
  return rl;
272
277
  };
278
+ const closeRl = () => {
279
+ if (!rl) return;
280
+ rl.close();
281
+ rl = null;
282
+ };
283
+ const ask = async (question, def) => {
284
+ const answer = await getRl().question(`${question} (${def}): `);
285
+ const trimmed = String(answer || '').trim();
286
+ return trimmed === '' ? def : trimmed;
287
+ };
288
+ const confirmFn = async (question, defYes) => {
289
+ const answer = await getRl().question(`${question} (${defYes ? 'Y/n' : 'y/N'}): `);
290
+ const t = String(answer || '').trim().toLowerCase();
291
+ if (t === '') return defYes;
292
+ return ['y', 'yes'].includes(t);
293
+ };
273
294
  let resolved;
274
295
  try {
275
296
  resolved = await resolveUpgradeModules(
@@ -279,21 +300,12 @@ export async function upgrade(options = {}, deps = {}) {
279
300
  loadProjects: deps.loadProjects,
280
301
  interactive,
281
302
  log,
282
- ask: async (question, def) => {
283
- const answer = await getRl().question(`${question} (${def}): `);
284
- const trimmed = String(answer || '').trim();
285
- return trimmed === '' ? def : trimmed;
286
- },
287
- confirm: async (question, defYes) => {
288
- const answer = await getRl().question(`${question} (${defYes ? 'Y/n' : 'y/N'}): `);
289
- const t = String(answer || '').trim().toLowerCase();
290
- if (t === '') return defYes;
291
- return ['y', 'yes'].includes(t);
292
- },
303
+ ask,
304
+ confirm: confirmFn,
293
305
  }
294
306
  );
295
307
  } finally {
296
- if (rl) rl.close();
308
+ closeRl();
297
309
  }
298
310
  if (!resolved.ok) {
299
311
  log(chalk.red(resolved.error));
@@ -311,25 +323,7 @@ export async function upgrade(options = {}, deps = {}) {
311
323
  fse
312
324
  );
313
325
 
314
- log(chalk.bold(`\nProject files for modules: ${resolved.modules.length ? resolved.modules.join(', ') : 'none'}`));
315
- if (plan.writes.length === 0) {
316
- log(' Everything is up to date.');
317
- }
318
- for (const w of plan.writes) {
319
- log(` ${w.file}: ${w.action}`);
320
- }
321
- for (const note of plan.notes) {
322
- log(chalk.yellow(` note: ${note}`));
323
- }
324
- if (perModuleTypes === false && resolved.modules.length > 0 && !resolved.modules.includes('all')) {
325
- log(
326
- chalk.yellow(
327
- ' note: the published @stagepass/modules has no per-module types yet (needs 2.2.0); types use "@stagepass/modules". Run `stagepass upgrade` again once it is published.'
328
- )
329
- );
330
- }
331
-
332
- // Snippet: --version pin of loader on 2.x wins; resolve before writing so a failure changes nothing.
326
+ // Refuse an unpublished --version before asking about scripts/build.mjs or writing.
333
327
  let loaderPub = '@stagepass/loader' in published ? published['@stagepass/loader'] : undefined;
334
328
  const getLoaderPub = async () => {
335
329
  if (loaderPub !== undefined) return loaderPub;
@@ -351,6 +345,64 @@ export async function upgrade(options = {}, deps = {}) {
351
345
  if (t.resolved && satisfiesSimple(t.resolved, PACKAGES_MAJOR_RANGE)) snippetVersion = t.resolved;
352
346
  }
353
347
 
348
+ /** @type {{ action: string, from?: string, content?: string, note?: string }} */
349
+ let buildUpgrade = { action: 'skipped' };
350
+ try {
351
+ let currentBuild;
352
+ try {
353
+ currentBuild = await fse.readFile(defaultBuildScriptTemplatePath(), 'utf8');
354
+ } catch (error) {
355
+ buildUpgrade = {
356
+ action: 'unreadable',
357
+ note: `Could not read the scaffold build script (${error instanceof Error ? error.message : String(error)}). The project script was left unchanged.`,
358
+ };
359
+ currentBuild = null;
360
+ }
361
+ if (currentBuild != null) {
362
+ buildUpgrade = await planBuildScriptUpgrade({
363
+ cwd,
364
+ currentSource: currentBuild,
365
+ interactive,
366
+ confirm: confirmFn,
367
+ fse,
368
+ });
369
+ }
370
+ if (buildUpgrade.action === 'update' && buildUpgrade.content) {
371
+ plan.writes.push({
372
+ file: 'scripts/build.mjs',
373
+ content: buildUpgrade.content,
374
+ action: `replace unmodified scaffold (${buildUpgrade.from})`,
375
+ });
376
+ }
377
+ } finally {
378
+ closeRl();
379
+ }
380
+
381
+ log(chalk.bold(`\nProject files for modules: ${resolved.modules.length ? resolved.modules.join(', ') : 'none'}`));
382
+ if (plan.writes.length === 0) {
383
+ log(' Everything is up to date.');
384
+ }
385
+ for (const w of plan.writes) {
386
+ log(` ${w.file}: ${w.action}`);
387
+ }
388
+ for (const note of plan.notes) {
389
+ log(chalk.yellow(` note: ${note}`));
390
+ }
391
+ if (buildUpgrade.action === 'custom') {
392
+ log(chalk.yellow(buildUpgrade.note));
393
+ } else if (buildUpgrade.action !== 'update' && buildUpgrade.note) {
394
+ const warn = buildUpgrade.action === 'declined' || buildUpgrade.action === 'symlink' || buildUpgrade.action === 'unreadable';
395
+ const line = ` ${buildUpgrade.note}`;
396
+ log(warn ? chalk.yellow(line) : line);
397
+ }
398
+ if (perModuleTypes === false && resolved.modules.length > 0 && !resolved.modules.includes('all')) {
399
+ log(
400
+ chalk.yellow(
401
+ ' note: the published @stagepass/modules has no per-module types yet (needs 2.2.0); types use "@stagepass/modules". Run `stagepass upgrade` again once it is published.'
402
+ )
403
+ );
404
+ }
405
+
354
406
  if (options.dryRun) {
355
407
  log(chalk.dim('\nDry run: no files were modified.'));
356
408
  } else {
@@ -205,6 +205,32 @@ async function requireAbsoluteExistingPath(candidate, label, pathExists) {
205
205
  return { ok: true, path: candidate };
206
206
  }
207
207
 
208
+ /** `<prefix>/Cellar/node[…]/<version>/<rel>` (Homebrew node keg). */
209
+ const CELLAR_NODE_RE = /^(.*)\/Cellar\/node[^/]*\/[^/]+\/(.+)$/;
210
+
211
+ /**
212
+ * Use `<prefix>/<rel>` when `absPath` is a versioned Homebrew node Cellar
213
+ * path and that unversioned file exists. Otherwise return `absPath`.
214
+ * @param {string} absPath
215
+ * @param {(p: string) => Promise<boolean>} pathExists
216
+ */
217
+ async function preferHomebrewStablePath(absPath, pathExists) {
218
+ const m = CELLAR_NODE_RE.exec(absPath);
219
+ if (!m) return absPath;
220
+ const stable = `${m[1]}/${m[2]}`;
221
+ if (stable !== absPath && (await pathExists(stable))) return stable;
222
+ return absPath;
223
+ }
224
+
225
+ /**
226
+ * True for `<prefix>/Cellar/node[…]/<version>/bin/node`.
227
+ * @param {string} absPath
228
+ */
229
+ export function isVersionedCellarNodeBin(absPath) {
230
+ const m = CELLAR_NODE_RE.exec(String(absPath || ''));
231
+ return !!m && m[2] === 'bin/node';
232
+ }
233
+
208
234
  /**
209
235
  * Resolve absolute node + CLI entry paths for the LaunchAgent.
210
236
  * @param {object} [opts]
@@ -237,7 +263,7 @@ export async function resolveAutostartPaths(opts = {}) {
237
263
  cliPath: null,
238
264
  };
239
265
  }
240
- const nodePath = nodeCheck.path;
266
+ const nodePath = await preferHomebrewStablePath(nodeCheck.path, pathExists);
241
267
 
242
268
  let cliPath = null;
243
269
 
@@ -274,7 +300,8 @@ export async function resolveAutostartPaths(opts = {}) {
274
300
  };
275
301
  }
276
302
 
277
- return { ok: true, nodePath, cliPath: cliCheck.path, error: null };
303
+ const cliPathStable = await preferHomebrewStablePath(cliCheck.path, pathExists);
304
+ return { ok: true, nodePath, cliPath: cliPathStable, error: null };
278
305
  }
279
306
 
280
307
  /**
@@ -539,9 +566,13 @@ export async function getAutostartStatus(opts = {}) {
539
566
  /**
540
567
  * Write plist (idempotent) and bootstrap the LaunchAgent.
541
568
  * @param {object} [opts]
569
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
570
+ * @param {() => number} [opts.now]
542
571
  */
543
572
  export async function enableAutostart(opts = {}) {
544
573
  const exec = opts.exec || defaultExec;
574
+ const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
575
+ const now = opts.now || Date.now;
545
576
  const uid = opts.uid ?? process.getuid?.() ?? os.userInfo().uid;
546
577
  const pathExists = opts.pathExists || ((p) => fs.pathExists(p));
547
578
  const paths =
@@ -609,19 +640,46 @@ export async function enableAutostart(opts = {}) {
609
640
 
610
641
  await writeFile(plistPath, plist);
611
642
 
612
- // Idempotent: bootout if already loaded, then bootstrap.
643
+ // bootout returns before launchd drops the job; bootstrap then hits error 5.
644
+ let unloaded = false;
613
645
  try {
614
646
  await exec('launchctl', buildLaunchctlBootoutArgs(uid));
647
+ unloaded = true;
615
648
  } catch {
616
- // not loaded yet
649
+ // not loaded yet: one bootstrap, no wait
650
+ }
651
+ if (unloaded) {
652
+ const until = now() + 3000;
653
+ for (let i = 0; i < 60 && now() < until; i++) {
654
+ try {
655
+ await exec('launchctl', buildLaunchctlPrintArgs(uid));
656
+ } catch {
657
+ break;
658
+ }
659
+ await sleep(50);
660
+ }
617
661
  }
618
662
 
619
- try {
620
- await exec('launchctl', buildLaunchctlBootstrapArgs(uid, plistPath));
621
- } catch (error) {
663
+ let bootErr = null;
664
+ for (let n = 0, tries = unloaded ? 3 : 1; n < tries; n++) {
665
+ try {
666
+ await exec('launchctl', buildLaunchctlBootstrapArgs(uid, plistPath));
667
+ bootErr = null;
668
+ break;
669
+ } catch (error) {
670
+ bootErr = error;
671
+ const msg = `${error instanceof Error ? error.message : error} ${error?.stderr || ''}`;
672
+ const race =
673
+ error?.code === 5 ||
674
+ /Input\/output error|Bootstrap failed: 5/.test(msg);
675
+ if (!race || n + 1 === tries) break;
676
+ await sleep(100);
677
+ }
678
+ }
679
+ if (bootErr) {
622
680
  return {
623
681
  ok: false,
624
- error: error instanceof Error ? error.message : String(error),
682
+ error: bootErr instanceof Error ? bootErr.message : String(bootErr),
625
683
  plistPath,
626
684
  paths,
627
685
  };
@@ -0,0 +1,244 @@
1
+ /**
2
+ * Detect an unmodified scaffold `scripts/build.mjs` and render the current one.
3
+ *
4
+ * Known hashes are SHA-256 of the LF-normalized template bytes (placeholders
5
+ * intact) from git history of `templates/project/scripts/build.mjs`. When the
6
+ * template changes, append the previous file's hash here or older projects
7
+ * will be treated as hand-edited.
8
+ *
9
+ * Project copies differ only by the three scaffold tokens and by CRLF. Those
10
+ * are normalized before hashing. Any other edit stays custom and is not overwritten.
11
+ */
12
+
13
+ import { createHash } from 'node:crypto';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import fs from 'fs-extra';
17
+ import { applyTemplate } from './scaffold.js';
18
+
19
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
20
+
21
+ /** Project-relative path written by `stagepass new`. */
22
+ export const BUILD_SCRIPT_REL = 'scripts/build.mjs';
23
+
24
+ export const BUILD_SCRIPT_DOC_URL =
25
+ 'https://github.com/arobertherz/stagepass/blob/master/docs/cli.md#upgrade';
26
+
27
+ export const BUILD_SCRIPT_CUSTOM_HINT = [
28
+ 'scripts/build.mjs has local edits, so stagepass upgrade left it unchanged.',
29
+ `What the current scaffold does (${BUILD_SCRIPT_DOC_URL}):`,
30
+ ' stagepass watch and stagepass dev write only stable dist/main.js and dist/styles.css. Hashed files and manifest.json stay as the last stagepass build left them.',
31
+ ' stagepass build writes content hashes, stable copies, and SRI in dist/manifest.json, then deletes hashed files the previous manifest listed that this build does not. CLI 2.2.x manifests store those filenames as strings; those names are included. Only plain <base>.<8 hex><ext> files directly in dist/ are removed.',
32
+ ' When stagepass.json has "php": true, stagepass build also copies api/ and .php/config.php into dist. It skips .env, .php/rate-limit, logs, pid files, and key, certificate, or database files (.pem, .key, .p12, .pfx, .crt, .cer, .sqlite, .db). It keeps .htaccess and .env.example. Watch does not copy them.',
33
+ 'Port that behavior into your script by hand. The Scripts section of a README from stagepass new describes the same stagepass build, stagepass watch and stagepass dev commands.',
34
+ ].join('\n');
35
+
36
+ export const BUILD_SCRIPT_MISSING_NOTE =
37
+ 'No scripts/build.mjs. stagepass build, stagepass watch and stagepass dev use the scaffold from stagepass new. See ' +
38
+ BUILD_SCRIPT_DOC_URL;
39
+
40
+ /**
41
+ * Distinct blobs of the scaffold before the template bundled with this CLI.
42
+ * @type {{ id: string, commit: string, sha256: string }[]}
43
+ */
44
+ export const KNOWN_SCAFFOLD_BUILD_SCRIPTS = [
45
+ {
46
+ id: '2.1.0-2.2.7',
47
+ commit: '8a98239',
48
+ sha256: 'f297b451318a5d37a26552fd2b284d1c8fc32d982d324d7554ea51010cc8da8b',
49
+ },
50
+ {
51
+ id: '2.3.0-sri',
52
+ commit: 'f7afa80',
53
+ sha256: 'a3af9742800b4652603f42683f78028cb51fb31791d904d61eb474ba3ab2d2cd',
54
+ },
55
+ {
56
+ id: '2.3.0',
57
+ commit: 'bcc87fc',
58
+ sha256: '10ee2eaa94b0b357bedb37bf89120b6ac971273e4e1fdc8c45eafb7d102bab22',
59
+ },
60
+ {
61
+ id: 'watch-stable',
62
+ commit: '688dca9',
63
+ sha256: '8f0bc02d4a58af8ad1b830bf53c4f712db6761f5155f4d11053f02ca203b88da',
64
+ },
65
+ {
66
+ id: 'pre-php',
67
+ commit: '9cb8c49',
68
+ sha256: 'f6507c32b6b59e97930bd9dbe1e4d272efcd2678213929b7bc1eb3aa0a167459',
69
+ },
70
+ {
71
+ id: '2.4.0',
72
+ commit: '983f090',
73
+ sha256: '98578f87225fd03d08b7e5d5bbdecc07cbb6ccbbc754642c6e880bb2f53559bb',
74
+ },
75
+ ];
76
+
77
+ const TOKEN_SPECS = [
78
+ {
79
+ key: 'ENTRY_JS',
80
+ placeholder: '{{ENTRY_JS}}',
81
+ re: /^const ENTRY_JS = process\.env\.STAGEPASS_ENTRY_JS \|\| '([^'\\]*)';$/m,
82
+ restore: "const ENTRY_JS = process.env.STAGEPASS_ENTRY_JS || '{{ENTRY_JS}}';",
83
+ },
84
+ {
85
+ key: 'ENTRY_CSS',
86
+ placeholder: '{{ENTRY_CSS}}',
87
+ re: /^const ENTRY_CSS = process\.env\.STAGEPASS_ENTRY_CSS \|\| '([^'\\]*)';$/m,
88
+ restore: "const ENTRY_CSS = process.env.STAGEPASS_ENTRY_CSS || '{{ENTRY_CSS}}';",
89
+ },
90
+ {
91
+ key: 'USE_SASS',
92
+ placeholder: '{{USE_SASS}}',
93
+ re: /^const USE_SASS = \(process\.env\.STAGEPASS_USE_SASS \|\| '([^'\\]*)'\) === 'true';$/m,
94
+ restore: "const USE_SASS = (process.env.STAGEPASS_USE_SASS || '{{USE_SASS}}') === 'true';",
95
+ },
96
+ ];
97
+
98
+ /** Absolute path of the scaffold shipped in this package. */
99
+ export function defaultBuildScriptTemplatePath() {
100
+ return path.join(__dirname, '../../templates/project/scripts/build.mjs');
101
+ }
102
+
103
+ /**
104
+ * @param {string} source
105
+ * @returns {string}
106
+ */
107
+ export function normalizeNewlines(source) {
108
+ return String(source).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
109
+ }
110
+
111
+ /**
112
+ * LF newlines, and the three scaffold assignments restored to placeholders.
113
+ * @param {string} source
114
+ * @returns {string}
115
+ */
116
+ export function canonicalizeBuildScript(source) {
117
+ let text = normalizeNewlines(source);
118
+ for (const spec of TOKEN_SPECS) {
119
+ text = text.replace(spec.re, spec.restore);
120
+ }
121
+ return text;
122
+ }
123
+
124
+ /**
125
+ * @param {string} source
126
+ * @returns {string}
127
+ */
128
+ export function hashBuildScript(source) {
129
+ return createHash('sha256').update(canonicalizeBuildScript(source), 'utf8').digest('hex');
130
+ }
131
+
132
+ /**
133
+ * Entry paths currently written in a scaffold script.
134
+ * @param {string} source
135
+ * @returns {Record<string, string>}
136
+ */
137
+ export function readScaffoldTokens(source) {
138
+ const text = normalizeNewlines(source);
139
+ /** @type {Record<string, string>} */
140
+ const tokens = {};
141
+ for (const spec of TOKEN_SPECS) {
142
+ const match = spec.re.exec(text);
143
+ tokens[spec.key] = match ? match[1] : spec.placeholder;
144
+ }
145
+ return tokens;
146
+ }
147
+
148
+ /**
149
+ * @param {string} currentSource template bytes from this package
150
+ * @param {string} projectSource
151
+ * @returns {string}
152
+ */
153
+ export function renderCurrentBuildScript(currentSource, projectSource) {
154
+ return applyTemplate(currentSource, readScaffoldTokens(projectSource));
155
+ }
156
+
157
+ /**
158
+ * @param {string} source project or template bytes
159
+ * @param {string} currentSource template bundled with this CLI
160
+ * @returns {{ status: 'current' | 'stock' | 'custom', hash: string, id?: string, commit?: string }}
161
+ */
162
+ export function classifyBuildScript(source, currentSource) {
163
+ const hash = hashBuildScript(source);
164
+ if (hash === hashBuildScript(currentSource)) return { status: 'current', hash };
165
+ const known = KNOWN_SCAFFOLD_BUILD_SCRIPTS.find((item) => item.sha256 === hash);
166
+ if (known) return { status: 'stock', hash, id: known.id, commit: known.commit };
167
+ return { status: 'custom', hash };
168
+ }
169
+
170
+ /**
171
+ * @param {string} cwd
172
+ * @param {string} currentSource
173
+ * @param {{ lstat: Function, readFile: Function }} [fse]
174
+ * @returns {Promise<{ status: string, hash?: string, id?: string, commit?: string, raw?: string, error?: string }>}
175
+ */
176
+ export async function inspectProjectBuildScript(cwd, currentSource, fse = fs) {
177
+ const abs = path.join(cwd, BUILD_SCRIPT_REL);
178
+ /** @type {import('node:fs').Stats} */
179
+ let st;
180
+ try {
181
+ st = await fse.lstat(abs);
182
+ } catch (err) {
183
+ if (err && /** @type {{ code?: string }} */ (err).code === 'ENOENT') return { status: 'missing' };
184
+ return {
185
+ status: 'unreadable',
186
+ error: err instanceof Error ? err.message : String(err),
187
+ };
188
+ }
189
+ if (st.isSymbolicLink()) return { status: 'symlink' };
190
+ if (!st.isFile()) return { status: 'unreadable', error: 'not a file' };
191
+ /** @type {string} */
192
+ let raw;
193
+ try {
194
+ raw = await fse.readFile(abs, 'utf8');
195
+ } catch (err) {
196
+ return {
197
+ status: 'unreadable',
198
+ error: err instanceof Error ? err.message : String(err),
199
+ };
200
+ }
201
+ const classified = classifyBuildScript(raw, currentSource);
202
+ return { ...classified, raw };
203
+ }
204
+
205
+ /**
206
+ * Decide whether upgrade should replace scripts/build.mjs.
207
+ * Does not write. `interactive` false (no TTY, or `--yes`) accepts a stock script.
208
+ *
209
+ * @param {object} options
210
+ * @param {string} options.cwd
211
+ * @param {string} options.currentSource
212
+ * @param {boolean} options.interactive
213
+ * @param {(question: string, defYes: boolean) => Promise<boolean>} [options.confirm]
214
+ * @param {{ lstat: Function, readFile: Function }} [options.fse]
215
+ */
216
+ export async function planBuildScriptUpgrade(options) {
217
+ const fse = options.fse || fs;
218
+ const found = await inspectProjectBuildScript(options.cwd, options.currentSource, fse);
219
+ if (found.status === 'missing') return { action: 'missing', note: BUILD_SCRIPT_MISSING_NOTE };
220
+ if (found.status === 'symlink') {
221
+ return { action: 'symlink', note: 'scripts/build.mjs is a symlink; left unchanged.' };
222
+ }
223
+ if (found.status === 'unreadable') {
224
+ return {
225
+ action: 'unreadable',
226
+ note: `scripts/build.mjs could not be read; left unchanged. ${found.error || ''}`.trim(),
227
+ };
228
+ }
229
+ if (found.status === 'current') {
230
+ return { action: 'current', note: 'scripts/build.mjs already matches the current scaffold.' };
231
+ }
232
+ if (found.status === 'custom') return { action: 'custom', note: BUILD_SCRIPT_CUSTOM_HINT };
233
+ const content = renderCurrentBuildScript(options.currentSource, found.raw || '');
234
+ if (!options.interactive) return { action: 'update', from: found.id, content };
235
+ if (typeof options.confirm !== 'function') {
236
+ throw new Error('confirm is required when upgrade asks about scripts/build.mjs');
237
+ }
238
+ const yes = await options.confirm(
239
+ `Replace scripts/build.mjs with the current scaffold? It matches the unmodified ${found.id} template.`,
240
+ true
241
+ );
242
+ if (!yes) return { action: 'declined', note: 'scripts/build.mjs left unchanged.' };
243
+ return { action: 'update', from: found.id, content };
244
+ }
@@ -0,0 +1,31 @@
1
+ import { defaultExec } from './exec.js';
2
+
3
+ /** v3 site blocks (`match status 2xx`) need Caddy 2.9+. */
4
+ export const CADDY_UPGRADE_HINT = 'brew upgrade caddy';
5
+
6
+ /**
7
+ * Read `caddy version` (`v2.10.2 h1:...`) and whether it is at least 2.9.0.
8
+ * Not found, or output that does not parse, is `{ known: false }` so callers
9
+ * keep the previous behaviour.
10
+ *
11
+ * @param {import('./exec.js').ExecFn} [exec]
12
+ * @returns {Promise<{ known: true, version: string, ok: boolean } | { known: false }>}
13
+ */
14
+ export async function readCaddyVersion(exec = defaultExec) {
15
+ let text = '';
16
+ try {
17
+ const result = await exec('caddy', ['version']);
18
+ text = `${result && result.stdout ? result.stdout : ''}\n${result && result.stderr ? result.stderr : ''}`;
19
+ } catch {
20
+ return { known: false };
21
+ }
22
+ const match = text.match(/v(\d+)\.(\d+)\.(\d+)/);
23
+ if (!match) return { known: false };
24
+ const major = Number(match[1]);
25
+ const minor = Number(match[2]);
26
+ return {
27
+ known: true,
28
+ version: `${major}.${minor}.${match[3]}`,
29
+ ok: major > 2 || (major === 2 && minor >= 9),
30
+ };
31
+ }