easy-devops 1.4.0 → 1.4.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/install.bat CHANGED
@@ -21,18 +21,25 @@ if errorlevel 1 (
21
21
  exit /b 1
22
22
  )
23
23
 
24
- :: Verify minimum PowerShell version (5.1)
25
- for /f "usebackq tokens=*" %%v in (
26
- `powershell.exe -NoProfile -Command "$PSVersionTable.PSVersion.Major" 2^>nul`
27
- ) do set PS_MAJOR=%%v
24
+ :: Verify minimum PowerShell version (5.1). Windows PowerShell 5.0 and the
25
+ :: 4.x that ships with older Windows releases cannot run install.ps1.
26
+ for /f "usebackq tokens=1,2 delims=." %%a in (
27
+ `powershell.exe -NoProfile -Command "$PSVersionTable.PSVersion.Major.ToString() + '.' + $PSVersionTable.PSVersion.Minor.ToString()" 2^>nul`
28
+ ) do (
29
+ set PS_MAJOR=%%a
30
+ set PS_MINOR=%%b
31
+ )
28
32
 
29
33
  if not defined PS_MAJOR (
30
34
  echo Error: Could not determine PowerShell version. >&2
31
35
  exit /b 1
32
36
  )
33
- if %PS_MAJOR% LSS 5 (
34
- echo Error: PowerShell 5.1 or later is required. Found version %PS_MAJOR%. >&2
35
- echo Please upgrade PowerShell: https://github.com/PowerShell/PowerShell/releases >&2
37
+ if not defined PS_MINOR set PS_MINOR=0
38
+ set /a PS_VERSION_NUM=PS_MAJOR*100+PS_MINOR
39
+ if %PS_VERSION_NUM% LSS 501 (
40
+ echo Error: PowerShell 5.1 or later is required. Found %PS_MAJOR%.%PS_MINOR%. >&2
41
+ echo Install Windows Management Framework 5.1, which upgrades Windows PowerShell to 5.1: >&2
42
+ echo https://www.microsoft.com/download/details.aspx?id=54616 >&2
36
43
  exit /b 1
37
44
  )
38
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "easy-devops",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
4
4
  "description": "A unified DevOps management tool with CLI and web dashboard for managing Nginx, SSL certificates, deployment apps, and Node.js on Linux and Windows servers.",
5
5
  "keywords": [
6
6
  "devops",
@@ -32,6 +32,8 @@ import {
32
32
  } from '../../core/hubLink.js';
33
33
  import { inspect } from '../../core/daemon/lock.js';
34
34
  import { connectToDaemon } from '../../core/daemon/ipc.js';
35
+ import { readAgentStateFromFile } from '../../core/daemon/stateFile.js';
36
+ import { getDataDir } from '../../core/platform.js';
35
37
  import { page, pause, BACK } from '../ui/page.js';
36
38
 
37
39
  const ACTIONS = ['connect', 'status', 'unlink'];
@@ -75,6 +77,11 @@ function say(line = '') {
75
77
  * frames over IPC (server → client only). Its hello frame carries the state at
76
78
  * connect time, so a CLI that starts after the agent connected still sees it.
77
79
  *
80
+ * In Windows Server mode the pipe belongs to NT SERVICE\EasyDevOps and the CLI
81
+ * cannot open it, so the same state is also read from the file the running
82
+ * daemon keeps in the data directory (core/daemon/stateFile.js) — trusted only
83
+ * while its pid holds the live daemon lock. Whichever answers first wins.
84
+ *
78
85
  * @param {Object} opts
79
86
  * @param {number} opts.timeoutMs
80
87
  * @param {(state: Object|null) => boolean} [opts.until]
@@ -86,16 +93,30 @@ function waitForAgentState({ timeoutMs, until = () => false }) {
86
93
  let finished = false;
87
94
  let client = null;
88
95
 
96
+ const dataDir = getDataDir();
97
+ let filePoll = null;
98
+
89
99
  const finish = (timedOut) => {
90
100
  if (finished) return;
91
101
  finished = true;
92
102
  clearTimeout(timer);
103
+ clearInterval(filePoll);
93
104
  try { client?.close(); } catch { /* already closed */ }
94
105
  resolve({ state: latest, timedOut });
95
106
  };
96
107
 
97
108
  const timer = setTimeout(() => finish(true), timeoutMs);
98
109
 
110
+ const fromFile = () => {
111
+ if (finished) return;
112
+ const state = readAgentStateFromFile({ dataDir });
113
+ if (!state) return;
114
+ latest = state;
115
+ if (until(latest)) finish(false);
116
+ };
117
+ fromFile();
118
+ filePoll = setInterval(fromFile, 500);
119
+
99
120
  client = connectToDaemon({
100
121
  onEvent(event, payload) {
101
122
  if (finished) return;
@@ -172,8 +172,16 @@ export async function showStatus() {
172
172
  const daemonDot = d.running ? dot(true) : s.stoppedByUser ? chalk.yellow('●') : dot(false);
173
173
  console.log(` Daemon ${daemonDot} ${daemonLine}`);
174
174
 
175
+ // Clean restarts (a stop, restart, update or repair) and crash restarts are
176
+ // told apart: only the second kind is a problem, and only it can make a
177
+ // crash loop.
175
178
  if (s.service.restarts) {
176
- console.log(` Restarts ${s.service.crashLooping ? chalk.red(s.service.restarts) : s.service.restarts}`);
179
+ const crashes = s.service.crashRestarts ?? 0;
180
+ const clean = s.service.cleanRestarts ?? (s.service.restarts - crashes);
181
+ const parts = [];
182
+ if (clean) parts.push(`${clean} clean (stop/restart)`);
183
+ if (crashes) parts.push(s.service.crashLooping ? chalk.red(`${crashes} after a crash`) : `${crashes} after a crash`);
184
+ console.log(` Restarts ${parts.join(', ')} ${chalk.gray('in the last 10 min')}`);
177
185
  }
178
186
 
179
187
  console.log(` Data directory ${chalk.gray(s.dataDir)}${s.serverMode ? chalk.gray(' (server mode)') : ''}`);
@@ -252,7 +260,30 @@ async function doInstall() {
252
260
  message: 'Install in Server mode?',
253
261
  default: true,
254
262
  }]);
255
- mode = confirmServer ? service.MODES.SERVER : service.MODES.PERSONAL;
263
+ if (confirmServer) {
264
+ mode = service.MODES.SERVER;
265
+ } else {
266
+ // Allowed, but not without saying what it costs on a server: Personal
267
+ // mode is tied to this user's logon session.
268
+ console.log();
269
+ console.log(' ' + chalk.yellow('Personal mode instead:'));
270
+ console.log(' ' + chalk.gray('• It only runs while this user is logged in.'));
271
+ console.log(' ' + chalk.gray('• Signing out of RDP stops it; disconnecting the RDP window keeps it running.'));
272
+ console.log(' ' + chalk.gray('• It does not start at boot before someone logs in.'));
273
+ console.log();
274
+
275
+ const { confirmPersonal } = await inquirer.prompt([{
276
+ type: 'confirm',
277
+ name: 'confirmPersonal',
278
+ message: 'Install in Personal mode?',
279
+ default: true,
280
+ }]);
281
+ if (!confirmPersonal) {
282
+ console.log(' ' + chalk.gray('Nothing was changed.'));
283
+ return 0;
284
+ }
285
+ mode = service.MODES.PERSONAL;
286
+ }
256
287
  } else {
257
288
  const { chosen } = await inquirer.prompt([{
258
289
  type: 'list',
@@ -351,6 +382,8 @@ async function doInstall() {
351
382
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
352
383
  }
353
384
  console.log();
385
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
386
+ console.log();
354
387
  return 1;
355
388
  }
356
389
 
@@ -359,7 +392,8 @@ async function doInstall() {
359
392
 
360
393
  if (result.migrated) {
361
394
  console.log(' ' + chalk.gray(`Data moved to ${result.dataDir}`));
362
- if (result.backup) console.log(' ' + chalk.gray(`Backup kept at ${result.backup}`));
395
+ const original = service.describeOriginal(result);
396
+ console.log(' ' + chalk.gray(`${original[0].toUpperCase()}${original.slice(1)}.`));
363
397
  }
364
398
 
365
399
  if (result.legacy?.removed?.length) {
@@ -393,6 +427,17 @@ async function doInstall() {
393
427
  console.log(' ' + chalk.gray(`Daemon reported in after ${Math.round(result.daemon.waitedMs / 1000)}s (pid ${result.daemon.pid})`));
394
428
  }
395
429
 
430
+ // Out of waiting time while Windows reports the service RUNNING: installed,
431
+ // just slow to initialise on its first start. Not a failure, so the status
432
+ // table (which would show the daemon as not yet running) is not printed.
433
+ if (result.stillInitialising) {
434
+ console.log(' ' + chalk.yellow('Started, still initialising.'));
435
+ console.log(' ' + chalk.gray('The first start can be slow while Windows scans the new runtime.'));
436
+ console.log(' ' + chalk.gray('Check with ') + chalk.white('ezz service status') + chalk.gray(' in a minute.'));
437
+ console.log();
438
+ return 0;
439
+ }
440
+
396
441
  console.log();
397
442
  return showStatus();
398
443
  }
@@ -671,6 +716,8 @@ async function doStart() {
671
716
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
672
717
  }
673
718
  console.log();
719
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
720
+ console.log();
674
721
  return 1;
675
722
  }
676
723
 
@@ -769,6 +816,8 @@ async function doRepair() {
769
816
  console.log(' ' + chalk.gray('No password is needed — only elevation.'));
770
817
  }
771
818
  console.log();
819
+ console.log(' ' + chalk.gray('Troubleshooting: https://easy-devops.devxor.team/docs/troubleshooting'));
820
+ console.log();
772
821
  return 1;
773
822
  }
774
823
 
@@ -35,6 +35,8 @@ import { startIpcServer } from './ipc.js';
35
35
  import { inspect } from './lock.js';
36
36
  import { watchForStop } from './stopRequest.js';
37
37
  import { getHubAgentStatus } from '../hub/agent.js';
38
+ import { subscribe } from '../jobs/bus.js';
39
+ import { writeDaemonState, removeDaemonState } from './stateFile.js';
38
40
  import { loadConfig } from '../config.js';
39
41
  import { ensureCode as ensureSetupCode, describe as describeSetupCode } from '../setupCode.js';
40
42
 
@@ -115,6 +117,14 @@ export async function startDaemon({
115
117
  const agent = getHubAgentStatus();
116
118
  log(` hub agent : ${agent?.status ?? 'unknown'}`);
117
119
 
120
+ // The same agent state, in the data directory, for a CLI that cannot open
121
+ // the pipe — in Windows Server mode it belongs to NT SERVICE\EasyDevOps. See
122
+ // core/daemon/stateFile.js. Rewritten on every transition the bus carries.
123
+ writeDaemonState({ dataDir, pid: process.pid, version, hub: agent });
124
+ const unsubscribeState = subscribe('hub:agentState', (payload) => {
125
+ writeDaemonState({ dataDir, pid: process.pid, version, hub: payload });
126
+ });
127
+
118
128
  // The first-run setup code, while the dashboard still has no password.
119
129
  // The daemon's stdout IS the service log (WinSW, systemd, the Startup
120
130
  // supervisor all capture it), which is the second of the two places the
@@ -150,6 +160,8 @@ export async function startDaemon({
150
160
  stopping = (async () => {
151
161
  log('Stopping...');
152
162
  stopWatch.stop();
163
+ try { unsubscribeState?.(); } catch { /* best effort */ }
164
+ removeDaemonState({ dataDir, pid: process.pid });
153
165
  if (ipc) {
154
166
  try { await ipc.close(); } catch { /* best effort */ }
155
167
  }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * core/daemon/stateFile.js
3
+ *
4
+ * The daemon's public state, written to a file in the data directory.
5
+ *
6
+ * ── Why a file when there is an IPC channel ────────────────────────────────
7
+ *
8
+ * In Windows Server mode the daemon runs as `NT SERVICE\EasyDevOps`, and the
9
+ * named pipe it creates carries that account's default security: an
10
+ * Administrator's CLI cannot open it. Node has no API to put a different ACL
11
+ * on a pipe, and a native module for it would be a new dependency for one
12
+ * read. So `ezz hub status` and `ezz hub connect` said "not reported by the
13
+ * background service yet" while the Hub showed the agent connected.
14
+ *
15
+ * The data directory is already shared on purpose — the service account
16
+ * modifies it, Administrators own ProgramData, the installing user reads it —
17
+ * so the daemon also writes what a CLI needs to read there. The IPC channel is
18
+ * unchanged and stays one-way; this file is a second, read-only window, not a
19
+ * way to send anything to the daemon.
20
+ *
21
+ * ── What it holds ──────────────────────────────────────────────────────────
22
+ *
23
+ * Only what `getHubAgentStatus()` returns — linked, connected, status,
24
+ * lastError, attempts — plus the daemon's pid, version and the time of the
25
+ * write. No secret, no Hub URL, no server id: those are in the database,
26
+ * readable by the same people, and never needed here.
27
+ *
28
+ * ── Staleness ──────────────────────────────────────────────────────────────
29
+ *
30
+ * A file outlives its writer. A reader trusts it only when its pid is the pid
31
+ * holding the live daemon lock (pid + heartbeat, core/daemon/lock.js), so a
32
+ * leftover from a crashed or stopped daemon is never reported as current.
33
+ */
34
+
35
+ import fs from 'fs';
36
+ import path from 'path';
37
+
38
+ import { inspect as inspectLock } from './lock.js';
39
+
40
+ export const STATE_FILE_NAME = 'daemon-state.json';
41
+
42
+ /** @param {string} dataDir */
43
+ export function stateFilePath(dataDir) {
44
+ return path.join(dataDir, STATE_FILE_NAME);
45
+ }
46
+
47
+ /**
48
+ * Writes the state atomically: a temporary file, then a rename, so a reader
49
+ * never sees half a JSON document. Never throws — the daemon's work must not
50
+ * depend on a status file.
51
+ *
52
+ * @param {Object} opts
53
+ * @param {string} opts.dataDir
54
+ * @param {number} opts.pid
55
+ * @param {string} [opts.version]
56
+ * @param {Object|null} opts.hub getHubAgentStatus()
57
+ * @returns {boolean} whether it was written
58
+ */
59
+ export function writeDaemonState({ dataDir, pid, version = null, hub }) {
60
+ const file = stateFilePath(dataDir);
61
+ const body = `${JSON.stringify({
62
+ pid,
63
+ version,
64
+ updatedAt: new Date().toISOString(),
65
+ hub: hub
66
+ ? {
67
+ linked: Boolean(hub.linked),
68
+ connected: Boolean(hub.connected),
69
+ status: hub.status ?? null,
70
+ lastError: hub.lastError ?? null,
71
+ attempts: Number.isFinite(hub.attempts) ? hub.attempts : 0,
72
+ }
73
+ : null,
74
+ })}\n`;
75
+
76
+ const temp = `${file}.${pid}.tmp`;
77
+ try {
78
+ fs.writeFileSync(temp, body, 'utf8');
79
+ try {
80
+ fs.renameSync(temp, file);
81
+ } catch {
82
+ // Windows refuses a rename over a file a reader has open at that
83
+ // instant. A direct write is still whole for a document this small.
84
+ fs.writeFileSync(file, body, 'utf8');
85
+ fs.rmSync(temp, { force: true });
86
+ }
87
+ return true;
88
+ } catch {
89
+ try { fs.rmSync(temp, { force: true }); } catch { /* nothing to clean */ }
90
+ return false;
91
+ }
92
+ }
93
+
94
+ /** Removes the file on a clean stop. Best effort. */
95
+ export function removeDaemonState({ dataDir, pid }) {
96
+ try {
97
+ const current = readDaemonStateFile({ dataDir });
98
+ // Only our own: a daemon that already replaced us must keep its file.
99
+ if (!current || current.pid === pid) fs.rmSync(stateFilePath(dataDir), { force: true });
100
+ } catch { /* best effort */ }
101
+ }
102
+
103
+ /** The raw file, or null. */
104
+ export function readDaemonStateFile({ dataDir }) {
105
+ try {
106
+ return JSON.parse(fs.readFileSync(stateFilePath(dataDir), 'utf8'));
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The agent state as last written by the RUNNING daemon, or null.
114
+ *
115
+ * @param {Object} opts
116
+ * @param {string} opts.dataDir
117
+ * @param {Function} [opts.inspect] Injected for tests
118
+ * @returns {Object|null} the `hub` object, with `source: 'state-file'`
119
+ */
120
+ export function readAgentStateFromFile({ dataDir, inspect = inspectLock } = {}) {
121
+ const state = readDaemonStateFile({ dataDir });
122
+ if (!state?.hub) return null;
123
+
124
+ const lock = inspect({ dataDir });
125
+ if (!lock.running || lock.lock?.pid !== state.pid) return null;
126
+
127
+ return { ...state.hub, updatedAt: state.updatedAt ?? null, source: 'state-file' };
128
+ }
package/src/core/db.js CHANGED
@@ -12,6 +12,11 @@ const DATA_DIR = getDataDir();
12
12
 
13
13
  const DB_PATH = path.join(DATA_DIR, 'easy-devops.sqlite');
14
14
 
15
+ // The file the open connection uses. It equals DB_PATH for the life of almost
16
+ // every process; only reopenDb() moves it, after the Windows Server-mode
17
+ // migration has changed what getDataDir() answers.
18
+ let dbPath = DB_PATH;
19
+
15
20
  // ─── One-time migration from old package-relative location ───────────────────
16
21
  const OLD_DATA_DIR = path.join(__dirname, '..', '..', 'data');
17
22
  const OLD_DB_PATH = path.join(OLD_DATA_DIR, 'easy-devops.sqlite');
@@ -70,7 +75,7 @@ let db;
70
75
  * per call site without every future caller having to remember.
71
76
  */
72
77
  function createDbConnection() {
73
- return new GoodDB(new SQLiteDriver({ path: DB_PATH }), {
78
+ return new GoodDB(new SQLiteDriver({ path: dbPath }), {
74
79
  nested: "..",
75
80
  nestedIsEnabled: true,
76
81
  cache: {
@@ -117,3 +122,23 @@ export function initDb() {
117
122
  db = createDbConnection();
118
123
  }
119
124
  }
125
+
126
+ /**
127
+ * Closes the connection and opens the database in the CURRENT data directory.
128
+ *
129
+ * For the one place where the data directory changes within a process: the
130
+ * Windows Server-mode switch during `ezz service install`. Without it, the
131
+ * installing process kept writing to the per-user database it opened at
132
+ * startup — a file every later process ignores — and Windows refused to
133
+ * rename that directory to its backup name because this handle held it open.
134
+ *
135
+ * @returns {string} The database file now in use
136
+ */
137
+ export function reopenDb() {
138
+ closeDb();
139
+ const dir = getDataDir();
140
+ fs.mkdirSync(dir, { recursive: true });
141
+ dbPath = path.join(dir, 'easy-devops.sqlite');
142
+ db = createDbConnection();
143
+ return dbPath;
144
+ }
@@ -306,6 +306,31 @@ export function windowsProductNameCmd() {
306
306
  return "(Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion').ProductName";
307
307
  }
308
308
 
309
+ /**
310
+ * Command that prints `True` only when this process runs ELEVATED.
311
+ *
312
+ * Membership of Administrators is not enough: with UAC on, an administrator's
313
+ * normal terminal carries a filtered token, and IsInRole(Administrator) is
314
+ * false there until "Run as administrator". That is exactly the question —
315
+ * a filtered token is what makes Windows raise a UAC prompt for the wrapper.
316
+ * @returns {string}
317
+ */
318
+ export function windowsElevationCheckCmd() {
319
+ return '([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())'
320
+ + '.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)';
321
+ }
322
+
323
+ /**
324
+ * The Service Control Manager's command-line tool, always with its extension.
325
+ *
326
+ * Commands run through PowerShell on Windows, and there `sc` is the built-in
327
+ * alias for Set-Content: `sc query EasyDevOps` silently wrote a file named
328
+ * `query` containing "EasyDevOps" into the current directory and "succeeded".
329
+ * 1.4.0 shipped that, which is why status read "unknown" and stop/start did
330
+ * nothing. `sc.exe` names the real program in PowerShell and cmd alike.
331
+ */
332
+ export const WINDOWS_SC = 'sc.exe';
333
+
309
334
  /**
310
335
  * Address the daemon listens on for local event delivery to a dashboard.
311
336
  *
@@ -146,18 +146,23 @@ export function backupPathFor(dir, now = new Date()) {
146
146
  * @param {string} opts.to
147
147
  * @param {boolean} [opts.keepBackup] Leave the backup in place (default true)
148
148
  * @param {(line: string) => void} [opts.log]
149
- * @returns {{ ok: true, moved: boolean, backup: string|null, reason?: string }
149
+ * `originalAt` always says where the original data is afterwards: the backup
150
+ * path when the rename worked, or `from` itself when it could not be renamed
151
+ * (Windows refuses to rename a directory while a file in it is open). It is
152
+ * null only when there was no original, or it was removed on request.
153
+ *
154
+ * @returns {{ ok: true, moved: boolean, backup: string|null, originalAt: string|null, reason?: string }
150
155
  * | { ok: false, reason: string }}
151
156
  */
152
157
  export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
153
158
  if (!fs.existsSync(from)) {
154
159
  // Nothing to move is a success: a fresh install has no per-user data, and
155
160
  // the service simply starts with an empty ProgramData directory.
156
- return { ok: true, moved: false, backup: null, reason: `${from} does not exist` };
161
+ return { ok: true, moved: false, backup: null, originalAt: null, reason: `${from} does not exist` };
157
162
  }
158
163
 
159
164
  if (path.resolve(from).toLowerCase() === path.resolve(to).toLowerCase()) {
160
- return { ok: true, moved: false, backup: null, reason: 'source and destination are the same' };
165
+ return { ok: true, moved: false, backup: null, originalAt: from, reason: 'source and destination are the same' };
161
166
  }
162
167
 
163
168
  const busy = assertNotInUse(from);
@@ -203,10 +208,12 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
203
208
  // The copy is good and verified, so the data is safe in two places. Not
204
209
  // being able to rename the original is worth reporting but not worth
205
210
  // undoing a verified migration over.
211
+ log(`Original left in place at ${from} (it could not be renamed: ${err.code ?? err.message})`);
206
212
  return {
207
213
  ok: true,
208
214
  moved: true,
209
215
  backup: null,
216
+ originalAt: from,
210
217
  reason: `the data was copied and verified, but the original could not be renamed: ${err.message}. `
211
218
  + `It is still at ${from} — remove it by hand once you are satisfied.`,
212
219
  };
@@ -216,13 +223,30 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
216
223
  try {
217
224
  fs.rmSync(backup, { recursive: true, force: true });
218
225
  log('Backup removed as requested.');
219
- return { ok: true, moved: true, backup: null };
226
+ return { ok: true, moved: true, backup: null, originalAt: null };
220
227
  } catch (err) {
221
- return { ok: true, moved: true, backup, reason: `the backup could not be removed: ${err.message}` };
228
+ return { ok: true, moved: true, backup, originalAt: backup, reason: `the backup could not be removed: ${err.message}` };
222
229
  }
223
230
  }
224
231
 
225
- return { ok: true, moved: true, backup };
232
+ return { ok: true, moved: true, backup, originalAt: backup };
233
+ }
234
+
235
+ /**
236
+ * One line saying where the user's original data is after a migration.
237
+ *
238
+ * Exists because 1.4.0 printed `backup at null`: the rename to a backup name
239
+ * fails on Windows while the database inside is open, the original then stays
240
+ * where it was, and `backup` is null for exactly that reason. The data was
241
+ * never lost — the message just did not say where it was.
242
+ *
243
+ * @param {{ backup?: string|null, originalAt?: string|null }} result
244
+ * @returns {string}
245
+ */
246
+ export function describeOriginal(result) {
247
+ if (result?.backup) return `the original is kept as a backup at ${result.backup}`;
248
+ if (result?.originalAt) return `the original was left in place at ${result.originalAt}; remove it by hand once you are satisfied`;
249
+ return 'there was no earlier data to keep';
226
250
  }
227
251
 
228
252
  /**
@@ -235,7 +259,8 @@ export function moveDataDir({ from, to, keepBackup = true, log = () => {} }) {
235
259
  *
236
260
  * @param {Object} [opts]
237
261
  * @param {(line: string) => void} [opts.log]
238
- * @returns {{ ok: boolean, dataDir: string, migrated: boolean, backup: string|null, reason?: string }}
262
+ * @returns {{ ok: boolean, dataDir: string, migrated: boolean, backup: string|null, originalAt?: string|null,
263
+ * reason?: string }}
239
264
  */
240
265
  export function enableServerMode({ log = () => {} } = {}) {
241
266
  if (!isWindows) {
@@ -289,7 +314,7 @@ export function enableServerMode({ log = () => {} } = {}) {
289
314
  resetDataDirCache();
290
315
  log(`Server mode enabled. Data directory: ${target}`);
291
316
 
292
- return { ok: true, dataDir: target, migrated: moved.moved, backup: moved.backup, reason: moved.reason };
317
+ return { ok: true, dataDir: target, migrated: moved.moved, backup: moved.backup, originalAt: moved.originalAt, reason: moved.reason };
293
318
  }
294
319
 
295
320
  /**
@@ -341,5 +366,5 @@ export function disableServerMode({ log = () => {} } = {}) {
341
366
  }
342
367
 
343
368
  log(`Server mode disabled. Data directory: ${target}`);
344
- return { ok: true, dataDir: target, moved: moved.moved, backup: moved.backup, reason: moved.reason };
369
+ return { ok: true, dataDir: target, moved: moved.moved, backup: moved.backup, originalAt: moved.originalAt, reason: moved.reason };
345
370
  }