@selvajs/cli 4.8.0-beta.10 → 4.8.0-beta.11

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
@@ -8,28 +8,23 @@ CLI for white-label Selva deployments.
8
8
  npx @selvajs/cli my-deployment
9
9
  ```
10
10
 
11
- Interactive scaffolder. Prompts for provider, tenancy, flags, brand name, admin email. Generates `SELVA_HMAC_KEY` + `SELVA_AT_REST_KEY`. Writes `.env`, `ecosystem.config.cjs`, `package.json`. Runs `npm install`.
11
+ Prompts for provider, tenancy, flags, brand name, admin email; generates `SELVA_HMAC_KEY` and `SELVA_AT_REST_KEY`; writes `.env`, `ecosystem.config.cjs`, `package.json`; runs `npm install`. Refuses to overwrite a non-empty directory unless you pass `--force`.
12
12
 
13
13
  ## Operate an existing deployment
14
14
 
15
- After install, the package exposes a `selva` bin:
15
+ Installing adds a `selva` bin, scoped to the deployment directory (needs `.env` or `ecosystem.config.cjs` in the cwd):
16
16
 
17
17
  ```bash
18
- selva init # reconfigure prompts; preserves existing secrets
19
- selva doctor # validate env + providers + paths
18
+ selva init # reconfigure prompts; keeps existing secrets
19
+ selva doctor [--fix] # validate env, providers, Node engine, boot persistence
20
+ selva migrate # bring package.json onto the current layout
20
21
  selva start | stop | restart | logs
21
- selva update # npm update @selvajs/selva + pm2 restart
22
+ selva update # update @selvajs/cli + @selvajs/selva, then restart
22
23
  selva keys rotate hmac # rotate SELVA_HMAC_KEY (logs everyone out)
23
24
  selva keys rotate at-rest # rotate SELVA_AT_REST_KEY (compute API key needs re-entry)
