@stagepass/cli 2.3.0 → 2.3.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.
package/README.md CHANGED
@@ -6,7 +6,7 @@ The CLI sets up and manages the local Stagepass infrastructure (`.sp` domains, C
6
6
 
7
7
  ## Install
8
8
 
9
- Published CLI 2.2.7 requires Node.js **18+** (`engines.node`: `>=18.0.0`) on **macOS** with Homebrew. CLI 2.3.0 (unreleased) raises the floor to `>=20.17.0` because `@inquirer/prompts@8` requires it. Development and CI use Node 22 or 24.
9
+ Published CLI 2.3.0 requires Node.js **20.17+** (`engines.node`: `>=20.17.0`) on **macOS** with Homebrew, because `@inquirer/prompts@8` requires it. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18. Development and CI use Node 22 or 24.
10
10
 
11
11
  ```bash
12
12
  npm install -g @stagepass/cli@2
@@ -21,7 +21,7 @@ npx @stagepass/cli@2 setup
21
21
  ## Requirements
22
22
 
23
23
  - **macOS** (system commands refuse other platforms with exit code 1; this is not a breaking change because those commands never worked off macOS)
24
- - Published CLI 2.2.7: Node.js 18+ (`engines.node` `>=18.0.0`). CLI 2.3.0 (unreleased): Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
24
+ - Published CLI 2.3.0: Node.js `>=20.17.0`. Use Node 22 or 24 for local development and CI
25
25
  - Homebrew
26
26
 
27
27
  `stagepass --version` and `stagepass --help` work on any platform. For tests/CI only, set `STAGEPASS_SKIP_PLATFORM_CHECK=1` to bypass the macOS guard (not for production use).
@@ -36,6 +36,8 @@ stagepass start
36
36
 
37
37
  # inside your project folder
38
38
  stagepass link my-project --origin www.example.com --origin my-project.webflow.io
39
+ stagepass build
40
+ stagepass dev
39
41
  ```
40
42
 
41
43
  Your project is then available at `https://my-project.sp`. Success output:
@@ -54,31 +56,29 @@ Linked: https://my-project.sp -> /absolute/path/to/project
54
56
  | `stagepass unlink [domain]` | Remove the site block and `projects.json` entry, reload Caddy. |
55
57
  | `stagepass reload` | Reload Caddy configuration. Migrates legacy Caddyfile blocks if needed. |
56
58
  | `stagepass stop` | Stop Caddy & PHP. If autostart is installed/loaded, `launchctl bootout` first (until next login); use `autostart off` to disable permanently. |
57
- | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files: **(unreleased, CLI 2.3.0)**. Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
59
+ | `stagepass doctor` | Read-only diagnostics (Homebrew, Caddy, PHP/php-fpm, dnsmasq, resolver, port 443, Caddyfile, projects, certs, LaunchAgent, declared modules vs. live site). CDN pin warnings in docs + project files. Never uses sudo. `--json`, `--skip-site`. Exit `1` if any fail. |
58
60
  | `stagepass certs check` | Read-only Caddy local CA check (validity, System keychain trust, orphans, optional TLS handshake per linked domain). `--json`, `--skip-handshake`. |
59
61
  | `stagepass certs trust` | Run `caddy trust` after interactive confirmation (or `--yes`). |
60
- | `stagepass certs renew` | **(unreleased, CLI 2.3.0)** Repair failing linked site certs; `--root` moves the CA folder to a backup (double confirm, or `--yes --i-understand-root-renewal`); `--remove-orphans` deletes keychain orphans by SHA-1 after confirm. |
62
+ | `stagepass certs renew` | Repair failing linked site certs; `--root` moves the CA folder to a backup (double confirm, or `--yes --i-understand-root-renewal`); `--remove-orphans` deletes keychain orphans by SHA-1 after confirm. |
61
63
  | `stagepass autostart on\|off\|status` | Manage a user LaunchAgent (`io.github.arobertherz.stagepass`) that runs `stagepass daemon` at login. |
62
64
  | `stagepass daemon` | Non-interactive LaunchAgent helper (PHP-FPM ensure, certs log-only, `caddy run`, macOS notifications). Never uses sudo. |
63
65
  | `stagepass new [name]` | Scaffold a lean Webflow project (TypeScript + SCSS by default). |
64
66
  | `stagepass build` | Run `npm run build` in the current project (forwards exit code). |
65
67
  | `stagepass watch` | Run `npm run watch` in the current project (forwards exit code). If Stagepass is not running, asks to start it (TTY) or prints a `stagepass start` hint (non-TTY / CI); warns with `stagepass link` when the cwd is not linked. |
66
- | `stagepass dev` | **(unreleased, CLI 2.3.0)** Like watch, plus live reload on the linked `.sp` domain. Same running check as watch; requires `stagepass link` (hard error if unlinked). |
68
+ | `stagepass dev` | Like `stagepass watch`, plus live reload on the linked `.sp` domain (CSS can swap without a full reload). Same running check as watch; requires `stagepass link` (hard error if unlinked). |
67
69
  | `stagepass upgrade` | Bump `@stagepass/*`, sync declared modules, `AGENTS.md`, the Cursor rule and `types`, print Webflow snippets. |
68
70
 
69
71
  All commands support `-v, --verbose` where applicable.
70
72
 
71
73
  ### Doctor / certificates / autostart
72
74
 
73
- Features marked **(unreleased, CLI 2.3.0)** are not in published npm `latest` (`2.2.7`).
74
-
75
75
  - `doctor` and `certs check` are read-only. They never delete keychain items or certificate files.
76
- - Prefer CDN major pin `@2` in Webflow custom code. Doctor unpinned-CDN warnings (`@latest`, bare `@1`, or unversioned `@stagepass/loader` / `@stagepass/modules` in recommended snippets and in the current project's `README.md`, `stagepass.json`, and `*.html` files directly in the project root and in `snippets/` — non-recursive, regular files ≤ 1 MB, symlinks skipped): **(unreleased, CLI 2.3.0)**.
77
- - `certs renew` **(unreleased, CLI 2.3.0)** is opt-in and confirmation-gated. Site repair only deletes `certificates/local/<linked-domain>` after checks fail. `--root` moves the CA folder to a timestamped backup (never deletes; needs two interactive confirmations without `--yes`, or `--yes --i-understand-root-renewal`). `--yes` alone always aborts for `--root` (TTY or not). Do not combine `--root` with `--remove-orphans`; run them as separate commands. Orphans are removed only by SHA-1 via `renew --remove-orphans`.
76
+ - Prefer CDN major pin `@2` in Webflow custom code. Doctor warns on unpinned CDN URLs (`@latest`, bare `@1`, or unversioned `@stagepass/loader` / `@stagepass/modules` in recommended snippets and in the current project's `README.md`, `stagepass.json`, and `*.html` files directly in the project root and in `snippets/`; non-recursive, regular files ≤ 1 MB, symlinks skipped).
77
+ - `certs renew` is opt-in and confirmation-gated. Site repair only deletes `certificates/local/<linked-domain>` after checks fail. `--root` moves the CA folder to a timestamped backup (never deletes; needs two interactive confirmations without `--yes`, or `--yes --i-understand-root-renewal`). `--yes` alone always aborts for `--root` (TTY or not). Do not combine `--root` with `--remove-orphans`; run them as separate commands. Orphans are removed only by SHA-1 via `renew --remove-orphans`.
78
78
  - Chrome may require Local Network Access permission for public HTTPS pages that load `https://*.sp` assets.
79
79
  - Autostart runs as your user (same privilege model as interactive `caddy start`). `start` kickstarts the agent when present; `stop` bootouts until the next login. If port 443 cannot be bound, `daemon` logs a clear error, may notify, and exits `0` so launchd KeepAlive does not restart-loop. Interactive `start` confirms before signalling any non-caddy listener (name + PID; SIGTERM then optional SIGKILL). Own processes are signalled without elevated rights first; `sudo` only when needed after confirmation. There is no standby `sudo -v`.
80
80
  - `stagepass autostart on` records a launchd-safe `PATH` from `brew --prefix` (Apple Silicon `/opt/homebrew`, Intel `/usr/local`) plus `/usr/bin:/bin:/usr/sbin:/sbin`. It does **not** copy your interactive shell environment. `brew` and `caddy` must resolve to shims under that prefix's `bin`/`sbin` (normal Homebrew Cellar symlinks are fine). Missing Homebrew/Caddy aborts **before** writing the plist.
81
- - Published CLI requires Node `>=18.0.0`. CLI 2.3.0 (unreleased) raises it to `>=20.17.0`.
81
+ - Published CLI requires Node `>=20.17.0`. Node 18 is no longer supported; stay on `@stagepass/cli@2.2.7` if you must remain on Node 18.
82
82
  - Manual macOS checklist: [`TESTING-macos.md`](./TESTING-macos.md).
83
83
 
84
84
  #### macOS permissions (keep these separate)
@@ -111,12 +111,12 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
111
111
  | `--styles scss\|css` | Styles (default: `scss`). |
112
112
  | `--modules` / `--no-modules` | Include `@stagepass/modules` as npm dependency (default: yes; forced on when `--site-modules` lists a module). |
113
113
  | `--site <host>` | Live Webflow site (https) to detect the loaded modules from. Also sets `origin` in `stagepass.json`. |
114
- | `--staging <domain>` | **(unreleased, CLI 2.3.0)** Staging hostname (hostname only; same validation as `--origin`). Stored as `origin`. Must match `--site` when both are set. |
115
- | `--production <domain>` | **(unreleased, CLI 2.3.0)** Optional production hostname. Stored as `production`. When omitted, prints a short hint to add it later via `stagepass link --origin`. |
114
+ | `--staging <domain>` | Staging hostname (hostname only; same validation as `--origin`). Stored as `origin`. Must match `--site` when both are set. |
115
+ | `--production <domain>` | Optional production hostname. Stored as `production`. When omitted, prints a short hint to add it later via `stagepass link --origin`. |
116
116
  | `--site-modules <list>` | Modules the site loads: `none`, `all`, or a comma list of `inject`, `cookies`, `maintenance`. Takes precedence over `--site`. |
117
- | `--php` / `--no-php` | **(unreleased, CLI 2.3.0)** Enable PHP for the project (`api/` + `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
118
- | `--php-examples` / `--no-php-examples` | **(unreleased, CLI 2.3.0)** Include `examples/php/` samples (requires `--php`). Default: off. |
119
- | `--link` / `--no-link` | **(unreleased, CLI 2.3.0)** After scaffolding, run `stagepass link` (macOS only). Default: off; interactive macOS may offer it. |
117
+ | `--php` / `--no-php` | Enable PHP for the project (`api/` + `php_fastcgi` on link). Default: off. Existing linked projects without `"php"` keep PHP on. |
118
+ | `--php-examples` / `--no-php-examples` | Include `examples/php/` samples (requires `--php`). Default: off. |
119
+ | `--link` / `--no-link` | After scaffolding, run `stagepass link` (macOS only). Default: off; interactive macOS may offer it. |
120
120
  | `--git` / `--no-git` | `git init` (default: yes). |
121
121
  | `--remote <url>` | Set `origin` after git init (rejects URLs with embedded credentials). |
122
122
  | `--install` / `--no-install` | Run `npm install` (default: no). |
@@ -125,7 +125,7 @@ Scaffold a project with flags for every choice (interactive prompts only on a TT
125
125
 
126
126
  The name must be DNS-safe (lowercase `a-z`, `0-9`, hyphens; 1 to 63 chars; no leading/trailing hyphen). Existing files are never overwritten. Generated projects include `scripts/build.mjs` (content-hashed `dist/` + SRI `integrity` in `manifest.json`), scripts `build` / `watch` / `dev` (`dev` aliases `watch`), Webflow head/footer snippets (jsDelivr `@2`, loader plus the declared modules), `stagepass.json`, an `AGENTS.md` with the full `sp` API reference, `.cursor/rules/stagepass.mdc`, and a `.gitignore`. `@stagepass/loader` / `@stagepass/modules` are added as `^2` (same major as the CDN pin `@2`; npm installs the newest published 2.x). Per-module types are written only when the published or installed `@stagepass/modules` ships them (2.2.0 and later); otherwise `types` lists the umbrella `@stagepass/modules`.
127
127
 
128
- Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). On published CLI 2.2.7, without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. Staging / production prompts, PHP prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are **(unreleased, CLI 2.3.0)**.
128
+ Interactively (macOS), `new` runs a read-only `doctor` preflight and can offer `stagepass setup` if the local stack looks incomplete (never automatic, never under `--yes` / no-TTY, never sudo by itself). Without a TTY (or with `--yes`) it uses `--site-modules`, then `--site` detection, else `[]` with a hint. Staging / production prompts, PHP prompts, `--staging` detection, and `link` reading `origin` / `production` from `stagepass.json` are part of this release.
129
129
 
130
130
  ### Declared modules (`stagepass.json`)
131
131
 
@@ -188,7 +188,7 @@ Every change is printed as `file: action` (unchanged files are not listed; skipp
188
188
  | `--no-allow-all-origins` | Disable allow-all mode and use the origin allowlist. |
189
189
  | `-v, --verbose` | Show Caddy reload output / errors. |
190
190
 
191
- Published CLI 2.2.7 still needs explicit `link --origin` for CORS (even when `new --site` wrote `origin` into `stagepass.json`). `link` reading `origin` / `production` from `stagepass.json` when no `--origin` / `--remove-origin` flags are passed is **(unreleased, CLI 2.3.0)**. The project's `"php"` flag (when set) controlling whether the Caddy site block includes `php_fastcgi` is also **(unreleased, CLI 2.3.0)**; missing `"php"` keeps the legacy PHP-on behaviour.
191
+ `link` reads `origin` / `production` from `stagepass.json` when no `--origin` / `--remove-origin` flags are passed. You can still pass `--origin` explicitly for CORS. The project's `"php"` flag (when set) controls whether the Caddy site block includes `php_fastcgi`; missing `"php"` keeps the legacy PHP-on behaviour.
192
192
 
193
193
  **`--origin` / `--remove-origin` format:** `example.com`, `www.example.com`, `*.example.com`, or `https://example.com`. Hostnames only (optional leading `*.`); no path, port, or `http://` for live origins.
194
194
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "2.3.0",
3
+ "version": "2.3.1",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
@@ -1,13 +1,15 @@
1
1
  import fs from 'fs-extra';
2
+ import { createRequire } from 'node:module';
2
3
  import chalk from 'chalk';
3
4
  import { defaultExec } from '../lib/exec.js';
4
- import { getCaddyfilePath, getLogsDir } from '../lib/paths.js';
5
+ import { getCaddyfilePath, getDaemonStatePath, getLogsDir, getProjectsPath } from '../lib/paths.js';
5
6
  import { runCertsCheck } from '../lib/certs.js';
6
7
  import { loadProjects } from '../lib/projects.js';
7
- import { getProjectsPath } from '../lib/paths.js';
8
8
  import { ensurePhpFpm } from '../lib/php-fpm.js';
9
9
  import { notifyMac } from '../lib/notify.js';
10
10
 
11
+ const CLI_VERSION = createRequire(import.meta.url)('../../package.json').version;
12
+
11
13
  /**
12
14
  * Detect bind / permission failures that will not self-heal on immediate restart.
13
15
  * LaunchAgent KeepAlive (SuccessfulExit=false) must not restart-loop on these.
@@ -61,6 +63,20 @@ export async function daemon(options = {}) {
61
63
 
62
64
  await fs.ensureDir(options.logsDir || getLogsDir());
63
65
 
66
+ // Doctor reads this to see the version that is actually running (#74).
67
+ if (options.recordState !== false) {
68
+ try {
69
+ const writeFile = options.writeFile || ((p, c) => fs.writeFile(p, c, 'utf8'));
70
+ const version = options.version || CLI_VERSION;
71
+ await writeFile(
72
+ options.statePath || getDaemonStatePath(),
73
+ JSON.stringify({ version, pid: process.pid })
74
+ );
75
+ } catch {
76
+ // diagnostic only
77
+ }
78
+ }
79
+
64
80
  if (!(await pathExists(caddyfilePath))) {
65
81
  log(`Caddyfile missing: ${caddyfilePath}`);
66
82
  log('Refusing to start. Run: stagepass setup && stagepass link');
@@ -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
  };
package/src/lib/doctor.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import fs from 'fs-extra';
2
+ import { createRequire } from 'node:module';
2
3
  import { runProjectSiteChecks } from './doctor-site.js';
3
4
  import path from 'node:path';
4
5
  import { defaultExec, resolveCommand } from './exec.js';
@@ -6,11 +7,14 @@ import {
6
7
  getCaddyfilePath,
7
8
  getProjectsPath,
8
9
  getCaddyRootCaPath,
10
+ getDaemonStatePath,
9
11
  } from './paths.js';
10
12
  import { parseBlocks } from './caddyfile.js';
11
13
  import { loadProjects } from './projects.js';
12
14
  import { runCertsCheck } from './certs.js';
13
- import { getAutostartStatus } from './autostart.js';
15
+ import { getAutostartStatus, isVersionedCellarNodeBin } from './autostart.js';
16
+ import { isPidAlive } from './dev-port.js';
17
+ import { isMacOS } from './platform.js';
14
18
  import {
15
19
  CHROME_LNA_HINT,
16
20
  findUnpinnedCdnSnippets,
@@ -18,6 +22,9 @@ import {
18
22
  scanProjectUnpinnedCdn,
19
23
  } from './cdn-snippets.js';
20
24
 
25
+ const CLI_VERSION = createRequire(import.meta.url)('../../package.json').version;
26
+ const AUTOSTART_ON = 'stagepass autostart on';
27
+
21
28
  /**
22
29
  * @typedef {'ok'|'warn'|'fail'|'info'} CheckStatus
23
30
  * @typedef {{ id: string, status: CheckStatus, message: string, detail?: string }} DoctorCheck
@@ -34,6 +41,50 @@ function check(id, status, message, detail) {
34
41
  return detail ? { id, status, message, detail } : { id, status, message };
35
42
  }
36
43
 
44
+ /** @param {unknown} value */
45
+ function safeVersion(value) {
46
+ return typeof value === 'string' && /^[0-9A-Za-z.+-]{1,32}$/.test(value) ? value : '';
47
+ }
48
+
49
+ /** @param {string} value */
50
+ function unescapeXml(value) {
51
+ return String(value)
52
+ .replace(/&lt;/g, '<')
53
+ .replace(/&gt;/g, '>')
54
+ .replace(/&quot;/g, '"')
55
+ .replace(/&apos;/g, "'")
56
+ .replace(/&amp;/g, '&');
57
+ }
58
+
59
+ /** @param {string} xml @returns {string[]} */
60
+ function plistProgramArguments(xml) {
61
+ const block = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(
62
+ String(xml || '')
63
+ );
64
+ if (!block) return [];
65
+ const args = [];
66
+ const re = /<string>([^<]*)<\/string>/g;
67
+ let m;
68
+ while ((m = re.exec(block[1]))) args.push(unescapeXml(m[1]));
69
+ return args;
70
+ }
71
+
72
+ /**
73
+ * Version recorded by the running daemon, or null when the pid is dead / unreadable.
74
+ * @param {(p: string, enc?: string) => Promise<string>} readFile
75
+ * @param {string} statePath
76
+ */
77
+ async function readRunningDaemonVersion(readFile, statePath) {
78
+ try {
79
+ const data = JSON.parse(String(await readFile(statePath, 'utf8')));
80
+ const version = safeVersion(data && data.version);
81
+ if (!version || !isPidAlive(data.pid)) return null;
82
+ return version;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
37
88
  /**
38
89
  * Parse `lsof -nP -iTCP:443 -sTCP:LISTEN` output.
39
90
  * @param {string} stdout
@@ -462,6 +513,55 @@ export async function runDoctor(opts = {}) {
462
513
  );
463
514
  }
464
515
 
516
+ // #74: plist paths and the running daemon version (macOS, plist on disk).
517
+ if (isMacOS(opts.platform) && autostart.plistExists) {
518
+ let args = [];
519
+ try {
520
+ args = plistProgramArguments(await readFile(autostart.plistPath, 'utf8'));
521
+ } catch {
522
+ args = [];
523
+ }
524
+ const nodeArg = args[0] || '';
525
+ const cliArg = args[1] || '';
526
+ const nodeOk = nodeArg.length > 0 && (await pathExists(nodeArg));
527
+ const cliOk = cliArg.length > 0 && (await pathExists(cliArg));
528
+ if (!nodeOk || !cliOk) {
529
+ const which = [!nodeOk ? 'node' : '', !cliOk ? 'CLI' : ''].filter(Boolean).join(' and ');
530
+ checks.push(check('autostart.paths', 'fail', `LaunchAgent ${which} path is missing`, AUTOSTART_ON));
531
+ } else {
532
+ checks.push(check('autostart.paths', 'ok', 'LaunchAgent node and CLI paths exist'));
533
+ }
534
+ if (isVersionedCellarNodeBin(nodeArg)) {
535
+ checks.push(
536
+ check(
537
+ 'autostart.node',
538
+ 'warn',
539
+ 'LaunchAgent node path is a versioned Homebrew Cellar path',
540
+ AUTOSTART_ON
541
+ )
542
+ );
543
+ } else if (nodeOk) {
544
+ checks.push(check('autostart.node', 'ok', 'LaunchAgent node path is not a versioned Cellar path'));
545
+ }
546
+ const running = await readRunningDaemonVersion(
547
+ readFile,
548
+ opts.daemonStatePath || getDaemonStatePath()
549
+ );
550
+ const cliVersion = safeVersion(opts.cliVersion || CLI_VERSION);
551
+ if (running && cliVersion && running !== cliVersion) {
552
+ checks.push(
553
+ check(
554
+ 'autostart.version',
555
+ 'warn',
556
+ `Daemon version ${running} differs from CLI ${cliVersion}`,
557
+ AUTOSTART_ON
558
+ )
559
+ );
560
+ } else if (running && cliVersion && running === cliVersion) {
561
+ checks.push(check('autostart.version', 'ok', `Daemon version matches CLI ${cliVersion}`));
562
+ }
563
+ }
564
+
465
565
  // CDN snippets: canonical docs + current project snippet files (read-only)
466
566
  const snippets = opts.cdnSnippets || RECOMMENDED_CDN_SNIPPETS;
467
567
  const unpinned = findUnpinnedCdnSnippets(snippets);
package/src/lib/paths.js CHANGED
@@ -31,6 +31,11 @@ export function getDaemonStderrLogPath() {
31
31
  return path.join(getLogsDir(), 'daemon.stderr.log');
32
32
  }
33
33
 
34
+ /** Version and pid of the running `stagepass daemon` (~/.stagepass/daemon.json). */
35
+ export function getDaemonStatePath() {
36
+ return path.join(getStagepassDir(), 'daemon.json');
37
+ }
38
+
34
39
  /** LaunchAgent label (owned GitHub-io reverse DNS; not a third-party domain). */
35
40
  export const LAUNCH_AGENT_LABEL = 'io.github.arobertherz.stagepass';
36
41