@stagepass/cli 2.2.6 → 2.3.0-beta.1

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 (50) hide show
  1. package/README.md +61 -13
  2. package/TESTING-macos.md +35 -8
  3. package/bin/index.js +4 -1
  4. package/package.json +9 -8
  5. package/src/cli.js +62 -7
  6. package/src/commands/certs.js +375 -19
  7. package/src/commands/daemon.js +75 -7
  8. package/src/commands/dev.js +419 -0
  9. package/src/commands/link.js +66 -25
  10. package/src/commands/new.js +397 -41
  11. package/src/commands/npm-run.js +8 -0
  12. package/src/commands/reload.js +2 -2
  13. package/src/commands/setup.js +5 -5
  14. package/src/commands/start.js +386 -83
  15. package/src/commands/stop.js +50 -31
  16. package/src/commands/unlink.js +8 -6
  17. package/src/commands/upgrade.js +51 -12
  18. package/src/lib/apply-site-block.js +48 -0
  19. package/src/lib/autostart.js +300 -3
  20. package/src/lib/caddyfile.js +72 -13
  21. package/src/lib/cdn-snippets.js +145 -3
  22. package/src/lib/certs.js +334 -47
  23. package/src/lib/dev-port.js +45 -0
  24. package/src/lib/doctor-site.js +61 -5
  25. package/src/lib/doctor.js +48 -4
  26. package/src/lib/ensure-running.js +89 -0
  27. package/src/lib/exec.js +72 -24
  28. package/src/lib/live-server.js +484 -0
  29. package/src/lib/node-engine.js +55 -0
  30. package/src/lib/notify.js +62 -0
  31. package/src/lib/origins.js +27 -5
  32. package/src/lib/package-versions.js +9 -0
  33. package/src/lib/paths.js +18 -0
  34. package/src/lib/php-fpm.js +33 -0
  35. package/src/lib/project-sync.js +165 -20
  36. package/src/lib/projects.js +137 -7
  37. package/src/lib/prompts.js +19 -0
  38. package/src/lib/registry.js +27 -6
  39. package/src/lib/scaffold.js +288 -11
  40. package/src/lib/site-detect.js +78 -25
  41. package/src/lib/snippets.js +14 -11
  42. package/src/lib/spinner.js +60 -0
  43. package/src/lib/versions.js +20 -8
  44. package/templates/project/AGENTS.md.tmpl +4 -3
  45. package/templates/project/README.md.tmpl +35 -6
  46. package/templates/project/api/README.md.tmpl +7 -0
  47. package/templates/project/examples/php/README.md.tmpl +18 -0
  48. package/templates/project/examples/php/form.php +105 -0
  49. package/templates/project/examples/php/proxy.php +171 -0
  50. package/templates/project/scripts/build.mjs +200 -37
@@ -1,56 +1,75 @@
1
- import { execa } from 'execa';
2
1
  import chalk from 'chalk';
3
- import ora from 'ora';
4
- import { getAutostartStatus } from '../lib/autostart.js';
2
+ import { createSpinner } from '../lib/spinner.js';
3
+ import os from 'node:os';
4
+ import { defaultExec } from '../lib/exec.js';
5
+ import {
6
+ getAutostartStatus,
7
+ buildLaunchctlBootoutArgs,
8
+ LAUNCH_AGENT_LABEL,
9
+ } from '../lib/autostart.js';
5
10
 