24
25
  ```
25
26
 
26
- All operator commands run inside the deployment directory (the one that contains `.env` and `ecosystem.config.cjs`).
27
-
28
- ## Re-running a command is safe
29
-
30
- - `npx @selvajs/cli` refuses to overwrite a non-empty directory without `--force`.
31
- - `selva init` reads the current `.env`, lets the user edit, and **never** regenerates `SELVA_HMAC_KEY` / `SELVA_AT_REST_KEY` if they're already set.
32
- - A `.selva-version` marker is written so a future CLI version knows which config layout it is looking at and can upgrade it cleanly.
27
+ `selva init` never regenerates `SELVA_HMAC_KEY` or `SELVA_AT_REST_KEY` once they're set — rotating those is `keys rotate`'s job, since it invalidates sessions or encrypted data. A `.selva-version` marker records which CLI version scaffolded the directory, so a later `selva migrate` knows what layout it's upgrading from.
33
28
 
34
29
  ## Relationship to `@selvajs/selva`
35
30
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@selvajs/cli",
3
- "version": "4.8.0-beta.10",
3
+ "version": "4.8.0-beta.11",
4
4
  "description": "Scaffold and operate a Selva white-label deployment. `npx @selvajs/cli <dir>` to bootstrap, `selva <cmd>` to manage.",
5
5
  "license": "MIT",
6
6
  "author": "VektorNode",
@@ -40,6 +40,9 @@
40
40
  "@clack/prompts": "^1.7.0",
41
41
  "picocolors": "^1.1.1"
42
42
  },
43
+ "devDependencies": {
44
+ "pm2": "7.0.3"
45
+ },
43
46
  "scripts": {
44
47
  "start": "node ./bin/cli.js",
45
48
  "selva": "node ./bin/selva.js",
@@ -12,7 +12,10 @@
12
12
 
13
13
  import { existsSync, readFileSync, accessSync, constants } from 'node:fs';
14
14
  import { spawnSync } from 'node:child_process';
15
- import { join, resolve, dirname, delimiter } from 'node:path';
15
+ // These checks only ever run on a Linux host (see the platform gate below), so
16
+ // every path here is POSIX. Using the platform-default `node:path` would build
17
+ // backslash paths and split PATH on `;` when the tests run on Windows.
18
+ import { posix as path } from 'node:path';
16
19
  import { homedir } from 'node:os';
17
20
  import { green, red, yellow, fixable } from './result.js';
18
21
 
@@ -22,10 +25,10 @@ export const systemEnv = {
22
25
  env: () => process.env,
23
26
  homedir,
24
27
  exists: existsSync,
25
- readFile: (path) => readFileSync(path, 'utf8'),
26
- isWritable: (path) => {
28
+ readFile: (target) => readFileSync(target, 'utf8'),
29
+ isWritable: (target) => {
27
30
  try {
28
- accessSync(path, constants.W_OK);
31
+ accessSync(target, constants.W_OK);
29
32
  return true;
30
33
  } catch {
31
34
  return false;
@@ -50,15 +53,15 @@ export function checkBootPersistence(dir, env = systemEnv) {
50
53
  // dump.pm2 is what `pm2 resurrect` replays. Without it the unit starts pm2 and
51
54
  // pm2 starts nothing.
52
55
  function checkSavedProcessList(dir, env) {
53
- const pm2Home = env.env().PM2_HOME ?? join(env.homedir(), '.pm2');
54
- if (env.exists(join(pm2Home, 'dump.pm2'))) {
56
+ const pm2Home = env.env().PM2_HOME ?? path.join(env.homedir(), '.pm2');
57
+ if (env.exists(path.join(pm2Home, 'dump.pm2'))) {
55
58
  return green('pm2 process list saved (dump.pm2 present)');
56
59
  }
57
60
  return yellow(
58
61
  'pm2 process list not saved — run `npx pm2 save` so a reboot can ' +
59
62
  'resurrect the app (nothing to restore without it)',
60
63
  fixable('run `pm2 save` to persist the current process list', () => {
61
- const bin = join(dir, 'node_modules', '.bin', 'pm2');
64
+ const bin = path.join(dir, 'node_modules', '.bin', 'pm2');
62
65
  if (!env.exists(bin)) return red('pm2 not installed in this deployment');
63
66
  const r = env.run(bin, ['save'], { cwd: dir });
64
67
  return (r.status ?? 1) === 0
@@ -89,7 +92,7 @@ function checkSystemdUnit(dir, env) {
89
92
  return [yellow(`pm2 systemd unit present but unreadable (${unitPath})`)];
90
93
  }
91
94
 
92
- const localPm2 = join(dir, 'node_modules', 'pm2', 'bin', 'pm2');
95
+ const localPm2 = path.join(dir, 'node_modules', 'pm2', 'bin', 'pm2');
93
96
  const execStart = /^ExecStart=(.+)$/m.exec(unit)?.[1] ?? '';
94
97
  if (execStart.includes(localPm2)) {
95
98
  return [green('pm2 systemd boot unit installed (uses deployment-local pm2)')];
@@ -102,7 +105,7 @@ function checkSystemdUnit(dir, env) {
102
105
  `expected: ${localPm2} resurrect\n ` +
103
106
  `Reboots will resurrect via the wrong pm2 (version skew). Re-run startup ` +
104
107
  `with the local binary:\n ` +
105
- `sudo env PATH=$PATH:${join(dir, 'node_modules', '.bin')} ${localPm2} ` +
108
+ `sudo env PATH=$PATH:${path.join(dir, 'node_modules', '.bin')} ${localPm2} ` +
106
109
  `startup systemd -u $USER --hp $HOME`
107
110
  )
108
111
  ];
@@ -116,14 +119,14 @@ function checkStrayGlobalPm2(dir, env) {
116
119
  // Only offer the removal when we could actually perform it. A global
117
120
  // install under /usr is root-owned; attempting it would half-fail and
118
121
  // leave the operator worse informed than a printed instruction.
119
- const writable = env.isWritable(dirname(globalPm2));
122
+ const writable = env.isWritable(path.dirname(globalPm2));
120
123
 
121
124
  return [
122
125
  yellow(
123
126
  `a pm2 outside this deployment is on PATH (${globalPm2}) — it can fork a ` +
124
127
  `mismatched daemon and trigger skew. Prefer \`npm run\` wrappers / \`npx pm2\` ` +