6
11
  export async function stop(options = {}) {
7
12
  console.log(chalk.bold('\nšŸ›‘ Stopping Stagepass...'));
8
-
9
- const spinner = ora('Shutting down services...').start();
13
+
14
+ const exec = options.exec || defaultExec;
15
+ const spinner = createSpinner('Shutting down services...').start();
10
16
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
11
17
 
12
18
  if (options.verbose) {
13
- spinner.stop();
14
- console.log(chalk.dim('--- Verbose Logs ---'));
19
+ spinner.stop();
20
+ console.log(chalk.dim('--- Verbose Logs ---'));
15
21
  }
16
22
 
17
23
  try {
18
- // 1. Stop Caddy
24
+ /** @type {{ loaded?: boolean, plistExists?: boolean, plistPath?: string }} */
25
+ let status = { loaded: false, plistExists: false };
26
+ try {
27
+ status =
28
+ (await (options.getAutostartStatus || getAutostartStatus)({ exec })) ||
29
+ status;
30
+ } catch {
31
+ // ignore status failures; still stop caddy/php
32
+ }
33
+ const uid = options.uid ?? process.getuid?.() ?? os.userInfo().uid;
34
+ let usedBootout = false;
35
+
36
+ if (status.loaded || status.plistExists) {
37
+ try {
38
+ await exec('launchctl', buildLaunchctlBootoutArgs(uid));
39
+ usedBootout = true;
40
+ } catch {
41
+ // not loaded
42
+ }
43
+ }
44
+
45
+ // Always attempt a direct caddy stop as well (covers non-autostart / leftover).
19
46
  try {
20
- await execa('caddy', ['stop'], { stdio: stdioMode });
21
- } catch (e) {
47
+ await exec('caddy', ['stop'], { stdio: stdioMode });
48
+ } catch {
22
49
  // Ignore if already stopped
23
50
  }
24
51
 
25
- // 2. Stop PHP (optional, but cleaner)
26
52
  try {
27
- await execa('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
28
- } catch (e) {
29
- // Ignore
53
+ await exec('brew', ['services', 'stop', 'php'], { stdio: stdioMode });
54
+ } catch {
55
+ // Ignore
30
56
  }
31
57
 
32
58
  if (!options.verbose) {
33
- spinner.succeed(chalk.green('Services stopped.'));
59
+ spinner.succeed(chalk.green('Services stopped.'));
34
60
  } else {
35
- console.log(chalk.green('āœ” Services stopped.'));
61
+ console.log(chalk.green('āœ” Services stopped.'));
36
62
  }
37
63
 
38
- // Non-breaking hint only: existing stop semantics stay unchanged.
39
- try {
40
- const status = await getAutostartStatus();
41
- if (status.loaded || status.plistExists) {
42
- console.log(
43
- chalk.dim(
44
- 'Autostart is enabled; Caddy may start again at next login. Use `stagepass autostart off` to disable permanently.'
45
- )
46
- );
47
- }
48
- } catch {
49
- // ignore status failures
64
+ if (usedBootout || status.loaded || status.plistExists) {
65
+ console.log(
66
+ chalk.dim(
67
+ `Autostart LaunchAgent ${LAUNCH_AGENT_LABEL} was stopped with launchctl bootout (until next login). Use \`stagepass autostart off\` to disable permanently.`
68
+ )
69
+ );
50
70
  }
51
-
52
71
  } catch (error) {
53
72
  if (!options.verbose) spinner.fail('Error stopping services.');
54
- console.error(chalk.red(error.message));
73
+ console.error(chalk.red(error instanceof Error ? error.message : String(error)));
55
74
  }
56
- }
75
+ }
@@ -2,7 +2,7 @@ import fs from 'fs-extra';
2
2
  import path from 'path';
3
3
  import chalk from 'chalk';
4
4
  import { execa } from 'execa';
5
- import ora from 'ora';
5
+ import { createSpinner } from '../lib/spinner.js';
6
6
  import { resolveLinkDomain } from '../lib/domain.js';
7
7
  import { removeBlock } from '../lib/caddyfile.js';
8
8
  import { getCaddyfilePath, getProjectsPath } from '../lib/paths.js';
@@ -15,19 +15,19 @@ export async function unlink(domain, options = {}) {
15
15
  const resolved = resolveLinkDomain(domain, folderName);
16
16
  if (!resolved.ok) {
17
17
  console.log(chalk.red(`āŒ ${resolved.error}`));
18
- return;
18
+ return 1;
19
19
  }
20
20
 
21
21
  const targetDomain = resolved.domain;
22
22
  const caddyFilePath = getCaddyfilePath();
23
23
  const projectsPath = getProjectsPath();
24
24
 
25
- const spinner = ora(`Unlinking ${chalk.bold(targetDomain)}...`).start();
25
+ const spinner = createSpinner(`Unlinking ${chalk.bold(targetDomain)}...`).start();
26
26
 
27
27
  try {
28
28
  if (!(await fs.pathExists(caddyFilePath))) {
29
29
  spinner.warn('No Caddyfile found. Nothing to unlink.');
30
- return;
30
+ return 0;
31
31
  }
32
32
 
33
33
  let content = await fs.readFile(caddyFilePath, 'utf-8');
@@ -35,7 +35,7 @@ export async function unlink(domain, options = {}) {
35
35
 
36
36
  if (!result.removed) {
37
37
  spinner.warn(`Domain ${chalk.bold(targetDomain)} is not linked.`);
38
- return;
38
+ return 0;
39
39
  }
40
40
 
41
41
  await fs.writeFile(caddyFilePath, result.content ? `${result.content}\n` : '', 'utf-8');
@@ -43,16 +43,18 @@ export async function unlink(domain, options = {}) {
43
43
  } catch (e) {
44
44
  spinner.fail('Failed to update config.');
45
45
  if (options.verbose) console.error(e);
46
- return;
46
+ return 1;
47
47
  }
48
48
 
49
49
  try {
50
50
  const stdioMode = options.verbose ? 'inherit' : 'ignore';
51
51
  await execa('caddy', ['reload', '--config', caddyFilePath], { stdio: stdioMode });
52
52
  spinner.succeed(`Unlinked: ${targetDomain}`);
53
+ return 0;
53
54
  } catch (error) {
54
55
  spinner.warn('Config updated, but Caddy reload failed.');
55
56
  console.log(chalk.dim(' Is Stagepass running? Try: stagepass start'));
56
57
  if (options.verbose) console.error(error);
58
+ return 0;
57
59
  }
58
60
  }
@@ -13,10 +13,10 @@ import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
13
13
  import {
14
14
  PACKAGES_MAJOR_RANGE,
15
15
  fetchPublished,
16
- resolveSnippetLoaderVersion,
17
16
  installedHasPerModuleTypes,
18
17
  maxSatisfying,
19
18
  rangeHasPerModuleTypes,
19
+ resolveSnippetLoaderVersion,
20
20
  satisfiesSimple,
21
21
  } from '../lib/registry.js';
22
22
  import { detectSite, normalizeSiteUrl } from '../lib/site-detect.js';
@@ -32,6 +32,7 @@ const STAGEPASS_SCOPE = '@stagepass/';
32
32
  const SAFE_SPEC_RE = /^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/;
33
33
 
34
34
  /**
35
+ * True when the version looks like an npm dist-tag (bare word, e.g. latest).
35
36
  * @param {string} version
36
37
  */
37
38
  function isDistTag(version) {
@@ -43,7 +44,15 @@ function isDistTag(version) {
43
44
  }
44
45
 
45
46
  /**
46
- * Never writes a version/range no published release satisfies (avoids ETARGET on staged releases).
47
+ * Resolve the range to write for one @stagepass/* package.
48
+ *
49
+ * Never writes a version or range that no published release satisfies
50
+ * (releases can be staged but not yet approved, which gives ETARGET):
51
+ * - default: `^<latest>` when latest is in the current major, else
52
+ * `^<highest published 2.x>`; `^2` when npm is unreachable
53
+ * - `--version <semver|range>`: must match a published version
54
+ * - `--version <dist-tag>`: the published version behind that tag
55
+ *
47
56
  * @param {string} name
48
57
  * @param {string|undefined} requested
49
58
  * @param {{ distTags: Record<string, string>, versions: string[] } | null} published
@@ -88,6 +97,8 @@ export function resolvePackageTarget(name, requested, published) {
88
97
  }
89
98
 
90
99
  /**
100
+ * Resolve target ranges for every @stagepass/* dependency in package.json.
101
+ *
91
102
  * @param {string|undefined} requested `--version`
92
103
  * @param {string[]} names package names
93
104
  * @param {object} [deps]
@@ -110,6 +121,7 @@ export async function resolveUpgradeTargets(requested, names, deps = {}) {
110
121
  }
111
122
 
112
123
  /**
124
+ * Collect @stagepass/* entries from dependencies and devDependencies.
113
125
  * @param {object} pkg
114
126
  * @returns {{ section: 'dependencies'|'devDependencies', name: string, from: string }[]}
115
127
  */
@@ -129,6 +141,7 @@ export function findStagepassDeps(pkg) {
129
141
  }
130
142
 
131
143
  /**
144
+ * Rewrite @stagepass/* versions in a package.json object (mutates a copy).
132
145
  * @param {object} pkg
133
146
  * @param {string | Record<string, string>} target one spec for all, or per package name
134
147
  * @returns {{ next: object, changes: { name: string, from: string, to: string, section: string }[] }}
@@ -151,6 +164,10 @@ export function applyStagepassVersions(pkg, target) {
151
164
  }
152
165
 
153
166
  /**
167
+ * Upgrade @stagepass/* deps in the current project's package.json and sync
168
+ * the declared modules into stagepass.json, AGENTS.md, the Cursor rule and
169
+ * tsconfig/jsconfig types.
170
+ *
154
171
  * @param {object} [options]
155
172
  * @param {boolean} [options.dryRun]
156
173
  * @param {string} [options.version]
@@ -186,10 +203,11 @@ export async function upgrade(options = {}, deps = {}) {
186
203
  return 1;
187
204
  }
188
205
 
206
+ // Validate --site before any registry / network access (no partial side effects).
189
207
  if (options.site) {
190
- const c = normalizeSiteUrl(options.site);
191
- if (!c.ok) {
192
- log(chalk.red(c.error));
208
+ const siteCheck = normalizeSiteUrl(options.site);
209
+ if (!siteCheck.ok) {
210
+ log(chalk.red(siteCheck.error));
193
211
  return 1;
194
212
  }
195
213
  }
@@ -332,17 +350,38 @@ export async function upgrade(options = {}, deps = {}) {
332
350
  }
333
351
  if (t.resolved && satisfiesSimple(t.resolved, PACKAGES_MAJOR_RANGE)) snippetVersion = t.resolved;
334
352
  }
353
+
335
354
  if (options.dryRun) {
336
355
  log(chalk.dim('\nDry run: no files were modified.'));
337
356
  } else {
338
- if (changes.length > 0) {
339
- const trailingNewline = raw.endsWith('\n');
340
- const pkgBody = `${JSON.stringify(next, null, 2)}${trailingNewline ? '\n' : ''}`;
341
- await fse.writeFile(pkgPath, pkgBody, 'utf8');
342
- log(chalk.green('\nUpdated package.json.'));
357
+ try {
358
+ if (changes.length > 0) {
359
+ try {
360
+ if ((await fse.lstat(pkgPath)).isSymbolicLink()) {
361
+ log(chalk.red('package.json is a symlink; refusing to write.'));
362
+ return 1;
363
+ }
364
+ } catch {
365
+ /* missing / unreadable: writeFile will surface the error */
366
+ }
367
+ const trailingNewline = raw.endsWith('\n');
368
+ const pkgBody = `${JSON.stringify(next, null, 2)}${trailingNewline ? '\n' : ''}`;
369
+ await fse.writeFile(pkgPath, pkgBody, 'utf8');
370
+ log(chalk.green('\nUpdated package.json.'));
371
+ }
372
+ await applyProjectSync(cwd, plan.writes, fse);
373
+ if (plan.writes.length > 0) log(chalk.green(`Updated ${plan.writes.length} project file(s).`));
374
+ } catch (err) {
375
+ // Restore package.json if project-sync failed after the pkg write.
376
+ try {
377
+ if (changes.length > 0) await fse.writeFile(pkgPath, raw, 'utf8');
378
+ } catch {
379
+ /* best effort */
380
+ }
381
+ log(chalk.red(err instanceof Error ? err.message : String(err)));
382
+ if (options.verbose === true && err instanceof Error && err.stack) log(err.stack);
383
+ return 1;
343
384
  }
344
- await applyProjectSync(cwd, plan.writes, fse);
345
- if (plan.writes.length > 0) log(chalk.green(`Updated ${plan.writes.length} project file(s).`));
346
385
  }