125
128
  `from this directory; consider \`npm uninstall -g pm2\`.` +
126
- (writable ? '' : `\n (${dirname(globalPm2)} is not writable — needs sudo)`),
129
+ (writable ? '' : `\n (${path.dirname(globalPm2)} is not writable — needs sudo)`),
127
130
  writable
128
131
  ? fixable(`uninstall the global pm2 at ${globalPm2}`, () => {
129
132
  const r = env.run('npm', ['uninstall', '-g', 'pm2'], {});
@@ -136,13 +139,12 @@ function checkStrayGlobalPm2(dir, env) {
136
139
  ];
137
140
  }
138
141
 
139
- // Scan PATH for a stray pm2 binary (read-only).
140
142
  export function findGlobalPm2(dir, env = systemEnv) {
141
- const localBin = resolve(dir, 'node_modules', '.bin');
142
- const dirs = (env.env().PATH ?? '').split(delimiter).filter(Boolean);
143
+ const localBin = path.resolve(dir, 'node_modules', '.bin');
144
+ const dirs = (env.env().PATH ?? '').split(path.delimiter).filter(Boolean);
143
145
  for (const d of dirs) {
144
- if (resolve(d) === localBin) continue;
145
- const candidate = join(d, 'pm2');
146
+ if (path.resolve(d) === localBin) continue;
147
+ const candidate = path.join(d, 'pm2');
146
148
  if (env.exists(candidate)) return candidate;
147
149
  }
148
150
  return null;
@@ -24,11 +24,7 @@ export function checkSecret(value, label) {
24
24
  return green(label);
25
25
  }
26
26
 
27
- /**
28
- * The three provider slots, lowercased and defaulted the same way the runtime
29
- * defaults them. Returned alongside the checks because the caller decides which
30
- * provider-specific checks to run from it.
31
- */
27
+ // Lowercased and defaulted the same way create-selva-providers.ts defaults them.
32
28
  export function resolveProviders(env) {
33
29
  return {
34
30
  auth: (env.SELVA_AUTH_PROVIDER ?? 'local').toLowerCase(),
@@ -69,13 +65,9 @@ export function checkOrigin(env) {
69
65
  return green(`ORIGIN=${env.ORIGIN}`);
70
66
  }
71
67
 
72
- /**
73
- * Report env vars that were renamed or replaced.
74
- *
75
- * A rename is auto-fixable (`selva migrate` rewrites the key). A replacement
76
- * encodes a value in the new name, so migrate leaves it alone rather than
77
- * guessing — it is reported here and nowhere else.
78
- */
68
+ // A rename is auto-fixable (`selva migrate` rewrites the key). A replacement
69
+ // encodes a value in the new name, so migrate leaves it alone rather than
70
+ // guessing — it's reported here and nowhere else.
79
71
  export function checkDeprecatedEnv(env) {
80
72
  const checks = [];
81
73
 
@@ -0,0 +1,289 @@
1
+ // What the host provides versus what the deployment brings itself.
2
+ //
3
+ // The split trips operators up: Node and npm come from the host (distro
4
+ // packages, nvm, whatever), pm2 comes from the deployment. Installing pm2 from
5
+ // apt or `npm i -g` looks like the tidy thing to do and produces a daemon that
6
+ // silently fights the local one. These checks name which side of the line each
7
+ // tool is on, so the answer is on screen instead of in a support thread.
8
+ //
9
+ // checkNodeEngine (doctor.js) already validates the running Node against
10
+ // engines.node. Nothing here repeats that — this covers what it can't see: npm,
11
+ // the pm2 install itself, and whether the Node running doctor is the same one
12
+ // pm2 launched the app under.
13
+
14
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { join } from 'node:path';
17
+ import { homedir } from 'node:os';
18
+ import { green, red, yellow } from './result.js';
19
+ import { PM2_VERSION } from '../deployment-package.js';
20
+
21
+ /** The real OS. Tests pass a stand-in with the same shape. */
22
+ export const runtimeEnv = {
23
+ platform: () => process.platform,
24
+ env: () => process.env,
25
+ homedir,
26
+ exists: existsSync,
27
+ readFile: (path) => readFileSync(path, 'utf8'),
28
+ realpath: (path) => {
29
+ try {
30
+ return realpathSync(path);
31
+ } catch {
32
+ return path;
33
+ }
34
+ },
35
+ execPath: () => process.execPath,
36
+ // Signal 0 probes liveness without touching the process. EPERM means it
37
+ // exists but belongs to another user — alive for our purposes.
38
+ processAlive: (pid) => {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ } catch (err) {
43
+ return err?.code === 'EPERM';
44
+ }
45
+ },
46
+ run: (cmd, args, opts) =>
47
+ spawnSync(cmd, args, {
48
+ ...opts,
49
+ encoding: 'utf8',
50
+ shell: process.platform === 'win32'
51
+ })
52
+ };
53
+
54
+ export function checkRuntimeEnvironment(dir, env = runtimeEnv) {
55
+ return [
56
+ checkNpm(env),
57
+ checkNodeProvenance(env),
58
+ ...checkPm2Install(dir, env),
59
+ ...checkPm2Daemon(dir, env)
60
+ ];
61
+ }
62
+
63
+ // ── npm ─────────────────────────────────────────────────────────────────
64
+
65
+ // Debian's `nodejs` package doesn't always pull in `npm`, and some distro
66
+ // splits ship an npm several majors behind the Node beside it. Both only
67
+ // surface at `selva update`, which is the worst moment to discover it.
68
+ const MIN_NPM_MAJOR = 10;
69
+
70
+ function checkNpm(env) {
71
+ const probe = env.run('npm', ['--version'], {});
72
+ const version = String(probe.stdout ?? '')
73
+ .trim()
74
+ .split('\n')
75
+ .pop();
76
+
77
+ if ((probe.status ?? 1) !== 0 || !/^\d+\.\d+\.\d+/.test(version ?? '')) {
78
+ return red(
79
+ 'npm not found on PATH — `selva update` and `npm install` cannot run.\n ' +
80
+ 'On Debian/Ubuntu the `nodejs` package does not always include it. Install\n ' +
81
+ 'Node 24 from NodeSource, which bundles a matching npm:\n ' +
82
+ 'curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs'
83
+ );
84
+ }
85
+
86
+ const major = Number(/^(\d+)\./.exec(version)[1]);
87
+ if (major < MIN_NPM_MAJOR) {
88
+ return yellow(
89
+ `npm ${version} is older than the Node beside it usually ships (expected >= ${MIN_NPM_MAJOR}).\n ` +
90
+ 'A distro-split npm can resolve dependencies the runtime does not expect.\n ' +
91
+ 'Install Node from NodeSource so npm and Node come from one source.'
92
+ );
93
+ }
94
+ return green(`npm ${version} on PATH`);
95
+ }
96
+
97
+ // ── Node provenance ─────────────────────────────────────────────────────
98
+
99
+ // Which Node runs the app is decided by pm2's environment, not by the shell
100
+ // running doctor. When those differ — a distro Node on PATH for the login
101
+ // shell, an nvm Node for the daemon, or the reverse — doctor validates a
102
+ // version the app never uses, and engines.node passes while production runs
103
+ // something else entirely.
104
+ function checkNodeProvenance(env) {
105
+ const running = env.realpath(env.execPath());
106
+ const source = describeNodeSource(running);
107
+
108
+ const which = env.run(env.platform() === 'win32' ? 'where' : 'which', ['node'], {});
109
+ const onPath = String(which.stdout ?? '')
110
+ .trim()
111
+ .split('\n')[0]
112
+ ?.trim();
113
+
114
+ if (!onPath) {
115
+ return yellow(`Node v${process.versions.node} at ${running} (${source}) — not resolvable on PATH`);
116
+ }
117
+
118
+ if (env.realpath(onPath) === running) {
119
+ return green(`Node v${process.versions.node} — ${source} (${running})`);
120
+ }
121
+
122
+ return yellow(
123
+ `Two Node installations are in play: this shell resolves \`node\` to ${env.realpath(onPath)},\n ` +
124
+ `but doctor is running under ${running} (${source}). pm2 launches the app with the\n ` +
125
+ `Node it inherited when the daemon started, which may be neither. Confirm with:\n ` +
126
+ `npx pm2 describe selva-compute | grep -i "node.js version"`
127
+ );
128
+ }
129
+
130
+ // nvm/fnm-managed Nodes disappear for a systemd unit that starts before the
131
+ // user's shell profile runs — worth naming the manager rather than the path.
132
+ function describeNodeSource(path) {
133
+ const p = path.replace(/\\/g, '/');
134
+ if (/\/\.nvm\//.test(p)) return 'nvm-managed';
135
+ if (/\/\.fnm\/|\/fnm_multishells\//.test(p)) return 'fnm-managed';
136
+ if (/\/\.volta\//.test(p)) return 'volta-managed';
137
+ if (/^\/usr\/bin\/|^\/bin\//.test(p)) return 'distro package';
138
+ if (/^\/usr\/local\//.test(p)) return 'manual /usr/local install';
139
+ if (/\/snap\//.test(p)) return 'snap package';
140
+ return 'unknown source';
141
+ }
142
+
143
+ // ── pm2 install ─────────────────────────────────────────────────────────
144
+
145
+ // The deployment pins pm2 exactly (see deployment-package.js). This verifies
146
+ // the pin actually landed — a hand-edited package.json, a partial install, or
147
+ // an operator who ran `npm i -g pm2` and deleted the local one all end here.
148
+ function checkPm2Install(dir, env) {
149
+ const out = [];
150
+ const pkgPath = join(dir, 'node_modules', 'pm2', 'package.json');
151
+
152
+ if (!env.exists(pkgPath)) {
153
+ out.push(
154
+ red(
155
+ `pm2 is not installed in this deployment (expected ${join(dir, 'node_modules', 'pm2')}).\n ` +
156
+ 'Selva ships its own pinned pm2 on purpose — the `selva` commands refuse to fall\n ' +
157
+ 'back to a global one, because two pm2 versions sharing a daemon hang restarts.\n ' +
158
+ 'Fix: npm install'
159
+ )
160
+ );
161
+ return out;
162
+ }
163
+
164
+ let installed = null;
165
+ try {
166
+ installed = JSON.parse(env.readFile(pkgPath)).version ?? null;
167
+ } catch {
168
+ // Unreadable package.json — reported below as an unverifiable version.
169
+ }
170
+
171
+ if (!installed) {
172
+ out.push(yellow('pm2 installed but its version is unreadable — cannot verify the pin'));
173
+ } else if (installed === PM2_VERSION) {
174
+ out.push(green(`pm2 ${installed} installed locally (matches the pinned version)`));
175
+ } else {
176
+ out.push(
177
+ yellow(
178
+ `pm2 ${installed} is installed but this scaffold pins ${PM2_VERSION}.\n ` +
179
+ 'The pin is exact because pm2 CLI and daemon must match. Realign it:\n ' +
180
+ `npm install pm2@${PM2_VERSION} && npx pm2 update`
181
+ )
182
+ );
183
+ }
184
+
185
+ // A pm2 listed in dependencies with a range instead of the exact pin means
186
+ // package.json was hand-edited; the next `npm install` silently drifts again.
187
+ const declared = readDeclaredPm2(dir, env);
188
+ if (declared && declared !== PM2_VERSION) {
189
+ out.push(
190
+ yellow(
191
+ `package.json declares pm2 "${declared}" rather than the exact pin ${PM2_VERSION}.\n ` +
192
+ 'A range lets a later `npm install` adopt a version the running daemon is not.\n ' +
193
+ 'Run `selva migrate` to restore the canonical package.json.'
194
+ )
195
+ );
196
+ }
197
+
198
+ return out;
199
+ }
200
+
201
+ function readDeclaredPm2(dir, env) {
202
+ try {
203
+ const pkg = JSON.parse(env.readFile(join(dir, 'package.json')));
204
+ return pkg.dependencies?.pm2 ?? null;
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+
210
+ // ── pm2 daemon ──────────────────────────────────────────────────────────
211
+
212
+ // Reports three distinct states rather than pass/fail: no daemon (fine,
213
+ // nothing started yet), a matching daemon, or a daemon a foreign pm2 owns.
214
+ //
215
+ // `pm2 ping` SPAWNS a daemon when none is running, and doctor must stay
216
+ // read-only — so liveness is checked via pm2.pid + signal 0 first, and pm2
217
+ // itself is only invoked once a live daemon is confirmed.
218
+ //
219
+ // The daemon-is-newer direction is red and deliberately offers no fix: `pm2
220
+ // update` would downgrade the daemon and drop its process table, leaving
221
+ // selva-compute unregistered. Same reasoning as ensurePm2InSync in commands/pm2.js.
222
+ function checkPm2Daemon(dir, env) {
223
+ const bin = join(dir, 'node_modules', '.bin', env.platform() === 'win32' ? 'pm2.cmd' : 'pm2');
224
+ if (!env.exists(bin)) return [];
225
+
226
+ const pm2Home = env.env().PM2_HOME ?? join(env.homedir(), '.pm2');
227
+ const pidPath = join(pm2Home, 'pm2.pid');
228
+ if (!env.exists(pidPath)) {
229
+ return [yellow('pm2 daemon is not running — it starts on `selva start`')];
230
+ }
231
+ let pid = NaN;
232
+ try {
233
+ pid = Number(String(env.readFile(pidPath)).trim());
234
+ } catch {
235
+ // Unreadable pid file — fall through to the stale case.
236
+ }
237
+ if (!Number.isInteger(pid) || pid <= 0 || !env.processAlive(pid)) {
238
+ return [yellow('pm2 daemon is not running (stale pm2.pid) — it starts on `selva start`')];
239
+ }
240
+
241
+ const probe = env.run(bin, ['ping'], { cwd: dir });
242
+ const output = String(probe.stdout ?? '') + String(probe.stderr ?? '');
243
+
244
+ if (!/out-of-date/i.test(output)) {
245
+ if (/pong/i.test(output)) return [green('pm2 daemon responds and matches the local pm2')];
246
+ return [yellow('pm2 daemon did not answer `pm2 ping` — check `npx pm2 ping` by hand')];
247
+ }
248
+
249
+ const { daemon, local } = parseSkew(output);
250
+ if (daemon && local && compareVersions(daemon, local) > 0) {
251
+ return [
252
+ red(
253
+ `The running pm2 daemon (v${daemon}) is NEWER than this deployment's pm2 (v${local}),\n ` +
254
+ 'so a pm2 from outside the deployment owns it. `pm2 update` would downgrade the\n ' +
255
+ 'daemon and drop its process table, so `selva start` refuses outright.\n ' +
256
+ 'Resolve it (the app goes down briefly):\n ' +
257
+ `npx pm2 kill && sudo npm uninstall -g pm2 && npm install && npm start\n ` +
258
+ 'Then re-run: npx pm2 save && npx pm2 startup systemd -u $USER --hp $HOME'
259
+ )
260
+ ];
261
+ }
262
+
263
+ return [
264
+ yellow(
265
+ `pm2 daemon (v${daemon ?? 'unknown'}) differs from the local pm2 (v${local ?? PM2_VERSION}).\n ` +
266
+ 'Resync it — this briefly restarts managed processes: npx pm2 update'
267
+ )
268
+ ];
269
+ }
270
+
271
+ function parseSkew(output) {
272
+ // eslint-disable-next-line no-control-regex -- pm2 colourises via chalk on a TTY
273
+ const clean = output.replace(/\[[0-9;]*m/g, '');
274
+ return {
275
+ daemon: /In memory PM2 version:\s*v?(\d+\.\d+\.\d+)/i.exec(clean)?.[1] ?? null,
276
+ local: /Local PM2 version:\s*v?(\d+\.\d+\.\d+)/i.exec(clean)?.[1] ?? null
277
+ };
278
+ }
279
+
280
+ function compareVersions(a, b) {
281
+ const [x, y] = [a.split('.').map(Number), b.split('.').map(Number)];
282
+ for (let i = 0; i < 3; i++) {
283
+ if (x[i] > y[i]) return 1;
284
+ if (x[i] < y[i]) return -1;
285
+ }
286
+ return 0;
287
+ }
288
+
289
+ export { describeNodeSource, compareVersions, MIN_NPM_MAJOR };
package/src/cli.js CHANGED
@@ -67,7 +67,7 @@ function printHelp() {
67
67
  ' stop pm2 stop selva-compute',
68
68
  ' restart pm2 restart selva-compute --update-env',
69
69
  ' logs pm2 logs selva-compute',
70
- ' update npm update @selvajs/selva + restart',
70
+ ' update npm update @selvajs/cli + @selvajs/selva, then restart',
71
71
  ' migrate Bring package.json onto the current layout',
72
72
  ' keys rotate <hmac|at-rest> Rotate a secret in .env (destructive)',
73
73
  '',
@@ -1,6 +1,5 @@
1
- // Scaffold a fresh deployment: write .env (merged from template + prompts),
2
- // ecosystem.config.cjs, package.json, and bootstrap node_modules. Runtime
3
- // templates are the source of truth; providers are env-driven.
1
+ // Scaffolds a fresh deployment: package.json, node_modules, .env (merged from
2
+ // template + prompts), and ecosystem.config.cjs.
4
3
 
5
4
  import { writeFileSync, existsSync, mkdirSync, readFileSync, cpSync } from 'node:fs';
6
5
  import { resolve, join, basename, dirname } from 'node:path';
@@ -22,12 +21,10 @@ import { satisfiesNodeRange } from '../node-range.js';
22
21
  export async function runCreate(argv) {
23
22
  const { dir: rawDir, force, skipInstall, yes } = parseArgs(argv);
24
23
 
25
- // Scaffolding under too old a Node produces a deployment that installs
26
- // cleanly and passes its health check, then fails only under real traffic —
27
- // npm treats an engine mismatch as a warning unless engine-strict is set,
28
- // which no deployment sets (issue #176). Refuse at the one moment the
29
- // operator is still choosing their environment. The floor comes from this
30
- // CLI's own engines.node, so a bump can't leave a stale copy behind.
24
+ // Scaffolding under too old a Node installs and passes the health check,
25
+ // then fails only under real traffic — npm treats an engine mismatch as a
26
+ // warning, not an error, unless engine-strict is set, which no deployment
27
+ // sets. Refuse now, while the operator is still choosing their environment.
31
28
  const required = requiredNodeRange();
32
29
  if (required && satisfiesNodeRange(process.versions.node, required) === false) {
33
30
  console.error(
@@ -50,19 +47,18 @@ export async function runCreate(argv) {
50
47
  }
51
48
  mkdirSync(targetDir, { recursive: true });
52
49
 
53
- // --yes or CI=1 skips prompts (unattended bootstrap).
54
50
  const nonInteractive = yes || envBool(process.env.CI);
55
51
  const values = nonInteractive
56
52
  ? collectConfigFromEnv(process.env)
57
53
  : await collectConfig({ defaults: {}, mode: 'create' });
58
54
 
59
- // Generate fresh secrets (stable across restarts; init refuses to regen).
60
55
  values.SELVA_HMAC_KEY = generateKey();
61
56
  values.SELVA_AT_REST_KEY = generateKey();
62
57
 
63
58
  const deployName = basename(targetDir);
64
59
 
65
- // Write package.json, then install (need templates from @selvajs/selva).
60
+ // package.json first: npm install needs it, and the runtime templates below
61
+ // only exist once @selvajs/selva is installed into node_modules.
66
62
  const pkgJson = JSON.stringify(buildDeploymentPackageJson({ name: deployName }), null, 2);
67
63
  writeFileSync(join(targetDir, 'package.json'), pkgJson + '\n', 'utf8');
68
64
 
@@ -74,7 +70,6 @@ export async function runCreate(argv) {
74
70
  );
75
71
  }
76
72
 
77
- // Copy templates from installed runtime.
78
73
  const envTemplatePath = runtimeTemplatePath(targetDir, '.env.example');
79
74
  const ecosystemTemplatePath = runtimeTemplatePath(targetDir, 'ecosystem.config.cjs');
80
75
  if (skipInstall || !existsSync(envTemplatePath)) {
@@ -110,21 +105,17 @@ export async function runCreate(argv) {
110
105
  );
111
106
  }
112
107
 
113
- // Stream npm output with live progress; on failure, show tail for debugging.
114
- // Cache-bust hint: surface broken versions like @selvajs/selva@0.10.2.
115
108
  function runNpmInstall(cwd) {
116
109
  return new Promise((resolveP, rejectP) => {
117
110
  const s = p.spinner();
118
111
  s.start('Installing dependencies (this can take a minute)');
119
112
 
120
- // Keep last 80 lines for failure output.
121
113
  const tail = [];
122
114
  const remember = (line) => {
123
115
  tail.push(line);
124
116
  if (tail.length > 80) tail.shift();
125
117
  };
126
118
 
127
- // Extract progress milestones (reify: lines, package count).
128
119
  const updateProgress = (line) => {
129
120
  const trimmed = line.trim();
130
121
  if (!trimmed) return;
@@ -140,7 +131,7 @@ function runNpmInstall(cwd) {
140
131
  if (/^npm (WARN|error|notice)/.test(trimmed)) return;
141
132
  };
142
133
 
143
- // Spawn with --loglevel=info for reify: progress; pipe stdout/stderr for live updates.
134
+ // --loglevel=info is what makes npm print the reify: lines updateProgress matches on.
144
135
  const child = spawn('npm', ['install', '--loglevel=info'], {
145
136
  cwd,
146
137
  stdio: ['ignore', 'pipe', 'pipe'],
@@ -184,8 +175,8 @@ function runNpmInstall(cwd) {
184
175
  }
185
176
  s.stop(pc.red(`npm install failed (exit ${code})`));
186
177
 
187
- // Show what npm actually said. Without this the operator has to
188
- // dig through ~/.npm/_logs/*-debug-0.log to find a single line.
178
+ // Without this the operator has to dig through ~/.npm/_logs/*-debug-0.log
179
+ // to find out what actually went wrong.
189
180
  console.error('');
190
181
  console.error(pc.dim('── last lines of npm output ──'));
191
182
  for (const line of tail) console.error(line);