347
386
 
348
387
  if (!snippetVersion) {
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Rewrite one Stagepass site block in the Caddyfile from a projects.json entry.
3
+ */
4
+
5
+ import fs from 'fs-extra';
6
+ import { renderSiteBlock, upsertBlock, isPhpEnabled } from './caddyfile.js';
7
+ import { validateRoot, getCaddyfilePath } from './paths.js';
8
+ import { normalizeDevPort } from './dev-port.js';
9
+
10
+ /**
11
+ * @param {string} domain
12
+ * @param {{ root?: string, origins?: string[], allowAllOrigins?: boolean, php?: boolean, devPort?: number }} project
13
+ * @param {object} [opts]
14
+ * @param {string} [opts.caddyfilePath]
15
+ * @param {typeof fs} [opts.fs]
16
+ * @returns {Promise<{ ok: true, path: string } | { ok: false, error: string }>}
17
+ */
18
+ export async function applySiteBlock(domain, project, opts = {}) {
19
+ const fse = opts.fs || fs;
20
+ const caddyfilePath = opts.caddyfilePath || getCaddyfilePath();
21
+ if (!project || typeof project.root !== 'string') {
22
+ return { ok: false, error: 'Project root is missing.' };
23
+ }
24
+ const rootCheck = validateRoot(project.root);
25
+ if (!rootCheck.ok) {
26
+ return { ok: false, error: rootCheck.error };
27
+ }
28
+ const devPort = normalizeDevPort(project.devPort);
29
+ let block;
30
+ try {
31
+ block = renderSiteBlock(domain, rootCheck.path, {
32
+ allowAllOrigins: project.allowAllOrigins === true,
33
+ origins: project.origins || [],
34
+ php: isPhpEnabled(project.php),
35
+ devPort: devPort || undefined,
36
+ });
37
+ } catch (err) {
38
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
39
+ }
40
+
41
+ let content = '';
42
+ if (await fse.pathExists(caddyfilePath)) {
43
+ content = await fse.readFile(caddyfilePath, 'utf-8');
44
+ }
45
+ content = upsertBlock(content, domain, block);
46
+ await fse.writeFile(caddyfilePath, `${content.trim()}\n`, 'utf-8');
47
+ return { ok: true, path: caddyfilePath };
48
+ }