@ubercode/channelvault 0.3.0-rc.1 → 0.3.0-rc.3

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/dist/cli.js CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { spawnSync } from "child_process";
5
- import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readdir as readdir5, readFile as readFile5, realpath as realpath4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
5
+ import { cp, lstat as lstat3, mkdir as mkdir5, mkdtemp, readFile as readFile6, realpath as realpath4, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
6
  import { existsSync as existsSync6 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path6 from "path";
9
+ import * as path8 from "path";
10
10
  import { createInterface } from "readline/promises";
11
11
  import { Command, CommanderError } from "commander";
12
12
 
@@ -1000,12 +1000,12 @@ function configMapKeyOf(entry) {
1000
1000
  return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
1001
1001
  }
1002
1002
  function mapLeaves(config, visit) {
1003
- const walk = (node, key, path7, labels, section, cmKey) => {
1003
+ const walk = (node, key, path9, labels, section, cmKey) => {
1004
1004
  if (typeof node === "string") {
1005
- return visit(node, { location: path7.join("/"), key, labels, section, configMapKey: cmKey });
1005
+ return visit(node, { location: path9.join("/"), key, labels, section, configMapKey: cmKey });
1006
1006
  }
1007
1007
  if (Array.isArray(node)) {
1008
- return node.map((el, i) => walk(el, key, [...path7.slice(0, -1), `${path7[path7.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1008
+ return node.map((el, i) => walk(el, key, [...path9.slice(0, -1), `${path9[path9.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1009
1009
  }
1010
1010
  if (node && typeof node === "object") {
1011
1011
  const name = node["name"];
@@ -1013,7 +1013,7 @@ function mapLeaves(config, visit) {
1013
1013
  const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
1014
1014
  const out = {};
1015
1015
  for (const [k, v] of Object.entries(node)) {
1016
- out[k] = walk(v, k, [...path7, k], inner, section || k, mapKey);
1016
+ out[k] = walk(v, k, [...path9, k], inner, section || k, mapKey);
1017
1017
  }
1018
1018
  return out;
1019
1019
  }
@@ -1411,6 +1411,15 @@ function connectionError(url, err) {
1411
1411
  error.code = code;
1412
1412
  return error;
1413
1413
  }
1414
+ function redirectTarget(url, response) {
1415
+ const location = response.headers.get("location");
1416
+ if (!location) return "";
1417
+ try {
1418
+ return `, to ${new URL(location, url).origin}`;
1419
+ } catch {
1420
+ return "";
1421
+ }
1422
+ }
1414
1423
  var SERVER_CONFIG_KEY = "serverConfiguration";
1415
1424
  function unwrapSingleKey(value) {
1416
1425
  const keys = Object.keys(value);
@@ -1613,15 +1622,15 @@ var MirthClientImpl = class {
1613
1622
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1614
1623
  }
1615
1624
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1616
- async sendJson(method, path7, body, query) {
1617
- const response = await this.request(method, path7, {
1625
+ async sendJson(method, path9, body, query) {
1626
+ const response = await this.request(method, path9, {
1618
1627
  query,
1619
1628
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1620
1629
  body: JSON.stringify(body)
1621
1630
  });
1622
1631
  const text = await response.text();
1623
1632
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1624
- throw new Error(`${method} ${path7}: the server refused the update`);
1633
+ throw new Error(`${method} ${path9}: the server refused the update`);
1625
1634
  }
1626
1635
  }
1627
1636
  // --- internal transport ---------------------------------------------------
@@ -1630,11 +1639,11 @@ var MirthClientImpl = class {
1630
1639
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1631
1640
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1632
1641
  */
1633
- async request(method, path7, options = {}, isRetry = false) {
1642
+ async request(method, path9, options = {}, isRetry = false) {
1634
1643
  if (!this.authenticated) {
1635
1644
  await this.login();
1636
1645
  }
1637
- const url = this.buildUrl(path7, options.query);
1646
+ const url = this.buildUrl(path9, options.query);
1638
1647
  const headers = {
1639
1648
  "X-Requested-With": "XMLHttpRequest",
1640
1649
  ...options.headers
@@ -1648,28 +1657,39 @@ var MirthClientImpl = class {
1648
1657
  if (response.status === 401 && this.authenticated && !isRetry) {
1649
1658
  this.authenticated = false;
1650
1659
  await this.login();
1651
- return this.request(method, path7, options, true);
1660
+ return this.request(method, path9, options, true);
1652
1661
  }
1653
1662
  if (!response.ok) {
1654
1663
  throw await this.toApiError(response);
1655
1664
  }
1656
1665
  return response;
1657
1666
  }
1658
- /** fetch through this client's pool, with network failures explained. */
1667
+ /**
1668
+ * fetch through this client's pool, with network failures explained. Never
1669
+ * follows a redirect: fetch re-sends a 307/308 body, so a redirected login
1670
+ * would post the username and password to wherever the server points.
1671
+ */
1659
1672
  async send(url, init) {
1673
+ let response;
1660
1674
  try {
1661
- return await fetch(url, {
1675
+ response = await fetch(url, {
1662
1676
  ...init,
1677
+ redirect: "manual",
1663
1678
  // @ts-expect-error - dispatcher is a Node.js/undici specific option
1664
1679
  dispatcher: this.dispatcher
1665
1680
  });
1666
1681
  } catch (err) {
1667
1682
  throw connectionError(url, err);
1668
1683
  }
1684
+ if (response.status >= 300 && response.status < 400) {
1685
+ await response.body?.cancel();
1686
+ throw new Error(`the server answered ${new URL(url).pathname} with a redirect (HTTP ${response.status}${redirectTarget(url, response)}); channelvault does not follow redirects, so credentials and session cookies are never sent elsewhere. Connect to the address it redirects to: check https vs --no-https, --host and --port (or MIRTH_HOST/MIRTH_PORT)`);
1687
+ }
1688
+ return response;
1669
1689
  }
1670
1690
  /** Build an absolute URL with an optional query string. */
1671
- buildUrl(path7, query) {
1672
- const url = `${this.baseUrl}${path7}`;
1691
+ buildUrl(path9, query) {
1692
+ const url = `${this.baseUrl}${path9}`;
1673
1693
  if (!query || Object.keys(query).length === 0) {
1674
1694
  return url;
1675
1695
  }
@@ -2446,8 +2466,21 @@ ${missing.join("\n")}
2446
2466
  import { randomBytes as randomBytes2 } from "crypto";
2447
2467
  import { existsSync as existsSync4, realpathSync } from "fs";
2448
2468
  import { mkdir as mkdir3, readdir as readdir4, readFile as readFile4, rename as rename2, rm as rm2, writeFile as writeFile4 } from "fs/promises";
2469
+ import * as path5 from "path";
2470
+
2471
+ // src/profiles.ts
2472
+ import { homedir } from "os";
2449
2473
  import * as path4 from "path";
2450
- var DEFAULT_BACKUP_DIR = ".backup";
2474
+ function configDir() {
2475
+ const override = process.env.CHANNELVAULT_CONFIG_DIR;
2476
+ return override ? path4.resolve(override) : path4.join(homedir(), ".channelvault");
2477
+ }
2478
+
2479
+ // src/backup/index.ts
2480
+ function defaultBackupDir() {
2481
+ return path5.join(configDir(), "backups");
2482
+ }
2483
+ var LEGACY_BACKUP_DIR = ".backup";
2451
2484
  var DEFAULT_KEEP = 10;
2452
2485
  var FILE_NAME = /^(.+)-(\d{8}T\d{6}Z)(?:-(\d+))?\.xml$/;
2453
2486
  function serverSlug(name) {
@@ -2472,13 +2505,13 @@ async function listBackups(dir) {
2472
2505
  const out = [];
2473
2506
  for (const name of await readdir4(dir)) {
2474
2507
  const m = FILE_NAME.exec(name);
2475
- if (m) out.push({ file: path4.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2508
+ if (m) out.push({ file: path5.join(dir, name), server: m[1], stamp: m[2], seq: m[3] ? Number(m[3]) : 1 });
2476
2509
  }
2477
2510
  return out.sort((a, b) => a.stamp.localeCompare(b.stamp) || a.seq - b.seq);
2478
2511
  }
2479
2512
  var MANIFEST = "channelvault-backups.json";
2480
2513
  async function readManifest(dir) {
2481
- const file = path4.join(dir, MANIFEST);
2514
+ const file = path5.join(dir, MANIFEST);
2482
2515
  if (!existsSync4(file)) return {};
2483
2516
  try {
2484
2517
  const parsed = JSON.parse(await readFile4(file, "utf8"));
@@ -2488,17 +2521,17 @@ async function readManifest(dir) {
2488
2521
  }
2489
2522
  }
2490
2523
  async function writeManifest(dir, files) {
2491
- const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path4.join(dir, name))));
2492
- await writePrivate(path4.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
2524
+ const present2 = Object.fromEntries(Object.entries(files).filter(([name]) => existsSync4(path5.join(dir, name))));
2525
+ await writePrivate(path5.join(dir, MANIFEST), `${JSON.stringify({ version: 1, files: present2 }, null, 2)}
2493
2526
  `);
2494
2527
  }
2495
2528
  async function backupsOf(dir, serverId) {
2496
2529
  const manifest = await readManifest(dir);
2497
- return (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === serverId);
2530
+ return (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === serverId);
2498
2531
  }
2499
2532
  async function originOf(dir, file) {
2500
- if (!existsSync4(dir) || !sameFile(path4.dirname(file), dir)) return null;
2501
- return (await readManifest(dir))[path4.basename(file)] ?? null;
2533
+ if (!existsSync4(dir) || !sameFile(path5.dirname(file), dir)) return null;
2534
+ return (await readManifest(dir))[path5.basename(file)] ?? null;
2502
2535
  }
2503
2536
  async function originsIn(dir) {
2504
2537
  if (!existsSync4(dir)) return [];
@@ -2510,12 +2543,12 @@ async function saveBackup(dir, name, xml2, opts) {
2510
2543
  await ensureBackupDir(dir);
2511
2544
  const manifest = await readManifest(dir);
2512
2545
  const base = `${name}-${stamp(opts.now ?? /* @__PURE__ */ new Date())}`;
2513
- let file = path4.join(dir, `${base}.xml`);
2514
- for (let n = 2; existsSync4(file); n += 1) file = path4.join(dir, `${base}-${n}.xml`);
2546
+ let file = path5.join(dir, `${base}.xml`);
2547
+ for (let n = 2; existsSync4(file); n += 1) file = path5.join(dir, `${base}-${n}.xml`);
2515
2548
  await writePrivate(file, xml2);
2516
- manifest[path4.basename(file)] = opts.origin;
2549
+ manifest[path5.basename(file)] = opts.origin;
2517
2550
  await writeManifest(dir, manifest);
2518
- const mine = (await listBackups(dir)).filter((b) => manifest[path4.basename(b.file)]?.serverId === opts.origin.serverId);
2551
+ const mine = (await listBackups(dir)).filter((b) => manifest[path5.basename(b.file)]?.serverId === opts.origin.serverId);
2519
2552
  for (const old of mine.slice(0, Math.max(0, mine.length - opts.keep))) {
2520
2553
  if (sameFile(old.file, file) || opts.protect !== void 0 && sameFile(old.file, opts.protect)) continue;
2521
2554
  await rm2(old.file);
@@ -2525,15 +2558,15 @@ async function saveBackup(dir, name, xml2, opts) {
2525
2558
  }
2526
2559
  function sameFile(a, b) {
2527
2560
  const real = (p) => {
2528
- const resolved = existsSync4(p) ? realpathSync.native(p) : path4.resolve(p);
2561
+ const resolved = existsSync4(p) ? realpathSync.native(p) : path5.resolve(p);
2529
2562
  return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
2530
2563
  };
2531
2564
  return real(a) === real(b);
2532
2565
  }
2533
2566
  async function ensureBackupDir(dir) {
2534
2567
  if (existsSync4(dir)) return;
2535
- await mkdir3(dir, { recursive: true });
2536
- await writeFile4(path4.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
2568
+ await mkdir3(dir, { recursive: true, mode: 448 });
2569
+ await writeFile4(path5.join(dir, ".gitignore"), "# channelvault backups hold credentials in plain text\n*\n");
2537
2570
  }
2538
2571
  async function writePrivate(file, text) {
2539
2572
  const temp = `${file}.${process.pid}-${randomBytes2(4).toString("hex")}.tmp`;
@@ -2559,14 +2592,28 @@ function compareVersions(a, b) {
2559
2592
  return 0;
2560
2593
  }
2561
2594
 
2595
+ // src/xml/chars.ts
2596
+ import { readFile as readFile5 } from "fs/promises";
2597
+ import * as path7 from "path";
2598
+
2562
2599
  // src/tree/transaction.ts
2563
2600
  import { randomUUID } from "crypto";
2564
2601
  import { constants, existsSync as existsSync5 } from "fs";
2565
- import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir4, readlink, realpath as realpath3, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
2602
+ import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir4, readdir as readdir5, readlink, realpath as realpath3, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
2566
2603
  import { hostname } from "os";
2567
- import * as path5 from "path";
2604
+ import * as path6 from "path";
2568
2605
  import { setTimeout as delay } from "timers/promises";
2569
2606
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2607
+ async function treeFiles(base) {
2608
+ const out = [];
2609
+ for (const d of MANAGED_DIRS) {
2610
+ if (!existsSync5(path6.join(base, d))) continue;
2611
+ for (const entry of await readdir5(path6.join(base, d), { recursive: true, withFileTypes: true })) {
2612
+ if (entry.isFile()) out.push(path6.relative(base, path6.join(entry.parentPath, entry.name)).split(path6.sep).join("/"));
2613
+ }
2614
+ }
2615
+ return out;
2616
+ }
2570
2617
  var STAGING_DIR = ".channelvault-staging";
2571
2618
  var JOURNAL = ".channelvault-transaction.json";
2572
2619
  var ITEMS = [...MANAGED_DIRS, "channelvault.json", ".gitignore", ".secrets", "env"];
@@ -2579,11 +2626,11 @@ async function present(file) {
2579
2626
  }
2580
2627
  async function canonical(file, depth = 0) {
2581
2628
  if (depth > 64) throw new Error(`too many links in path: ${file}`);
2582
- let existing = path5.resolve(file);
2583
- while (!await present(existing) && path5.dirname(existing) !== existing) existing = path5.dirname(existing);
2629
+ let existing = path6.resolve(file);
2630
+ while (!await present(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
2584
2631
  const info = await lstat2(existing);
2585
- const base = info.isSymbolicLink() ? await canonical(path5.resolve(path5.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2586
- return path5.join(base, path5.relative(existing, path5.resolve(file)));
2632
+ const base = info.isSymbolicLink() ? await canonical(path6.resolve(path6.dirname(existing), await readlink(existing)), depth + 1) : await realpath3(existing);
2633
+ return path6.join(base, path6.relative(existing, path6.resolve(file)));
2587
2634
  }
2588
2635
  var samePath = (a, b) => process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
2589
2636
  async function move(from, to) {
@@ -2598,9 +2645,9 @@ async function move(from, to) {
2598
2645
  }
2599
2646
  }
2600
2647
  async function lockTree(root) {
2601
- await mkdir4(path5.dirname(root), { recursive: true });
2648
+ await mkdir4(path6.dirname(root), { recursive: true });
2602
2649
  const lock = `${await canonical(root)}.channelvault-lock`;
2603
- const ownerFile = path5.join(lock, "owner.json");
2650
+ const ownerFile = path6.join(lock, "owner.json");
2604
2651
  const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
2605
2652
  try {
2606
2653
  await mkdir4(lock);
@@ -2623,7 +2670,7 @@ async function lockTree(root) {
2623
2670
  }
2624
2671
  };
2625
2672
  if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
2626
- const reaping = path5.join(lock, "reaping");
2673
+ const reaping = path6.join(lock, "reaping");
2627
2674
  try {
2628
2675
  await mkdir4(reaping);
2629
2676
  } catch {
@@ -2654,7 +2701,7 @@ async function lockTree(root) {
2654
2701
  }
2655
2702
  async function assertStage(root) {
2656
2703
  for (const suffix of ["", "next", "previous"]) {
2657
- const stage = path5.join(root, STAGING_DIR, suffix);
2704
+ const stage = path6.join(root, STAGING_DIR, suffix);
2658
2705
  const info = await lstat2(stage).catch((err) => {
2659
2706
  if (err.code !== "ENOENT") throw err;
2660
2707
  return void 0;
@@ -2663,10 +2710,10 @@ async function assertStage(root) {
2663
2710
  }
2664
2711
  }
2665
2712
  function targetOf(root, journal, name) {
2666
- return name === "env" ? journal.envFile : path5.join(root, name);
2713
+ return name === "env" ? journal.envFile : path6.join(root, name);
2667
2714
  }
2668
2715
  function copies(root, journal, name) {
2669
- return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path5.join(root, STAGING_DIR, "previous", name), next: path5.join(root, STAGING_DIR, "next", name) };
2716
+ return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path6.join(root, STAGING_DIR, "previous", name), next: path6.join(root, STAGING_DIR, "next", name) };
2670
2717
  }
2671
2718
  async function cleanup(root, journal) {
2672
2719
  if (journal.entries.some((e) => e.name === "env")) {
@@ -2674,7 +2721,7 @@ async function cleanup(root, journal) {
2674
2721
  await rm3(old, { force: true });
2675
2722
  await rm3(next, { force: true });
2676
2723
  }
2677
- await rm3(path5.join(root, STAGING_DIR), RM);
2724
+ await rm3(path6.join(root, STAGING_DIR), RM);
2678
2725
  }
2679
2726
  async function rollback(root, journal) {
2680
2727
  for (const entry of [...journal.entries].reverse()) {
@@ -2689,7 +2736,7 @@ async function rollback(root, journal) {
2689
2736
  }
2690
2737
  }
2691
2738
  async function recoverTree(root, envFile) {
2692
- const file = path5.join(root, JOURNAL);
2739
+ const file = path6.join(root, JOURNAL);
2693
2740
  if (!existsSync5(file)) return;
2694
2741
  await assertStage(root);
2695
2742
  const journal = await readJson(file);
@@ -2703,9 +2750,9 @@ async function recoverTree(root, envFile) {
2703
2750
  async function replaceTree(root, envFile, prepare) {
2704
2751
  await recoverTree(root, envFile);
2705
2752
  await assertStage(root);
2706
- const stage = path5.join(root, STAGING_DIR);
2753
+ const stage = path6.join(root, STAGING_DIR);
2707
2754
  await rm3(stage, RM);
2708
- const next = path5.join(stage, "next");
2755
+ const next = path6.join(stage, "next");
2709
2756
  await mkdir4(next, { recursive: true });
2710
2757
  let journal;
2711
2758
  try {
@@ -2713,7 +2760,7 @@ async function replaceTree(root, envFile, prepare) {
2713
2760
  const targetEnv = await canonical(envFile);
2714
2761
  journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
2715
2762
  for (const name of ITEMS) {
2716
- if (!MANAGED_DIRS.includes(name) && !existsSync5(path5.join(next, name === "env" ? ".env" : name))) continue;
2763
+ if (!MANAGED_DIRS.includes(name) && !existsSync5(path6.join(next, name === "env" ? ".env" : name))) continue;
2717
2764
  const target = targetOf(root, journal, name);
2718
2765
  const info = await lstat2(target).catch((err) => {
2719
2766
  if (err.code !== "ENOENT") throw err;
@@ -2721,38 +2768,78 @@ async function replaceTree(root, envFile, prepare) {
2721
2768
  });
2722
2769
  journal.entries.push({ name, hadOld: info !== void 0 });
2723
2770
  }
2724
- await mkdir4(path5.join(stage, "previous"));
2725
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
2771
+ await mkdir4(path6.join(stage, "previous"));
2772
+ await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
2726
2773
  if (journal.entries.some((e) => e.name === "env")) {
2727
- await mkdir4(path5.dirname(targetEnv), { recursive: true });
2728
- await copyFile2(path5.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2774
+ await mkdir4(path6.dirname(targetEnv), { recursive: true });
2775
+ await copyFile2(path6.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
2729
2776
  }
2730
2777
  for (const entry of journal.entries) {
2731
2778
  const target = targetOf(root, journal, entry.name);
2732
2779
  const files = copies(root, journal, entry.name);
2733
2780
  if (entry.hadOld) await move(target, files.old);
2734
2781
  if (existsSync5(files.next)) {
2735
- await mkdir4(path5.dirname(target), { recursive: true });
2782
+ await mkdir4(path6.dirname(target), { recursive: true });
2736
2783
  await move(files.next, target);
2737
2784
  }
2738
2785
  }
2739
2786
  journal.state = "committed";
2740
- await writePrivate(path5.join(root, JOURNAL), JSON.stringify(journal));
2787
+ await writePrivate(path6.join(root, JOURNAL), JSON.stringify(journal));
2741
2788
  } catch (err) {
2742
- if (journal && existsSync5(path5.join(root, JOURNAL))) {
2789
+ if (journal && existsSync5(path6.join(root, JOURNAL))) {
2743
2790
  try {
2744
2791
  await rollback(root, journal);
2745
2792
  } catch (recoveryError) {
2746
- throw new Error(`replacement failed and recovery is pending in ${path5.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2793
+ throw new Error(`replacement failed and recovery is pending in ${path6.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
2747
2794
  }
2748
2795
  await cleanup(root, journal);
2749
- await unlink(path5.join(root, JOURNAL));
2796
+ await unlink(path6.join(root, JOURNAL));
2750
2797
  }
2751
2798
  await rm3(stage, RM);
2752
2799
  throw err;
2753
2800
  }
2754
2801
  await cleanup(root, journal);
2755
- await unlink(path5.join(root, JOURNAL));
2802
+ await unlink(path6.join(root, JOURNAL));
2803
+ }
2804
+
2805
+ // src/xml/chars.ts
2806
+ var FORBIDDEN = /[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff￾￿]/gu;
2807
+ var hex = (ch) => `U+${ch.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`;
2808
+ function positions(text) {
2809
+ const out = [];
2810
+ text.split(/\r\n|\r|\n/).forEach((line, i) => {
2811
+ for (const m of line.matchAll(FORBIDDEN)) {
2812
+ out.push({ line: i + 1, column: [...line.slice(0, m.index)].length + 1, codePoint: hex(m[0]) });
2813
+ }
2814
+ });
2815
+ return out;
2816
+ }
2817
+ function forbiddenXmlChars(config) {
2818
+ const out = [];
2819
+ mapLeaves(config, (value, leaf) => {
2820
+ const owner = leaf.configMapKey !== void 0 ? [`configuration map ${leaf.configMapKey}`] : leaf.labels.length ? leaf.labels : [leaf.location];
2821
+ for (const p of positions(value)) out.push({ where: [...owner, leaf.key].join(" \u203A "), ...p });
2822
+ return value;
2823
+ });
2824
+ return out;
2825
+ }
2826
+ async function forbiddenInFiles(root) {
2827
+ const out = [];
2828
+ for (const file of await treeFiles(root)) {
2829
+ for (const p of positions(await readFile5(path7.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
2830
+ }
2831
+ return out;
2832
+ }
2833
+ async function xmlSafetyProblem(config, treeRoot) {
2834
+ const found = forbiddenXmlChars(config);
2835
+ if (found.length === 0) return void 0;
2836
+ const files = treeRoot ? await forbiddenInFiles(treeRoot) : [];
2837
+ return [
2838
+ `${found.length} character(s) that XML 1.0 forbids; Mirth would save them and then fail to export its configuration (HTTP 500), breaking every later pull, push and restore:`,
2839
+ ...found.map((f) => ` ${f.where}: line ${f.line}, column ${f.column} of the value (${f.codePoint})`),
2840
+ ...files.length ? ["in the tree:", ...files.map((f) => ` ${f}`)] : [],
2841
+ "escape them in the script, for example \\uFFFE inside a regex or string"
2842
+ ].join("\n");
2756
2843
  }
2757
2844
 
2758
2845
  // src/cli.ts
@@ -2809,10 +2896,10 @@ function writeJson2(value) {
2809
2896
  `);
2810
2897
  }
2811
2898
  function addBackupDirFlags(cmd) {
2812
- return cmd.option("--backup-dir <dir>", `where backups are kept (default ./${DEFAULT_BACKUP_DIR})`).option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
2899
+ return cmd.option("--backup-dir <dir>", "where backups are kept (default ~/.channelvault/backups, shared by every checkout)").option("--keep <n>", `backups kept per server (default ${DEFAULT_KEEP})`);
2813
2900
  }
2814
2901
  function backupDirOf(flags) {
2815
- return path6.resolve(flags.backupDir ?? DEFAULT_BACKUP_DIR);
2902
+ return path8.resolve(flags.backupDir ?? defaultBackupDir());
2816
2903
  }
2817
2904
  function keepOf(flags) {
2818
2905
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -2879,21 +2966,24 @@ function hostOf(flags) {
2879
2966
  const cfg = resolveClientConfig(flags);
2880
2967
  return `${cfg.host}:${cfg.port}`;
2881
2968
  }
2882
- async function confirm(question) {
2969
+ async function ask(question) {
2883
2970
  const rl = createInterface({ input: process.stdin, output: process.stdout });
2884
2971
  const controller = new AbortController();
2885
2972
  rl.once("close", () => controller.abort());
2886
2973
  rl.once("SIGINT", () => controller.abort());
2887
2974
  try {
2888
- const answer = (await rl.question(`${question} [y/N] `, { signal: controller.signal })).trim().toLowerCase();
2889
- return answer === "y" || answer === "yes";
2975
+ return (await rl.question(question, { signal: controller.signal })).trim();
2890
2976
  } catch (err) {
2891
- if (controller.signal.aborted) fail("confirmation interrupted; nothing was pushed");
2977
+ if (controller.signal.aborted) fail("confirmation interrupted; nothing was changed");
2892
2978
  throw err;
2893
2979
  } finally {
2894
2980
  rl.close();
2895
2981
  }
2896
2982
  }
2983
+ async function confirm(question) {
2984
+ const answer = (await ask(`${question} [y/N] `)).toLowerCase();
2985
+ return answer === "y" || answer === "yes";
2986
+ }
2897
2987
  function summarize(config) {
2898
2988
  const asArray2 = (v) => Array.isArray(v) ? v : v == null ? [] : [v];
2899
2989
  const channels = asArray2(config.channels?.channel);
@@ -2926,24 +3016,24 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
2926
3016
  resources,
2927
3017
  serverId
2928
3018
  };
2929
- const file = path6.join(root, "channelvault.json");
3019
+ const file = path8.join(root, "channelvault.json");
2930
3020
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
2931
3021
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
2932
3022
  }
2933
3023
  function envFilePath(root, flags) {
2934
- return flags.dotenv ? path6.resolve(flags.dotenv) : path6.join(root, ".env");
3024
+ return flags.dotenv ? path8.resolve(flags.dotenv) : path8.join(root, ".env");
2935
3025
  }
2936
3026
  async function loadEnv(file) {
2937
3027
  return { ...await readEnvFile(file), ...process.env };
2938
3028
  }
2939
3029
  function addEnvFlag(cmd) {
2940
- return cmd.option("--dotenv <path>", "env file holding secrets and per-environment values (default <dir>/.env)");
3030
+ return cmd.option("--dotenv <path>", "env file holding the tree's placeholder values, not the login (default <dir>/.env)");
2941
3031
  }
2942
3032
  function addExtractFlag(cmd) {
2943
3033
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
2944
3034
  }
2945
3035
  async function existingTree(root) {
2946
- return existsSync6(path6.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3036
+ return existsSync6(path8.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
2947
3037
  }
2948
3038
  async function renderedTree(root, flags) {
2949
3039
  const tree = await engine.implode({ root });
@@ -2972,7 +3062,7 @@ function scrub(text) {
2972
3062
  }
2973
3063
  var ALLOW_FILE = "channelvault.allow.json";
2974
3064
  async function readAllow(root) {
2975
- const file = path6.join(root, ALLOW_FILE);
3065
+ const file = path8.join(root, ALLOW_FILE);
2976
3066
  if (!existsSync6(file)) return [];
2977
3067
  const parsed = await readJson(file);
2978
3068
  return parsed.ignore ?? [];
@@ -2998,27 +3088,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
2998
3088
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
2999
3089
  rememberSecrets(config, { ...env, ...envUpdates });
3000
3090
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3001
- const rel = path6.relative(root, envFile);
3002
- const envInTree = !rel.startsWith("..") && !path6.isAbsolute(rel);
3091
+ const rel = path8.relative(root, envFile);
3092
+ const envInTree = !rel.startsWith("..") && !path8.isAbsolute(rel);
3003
3093
  let backup = null;
3004
3094
  await replaceTree(root, envFile, async (next) => {
3005
3095
  await engine.explode(config, { root: next });
3006
3096
  await writeMeta(next, source, fetched, previousMeta, serverId);
3007
3097
  if (Object.keys(envUpdates).length > 0) {
3008
- const history = path6.join(root, ".secrets");
3098
+ const history = path8.join(root, ".secrets");
3009
3099
  if (existsSync6(history)) {
3010
3100
  if ((await lstat3(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3011
- await cp(history, path6.join(next, ".secrets"), { recursive: true });
3101
+ await cp(history, path8.join(next, ".secrets"), { recursive: true });
3012
3102
  }
3013
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path6.join(next, ".secrets"));
3014
- if (stagedBackup) backup = path6.join(root, ".secrets", path6.basename(stagedBackup));
3103
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path8.join(next, ".secrets"));
3104
+ if (stagedBackup) backup = path8.join(root, ".secrets", path8.basename(stagedBackup));
3015
3105
  if (backup || envInTree) {
3016
- const ignore = path6.join(root, ".gitignore");
3017
- if (existsSync6(ignore)) await writeFile6(path6.join(next, ".gitignore"), await readFile5(ignore));
3106
+ const ignore = path8.join(root, ".gitignore");
3107
+ if (existsSync6(ignore)) await writeFile6(path8.join(next, ".gitignore"), await readFile6(ignore));
3018
3108
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3019
3109
  }
3020
- const stagedEnv = path6.join(next, ".env");
3021
- if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile5(envFile), { mode: 384 });
3110
+ const stagedEnv = path8.join(next, ".env");
3111
+ if (existsSync6(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3022
3112
  await updateEnvFile(stagedEnv, envUpdates);
3023
3113
  }
3024
3114
  });
@@ -3041,27 +3131,27 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3041
3131
  }
3042
3132
  }
3043
3133
  function gitWouldCommit(file) {
3044
- const r = spawnSync("git", ["check-ignore", "-q", path6.basename(file)], { cwd: path6.dirname(file) });
3134
+ const r = spawnSync("git", ["check-ignore", "-q", path8.basename(file)], { cwd: path8.dirname(file) });
3045
3135
  return r.status === 1;
3046
3136
  }
3047
3137
  async function resolvedPath(p) {
3048
- const abs = path6.resolve(p);
3138
+ const abs = path8.resolve(p);
3049
3139
  let existing = abs;
3050
- while (!existsSync6(existing) && path6.dirname(existing) !== existing) existing = path6.dirname(existing);
3051
- return path6.join(await realpath4(existing), path6.relative(existing, abs));
3140
+ while (!existsSync6(existing) && path8.dirname(existing) !== existing) existing = path8.dirname(existing);
3141
+ return path8.join(await realpath4(existing), path8.relative(existing, abs));
3052
3142
  }
3053
3143
  function isWithin(child, parent) {
3054
3144
  const norm = (p) => process.platform === "win32" ? p.toLowerCase() : p;
3055
- const rel = path6.relative(norm(parent), norm(child));
3056
- return rel === "" || rel !== ".." && !rel.startsWith(`..${path6.sep}`) && !path6.isAbsolute(rel);
3145
+ const rel = path8.relative(norm(parent), norm(child));
3146
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${path8.sep}`) && !path8.isAbsolute(rel);
3057
3147
  }
3058
3148
  async function preflightTree(root, envFile) {
3059
3149
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3060
3150
  const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
3061
- (d) => isWithin(path6.resolve(envFile), path6.resolve(root, d)) || isWithin(realEnv, path6.join(realRoot, d))
3151
+ (d) => isWithin(path8.resolve(envFile), path8.resolve(root, d)) || isWithin(realEnv, path8.join(realRoot, d))
3062
3152
  );
3063
3153
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3064
- const metaPath = path6.join(root, "channelvault.json");
3154
+ const metaPath = path8.join(root, "channelvault.json");
3065
3155
  if (existsSync6(metaPath)) {
3066
3156
  let meta;
3067
3157
  try {
@@ -3076,7 +3166,7 @@ async function preflightTree(root, envFile) {
3076
3166
  }
3077
3167
  return meta;
3078
3168
  }
3079
- const foreign = MANAGED_DIRS.filter((d) => existsSync6(path6.join(root, d)));
3169
+ const foreign = MANAGED_DIRS.filter((d) => existsSync6(path8.join(root, d)));
3080
3170
  if (foreign.length > 0) {
3081
3171
  fail(
3082
3172
  `${root} is not a channelvault tree (no channelvault.json) but has ${foreign.map((d) => `${d}/`).join(", ")}, which this command would replace; nothing was written. Use a new or empty directory (or, if an earlier pull or explode into it was interrupted, delete those directories).`
@@ -3085,12 +3175,12 @@ async function preflightTree(root, envFile) {
3085
3175
  return null;
3086
3176
  }
3087
3177
  function assertTree(root) {
3088
- if (!existsSync6(path6.join(root, "server", "configuration.json"))) {
3178
+ if (!existsSync6(path8.join(root, "server", "configuration.json"))) {
3089
3179
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3090
3180
  }
3091
3181
  }
3092
3182
  async function readTreeOrigin(root) {
3093
- const metaPath = path6.join(root, "channelvault.json");
3183
+ const metaPath = path8.join(root, "channelvault.json");
3094
3184
  if (!existsSync6(metaPath)) return "unknown";
3095
3185
  try {
3096
3186
  const meta = await readJson(metaPath);
@@ -3119,22 +3209,26 @@ function collect(value, previous) {
3119
3209
  return [...previous ?? [], value];
3120
3210
  }
3121
3211
  async function bindingProblems(root, serverId) {
3122
- const file = path6.join(root, "channelvault.json");
3212
+ const file = path8.join(root, "channelvault.json");
3123
3213
  const meta = existsSync6(file) ? await readJson(file) : null;
3124
3214
  if (meta?.serverId === serverId) return [];
3125
3215
  return [`this tree's baseline belongs to ${meta?.serverId ? `installation ${meta.serverId}` : "an unknown installation"}, not the target (${serverId}); pull the target and merge your edits, or review with 'adopt <dir> --plan-only' and run 'adopt <dir>' to establish its baseline; --force does not bypass installation binding`];
3126
3216
  }
3217
+ async function xmlProblems(root, config) {
3218
+ const problem = await xmlSafetyProblem(config, root);
3219
+ return problem ? [problem] : [];
3220
+ }
3127
3221
  async function assertBinding(client, root) {
3128
3222
  const problems = await bindingProblems(root, await client.getServerId());
3129
3223
  if (problems.length) fail(problems.join("\n"));
3130
3224
  }
3131
3225
  async function readKnown(root) {
3132
- const metaPath = path6.join(root, "channelvault.json");
3226
+ const metaPath = path8.join(root, "channelvault.json");
3133
3227
  if (!existsSync6(metaPath)) return void 0;
3134
3228
  return knownFrom((await readJson(metaPath)).resources);
3135
3229
  }
3136
3230
  async function writeKnown(root, known) {
3137
- const metaPath = path6.join(root, "channelvault.json");
3231
+ const metaPath = path8.join(root, "channelvault.json");
3138
3232
  if (!existsSync6(metaPath)) return;
3139
3233
  const meta = await readJson(metaPath);
3140
3234
  if (!meta.resources) return;
@@ -3199,7 +3293,7 @@ async function scopedPush(client, root, local, scope, target, flags) {
3199
3293
  const remote = await client.getServerConfiguration();
3200
3294
  const known = await readKnown(root);
3201
3295
  const plan = planPush(local, remote, scope, known);
3202
- const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags)];
3296
+ const problems = [...await bindingProblems(root, await client.getServerId()), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3203
3297
  const names = new Map(
3204
3298
  [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
3205
3299
  );
@@ -3259,23 +3353,43 @@ pull and try again, or pass --force`);
3259
3353
  }
3260
3354
  await assertBinding(client, root);
3261
3355
  const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
3356
+ let baselineError;
3357
+ let changedAgain = [];
3358
+ let unverified = [];
3359
+ let after;
3262
3360
  try {
3263
- const after = await client.getServerConfiguration();
3264
- const refreshedLibraries = librariesOf(local).filter((l) => result.touchedIds.has(String(l["id"]))).map((l) => ({ kind: "library", op: "update", id: String(l["id"]), label: String(l["name"]) }));
3265
- const membershipSent = result.sentLibraries ? { ...local, codeTemplateLibraries: { codeTemplateLibrary: result.sentLibraries } } : local;
3266
- const changedAgain = [...result.applied, ...refreshedLibraries].filter((c) => !savedChangeMatches(c, c.kind === "library" ? membershipSent : local, after));
3267
- if (changedAgain.length > 0) fail(`changed again after saving: ${[...new Set(changedAgain.map((c) => c.label))].join(", ")}; pull and review before retrying`);
3268
- if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
3269
- if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
3361
+ after = await client.getServerConfiguration();
3270
3362
  } catch (err) {
3271
- const message = err instanceof Error ? err.message : String(err);
3272
- if (!result.failed) fail(`applied ${result.applied.length} change(s), but could not refresh the local sync baseline: ${message}; inspect the server before retrying`);
3273
- process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(message)}
3274
- `);
3363
+ baselineError = `could not read the server configuration back: ${err instanceof Error ? err.message : String(err)}. ${exportBrokenHint(flags)}`;
3364
+ ({ changed: changedAgain, unverified } = await changedAgainSingly(client, result.applied, local));
3275
3365
  }
3366
+ if (after) {
3367
+ try {
3368
+ const refreshedLibraries = librariesOf(local).filter((l) => result.touchedIds.has(String(l["id"]))).map((l) => ({ kind: "library", op: "update", id: String(l["id"]), label: String(l["name"]) }));
3369
+ const membershipSent = result.sentLibraries ? { ...local, codeTemplateLibraries: { codeTemplateLibrary: result.sentLibraries } } : local;
3370
+ const saved = after;
3371
+ changedAgain = [...new Set([...result.applied, ...refreshedLibraries].filter((c) => !savedChangeMatches(c, c.kind === "library" ? membershipSent : local, saved)).map((c) => c.label))];
3372
+ if (changedAgain.length === 0) {
3373
+ if (result.touchedIds.size > 0) await refreshRevisions(root, after, result.touchedIds);
3374
+ if (known) await writeKnown(root, knownAfterPush(known, result.applied, result.touchedIds, after));
3375
+ }
3376
+ } catch (err) {
3377
+ baselineError = err instanceof Error ? err.message : String(err);
3378
+ }
3379
+ }
3380
+ const notRedeployed = toDeploy.length > 0 ? `
3381
+ ${toDeploy.length} channel(s) NOT redeployed: ${toDeploy.map(nameOf2).join(", ")}; redeploy them from the Administrator once the server is as intended` : "";
3382
+ const againNote = changedAgain.length > 0 ? `
3383
+ changed again after saving (pull and review before retrying): ${changedAgain.join(", ")}` : "";
3276
3384
  if (result.failed) {
3385
+ if (baselineError) process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(baselineError)}
3386
+ `);
3277
3387
  const { change, error } = result.failed;
3278
- fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}`);
3388
+ fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
3389
+ }
3390
+ if (changedAgain.length > 0) {
3391
+ fail(`applied ${result.applied.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
3392
+ ${baselineError}` : ""}`);
3279
3393
  }
3280
3394
  process.stdout.write(`pushed ${result.applied.length} change(s)
3281
3395
  `);
@@ -3289,12 +3403,57 @@ pull and try again, or pass --force`);
3289
3403
  `);
3290
3404
  if (failures.length > 0) process.exitCode = 1;
3291
3405
  }
3406
+ if (baselineError) {
3407
+ const note = unverified.length > 0 ? `
3408
+ not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3409
+ fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3410
+ }
3411
+ printCommitHint(root);
3412
+ }
3413
+ function printCommitHint(root) {
3414
+ const r = spawnSync("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--", "."], { cwd: root, encoding: "utf8" });
3415
+ if (r.status !== 0 || !r.stdout) return;
3416
+ const entries = r.stdout.split("\0");
3417
+ const files = [];
3418
+ for (let i = 0; i < entries.length; i++) {
3419
+ const entry = entries[i];
3420
+ if (entry.length < 4) continue;
3421
+ files.push(entry.slice(3));
3422
+ if (entry[0] === "R" || entry[0] === "C") i++;
3423
+ }
3424
+ if (files.length === 0) return;
3425
+ const shown = files.length > 10 ? [...files.slice(0, 10), `and ${files.length - 10} more`] : files;
3426
+ process.stdout.write(`commit the refreshed baseline with your change (paths from the repository root): ${shown.join(", ")}
3427
+ `);
3428
+ }
3429
+ function exportBrokenHint(flags) {
3430
+ const undo = flags.backup === false ? "" : " (including the undo command above, unless you add --export-broken to it, which restores without a preview or an undo backup)";
3431
+ return `If the server cannot export its configuration, pull, diff, push and restore${undo} fail until the resource that broke it is fixed in the Administrator; then pull or adopt to refresh the baseline`;
3432
+ }
3433
+ async function changedAgainSingly(client, applied, local) {
3434
+ const changed = [];
3435
+ const unverified = [];
3436
+ for (const c of applied) {
3437
+ if (c.kind !== "channel" && c.kind !== "codeTemplate") {
3438
+ unverified.push(c.label);
3439
+ continue;
3440
+ }
3441
+ try {
3442
+ const current = c.kind === "channel" ? await client.getChannel(c.id) : await client.getCodeTemplate(c.id);
3443
+ const held = current ? [current] : [];
3444
+ const server = c.kind === "channel" ? { channels: { channel: held } } : { codeTemplateLibraries: { codeTemplateLibrary: [{ codeTemplates: { codeTemplate: held } }] } };
3445
+ if (!savedChangeMatches(c, local, server)) changed.push(c.label);
3446
+ } catch {
3447
+ changed.push(`${c.label} (could not be read)`);
3448
+ }
3449
+ }
3450
+ return { changed, unverified };
3292
3451
  }
3293
3452
  async function wholeServerPush(client, root, local, target, flags) {
3294
3453
  const remote = await client.getServerConfiguration();
3295
3454
  const known = await readKnown(root);
3296
3455
  const plan = planPush(local, remote, {}, known, { wholeReplace: true });
3297
- const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags)];
3456
+ const problems = [...await bindingProblems(root, await client.getServerId()), ...wholeServerProblems(plan, flags), ...await xmlProblems(root, local)];
3298
3457
  if (flags.planOnly && flags.json) {
3299
3458
  reportPlanOnly(flags, plan, problems, { target, mode: "whole-server" });
3300
3459
  return;
@@ -3345,7 +3504,12 @@ async function wholeServerPush(client, root, local, target, flags) {
3345
3504
  deploy: flags.deploy === true,
3346
3505
  overwriteConfigMap: flags.overwriteConfigMap === true
3347
3506
  });
3348
- const after = await client.getServerConfiguration();
3507
+ let after;
3508
+ try {
3509
+ after = await client.getServerConfiguration();
3510
+ } catch (err) {
3511
+ fail(`replaced the configuration at ${target}${flags.deploy ? " (Mirth redeploys as part of the replace)" : ""}, but could not read it back: ${err instanceof Error ? err.message : String(err)}. The tree's baseline was not refreshed. ${exportBrokenHint(flags)}`);
3512
+ }
3349
3513
  if (planPush(local, after, {}, void 0, { wholeReplace: true }).changes.length > 0) {
3350
3514
  fail("applied the whole-server replacement, but resources changed again after saving; pull and review before retrying");
3351
3515
  }
@@ -3354,15 +3518,16 @@ async function wholeServerPush(client, root, local, target, flags) {
3354
3518
  if (known) await writeKnown(root, resourceIds(after));
3355
3519
  process.stdout.write(`pushed ${root} -> ${target}
3356
3520
  `);
3521
+ printCommitHint(root);
3357
3522
  }
3358
3523
  var program = new Command();
3359
3524
  program.name("channelvault").description("Git-style pull/push/diff for Mirth Connect").version(VERSION).allowExcessArguments(false);
3360
3525
  addExtractFlag(addEnvFlag(
3361
3526
  program.command("explode").description("Explode a Mirth backup XML into a working tree").argument("<backup.xml>", "path to a Mirth backup config XML file").argument("<dir>", "output working-tree directory")
3362
3527
  )).action(async (backupPath, dir, flags) => {
3363
- const config = xml.parse(await readFile5(backupPath, "utf8"));
3364
- const root = path6.resolve(dir);
3365
- await writeTree(root, config, `file:${path6.resolve(backupPath)}`, flags);
3528
+ const config = xml.parse(await readFile6(backupPath, "utf8"));
3529
+ const root = path8.resolve(dir);
3530
+ await writeTree(root, config, `file:${path8.resolve(backupPath)}`, flags);
3366
3531
  const s = summarize(config);
3367
3532
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3368
3533
  `);
@@ -3370,19 +3535,19 @@ addExtractFlag(addEnvFlag(
3370
3535
  addEnvFlag(
3371
3536
  program.command("implode").description("Reassemble a working tree into a Mirth backup XML").argument("<dir>", "working-tree directory").argument("<backup.xml>", "output XML path").option("--force", "implode even if the tree was pulled from a live server", false)
3372
3537
  ).action(async (dir, outPath, flags) => {
3373
- const root = path6.resolve(dir);
3538
+ const root = path8.resolve(dir);
3374
3539
  assertTree(root);
3375
3540
  const config = await renderedTree(root, flags);
3376
3541
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3377
3542
  const xmlStr = xml.build(config);
3378
3543
  await writeFile6(outPath, xmlStr, "utf8");
3379
- process.stdout.write(`imploded ${root} -> ${path6.resolve(outPath)}
3544
+ process.stdout.write(`imploded ${root} -> ${path8.resolve(outPath)}
3380
3545
  `);
3381
3546
  });
3382
3547
  addExtractFlag(addEnvFlag(addConnectionFlags(
3383
3548
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3384
3549
  ))).action(async (dir, flags) => {
3385
- const root = path6.resolve(dir);
3550
+ const root = path8.resolve(dir);
3386
3551
  await preflightTree(root, envFilePath(root, flags));
3387
3552
  const { config, serverId } = await withClient(flags, async (client) => {
3388
3553
  const serverId2 = await client.getServerId();
@@ -3399,7 +3564,7 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3399
3564
  addJsonFlag(addEnvFlag(addConnectionFlags(
3400
3565
  program.command("adopt").description("Review and capture this installation as the tree baseline, preserving local content; writes no server resources").argument("<dir>", "working-tree directory").option("--plan-only", "preview the resulting push plan without changing the tree", false).option("-y, --yes", "accept the reviewed destination baseline without a prompt", false)
3401
3566
  ))).action(async (dir, flags) => {
3402
- const root = path6.resolve(dir);
3567
+ const root = path8.resolve(dir);
3403
3568
  assertTree(root);
3404
3569
  const previous = await preflightTree(root, envFilePath(root, flags));
3405
3570
  const stored = await engine.implode({ root });
@@ -3453,7 +3618,7 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3453
3618
  fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
3454
3619
  }
3455
3620
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
3456
- const root = path6.resolve(dir);
3621
+ const root = path8.resolve(dir);
3457
3622
  assertTree(root);
3458
3623
  const config = await renderedTree(root, flags);
3459
3624
  await assertCompatibleOrigin(root, config, "live", flags.ignoreOrigin === true);
@@ -3472,17 +3637,17 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
3472
3637
  }
3473
3638
  );
3474
3639
  addBackupDirFlags(addConnectionFlags(
3475
- program.command("backup").description(`Save the server configuration as <server>-<UTC time>.xml in ./${DEFAULT_BACKUP_DIR} (holds credentials in plain text)`).option("--out <file>", "write to this file instead (no rotation)")
3640
+ program.command("backup").description("Save the server configuration as <server>-<UTC time>.xml in ~/.channelvault/backups (holds credentials in plain text)").option("--out <file>", "write to this file instead (no rotation)")
3476
3641
  )).action(async (flags) => {
3477
3642
  const cfg = resolveClientConfig(flags);
3478
3643
  const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3479
3644
  const file = await withClient(flags, async (client) => {
3480
3645
  const text = await client.getServerConfigurationXml();
3481
3646
  if (!flags.out) return saveServerBackup(client, text, flags);
3482
- const out = path6.resolve(flags.out);
3647
+ const out = path8.resolve(flags.out);
3483
3648
  parseBackup(text, "the server configuration");
3484
3649
  if (existsSync6(out)) fail(`${out} already exists; choose another name`);
3485
- await mkdir5(path6.dirname(out), { recursive: true });
3650
+ await mkdir5(path8.dirname(out), { recursive: true });
3486
3651
  await writePrivate(out, text);
3487
3652
  if (gitWouldCommit(out)) {
3488
3653
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -3493,31 +3658,94 @@ addBackupDirFlags(addConnectionFlags(
3493
3658
  process.stdout.write(`backed up ${target} to ${file}
3494
3659
  `);
3495
3660
  });
3661
+ async function chooseBackup(dir, file, serverId, target) {
3662
+ if (file) {
3663
+ const chosen = path8.resolve(file);
3664
+ if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3665
+ return chosen;
3666
+ }
3667
+ const mine = await backupsOf(dir, serverId);
3668
+ if (mine.length === 0) {
3669
+ const others = (await originsIn(dir)).map((o) => o.host);
3670
+ const legacy = path8.resolve(LEGACY_BACKUP_DIR);
3671
+ const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
3672
+ fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}` + (inLegacy ? `; ${legacy} has backups of this server (the default before 0.3.0-rc.3): pass --backup-dir ${shellArgument(legacy)}` : ""));
3673
+ }
3674
+ return mine[mine.length - 1].file;
3675
+ }
3676
+ async function restoreWithBrokenExport(client, file, flags, target) {
3677
+ try {
3678
+ await client.getServerConfigurationXml();
3679
+ fail("the server can export its configuration; run restore without --export-broken, which shows a preview and saves an undo backup first");
3680
+ } catch (err) {
3681
+ if (err instanceof CliError) throw err;
3682
+ if (err.status !== 500) {
3683
+ fail(`cannot tell whether the export is broken: ${err instanceof Error ? err.message : String(err)}; --export-broken only proceeds when the server answers its export with HTTP 500`);
3684
+ }
3685
+ }
3686
+ const serverId = await client.getServerId();
3687
+ const dir = backupDirOf(flags);
3688
+ const chosen = await chooseBackup(dir, file, serverId, target);
3689
+ const text = await readFile6(chosen, "utf8");
3690
+ const backup = parseBackup(text, chosen);
3691
+ const unsafe = await xmlSafetyProblem(backup);
3692
+ if (unsafe) fail(`${chosen} holds ${unsafe}`);
3693
+ const origin = await originOf(dir, chosen);
3694
+ if (!origin && !flags.force) {
3695
+ fail(`${chosen} is not in ${path8.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
3696
+ }
3697
+ if (origin && origin.serverId !== serverId && !flags.force) {
3698
+ fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
3699
+ }
3700
+ process.stdout.write(
3701
+ `Restore ${chosen}
3702
+ to ${target} (installation ${serverId}), replacing its ENTIRE configuration${flags.deploy ? ", then redeploy all channels" : ""}.
3703
+ The server cannot export its configuration, so there is no preview, no undo backup and no version check.
3704
+ `
3705
+ );
3706
+ if (!flags.yes && await ask(`Type the installation ID (${serverId}) to continue: `) !== serverId) {
3707
+ process.stdout.write("aborted.\n");
3708
+ return;
3709
+ }
3710
+ await client.putServerConfigurationXml(text, { deploy: flags.deploy === true, overwriteConfigMap: flags.overwriteConfigMap === true });
3711
+ let afterText;
3712
+ try {
3713
+ afterText = await client.getServerConfigurationXml();
3714
+ } catch (err) {
3715
+ fail(`sent ${chosen} to ${target}, but the server still cannot export its configuration: ${err instanceof Error ? err.message : String(err)}; inspect it in the Administrator`);
3716
+ }
3717
+ const differ = planPush(backup, parseBackup(afterText, "the server configuration"), {}, void 0, { wholeReplace: true }).changes;
3718
+ if (differ.length > 0) {
3719
+ fail(`restored, but these differ from the backup afterwards: ${differ.map((c) => c.label).join(", ")}; inspect the server`);
3720
+ }
3721
+ process.stdout.write(`restored ${chosen} to ${target}; the server exports its configuration again
3722
+ `);
3723
+ }
3496
3724
  addBackupDirFlags(addConnectionFlags(
3497
- program.command("restore").description("Replace the entire server configuration with a backup (default: the newest backup of this server)").argument("[file]", "backup XML to restore").option("--deploy", "redeploy all channels afterwards", false).option("--overwrite-config-map", "also replace the configuration map", false).option("--force", "restore a backup taken from another server", false).option("-y, --yes", "skip the confirmation prompt", false)
3725
+ program.command("restore").description("Replace the entire server configuration with a backup (default: the newest backup of this server)").argument("[file]", "backup XML to restore").option("--deploy", "redeploy all channels afterwards", false).option("--overwrite-config-map", "also replace the configuration map", false).option("--force", "restore a backup taken from another server", false).option("--export-broken", "the server cannot export its configuration (HTTP 500): restore without a preview, undo backup or version check", false).option("-y, --yes", "skip the confirmation prompt", false)
3498
3726
  )).action(async (file, flags) => {
3499
3727
  const cfg = resolveClientConfig(flags);
3500
3728
  const target = `${cfg.https === false ? "http" : "https"}://${cfg.host}:${cfg.port}`;
3501
3729
  if (!flags.yes && !process.stdin.isTTY) fail("no terminal to confirm on; pass --yes");
3502
3730
  const dir = backupDirOf(flags);
3503
3731
  await withClient(flags, async (client) => {
3504
- const currentText = await client.getServerConfigurationXml();
3732
+ if (flags.exportBroken) {
3733
+ await restoreWithBrokenExport(client, file, flags, target);
3734
+ return;
3735
+ }
3736
+ let currentText;
3737
+ try {
3738
+ currentText = await client.getServerConfigurationXml();
3739
+ } catch (err) {
3740
+ fail(`cannot read the server's current configuration: ${err instanceof Error ? err.message : String(err)}. If its export is broken (for example HTTP 500), restore with --export-broken, which skips the preview and the undo backup`);
3741
+ }
3505
3742
  const current = parseBackup(currentText, "the server configuration");
3506
3743
  const serverId = await client.getServerId();
3507
- let chosen;
3508
- if (file) {
3509
- chosen = path6.resolve(file);
3510
- if (!existsSync6(chosen)) fail(`${chosen} does not exist`);
3511
- } else {
3512
- const mine = await backupsOf(dir, serverId);
3513
- if (mine.length === 0) {
3514
- const others = (await originsIn(dir)).map((o) => o.host);
3515
- fail(`no backups of ${target} in ${dir}${others.length ? ` (it has backups of: ${others.join(", ")})` : ""}`);
3516
- }
3517
- chosen = mine[mine.length - 1].file;
3518
- }
3519
- const text = await readFile5(chosen, "utf8");
3744
+ const chosen = await chooseBackup(dir, file, serverId, target);
3745
+ const text = await readFile6(chosen, "utf8");
3520
3746
  const backup = parseBackup(text, chosen);
3747
+ const unsafe = await xmlSafetyProblem(backup);
3748
+ if (unsafe) fail(`${chosen} holds ${unsafe}`);
3521
3749
  const origin = await originOf(dir, chosen);
3522
3750
  if (origin) {
3523
3751
  if (origin.serverId !== serverId && !flags.force) {
@@ -3528,7 +3756,7 @@ addBackupDirFlags(addConnectionFlags(
3528
3756
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
3529
3757
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
3530
3758
  }
3531
- process.stderr.write(`warning: ${chosen} is not in ${path6.join(dir, MANIFEST)}, so which server it came from cannot be checked
3759
+ process.stderr.write(`warning: ${chosen} is not in ${path8.join(dir, MANIFEST)}, so which server it came from cannot be checked
3532
3760
  `);
3533
3761
  }
3534
3762
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -3587,19 +3815,20 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3587
3815
  })
3588
3816
  ))).action(async (dir, flags) => {
3589
3817
  errorExitCode = 2;
3590
- const root = path6.resolve(dir);
3818
+ const root = path8.resolve(dir);
3591
3819
  assertTree(root);
3592
3820
  const fetched = await withClient(flags, (client) => client.getServerConfiguration());
3593
3821
  const tree = await engine.implode({ root });
3594
3822
  const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFilePath(root, flags)));
3595
3823
  const messages = [
3596
3824
  ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
3597
- ...notes
3825
+ ...notes,
3826
+ ...await xmlProblems(root, tree)
3598
3827
  ];
3599
3828
  const allow = await readAllow(root);
3600
3829
  const staleRevisions = newerOnServer(tree, templatedRemote);
3601
3830
  if (staleRevisions.length > 0) {
3602
- messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline`);
3831
+ messages.push(`${staleRevisions.length} resource(s) have a newer revision on the server; pull to update the tree's baseline, or adopt it when the content already matches`);
3603
3832
  }
3604
3833
  const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
3605
3834
  const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
@@ -3609,15 +3838,15 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3609
3838
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
3610
3839
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
3611
3840
  `);
3612
- const tmp = await mkdtemp(path6.join(tmpdir(), "channelvault-diff-"));
3841
+ const tmp = await mkdtemp(path8.join(tmpdir(), "channelvault-diff-"));
3613
3842
  try {
3614
- await engine.explode(treeView.config, { root: path6.join(tmp, "tree") });
3615
- await engine.explode(serverView.config, { root: path6.join(tmp, "server") });
3616
- await mkdir5(path6.join(tmp, ".empty"));
3843
+ await engine.explode(treeView.config, { root: path8.join(tmp, "tree") });
3844
+ await engine.explode(serverView.config, { root: path8.join(tmp, "server") });
3845
+ await mkdir5(path8.join(tmp, ".empty"));
3617
3846
  const chunks = [];
3618
3847
  for (const d of MANAGED_DIRS) {
3619
- const local = existsSync6(path6.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3620
- const server = existsSync6(path6.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3848
+ const local = existsSync6(path8.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
3849
+ const server = existsSync6(path8.join(tmp, "server", d)) ? `server/${d}` : ".empty";
3621
3850
  if (local === ".empty" && server === ".empty") continue;
3622
3851
  const result = spawnSync(
3623
3852
  "git",
@@ -3639,7 +3868,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3639
3868
  const clean = out === "" && secretDrift.length === 0;
3640
3869
  if (!clean) process.exitCode = 1;
3641
3870
  if (flags.json) {
3642
- const files = await changedFiles(path6.join(tmp, "tree"), path6.join(tmp, "server"));
3871
+ const files = await changedFiles(path8.join(tmp, "tree"), path8.join(tmp, "server"));
3643
3872
  writeJson2({ clean, files, secretDrift, staleRevisions, notes: messages, patch: out });
3644
3873
  } else if (clean) {
3645
3874
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
@@ -3655,22 +3884,12 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
3655
3884
  }
3656
3885
  });
3657
3886
  async function changedFiles(treeDir, serverDir) {
3658
- const list2 = async (base) => {
3659
- const out = [];
3660
- for (const d of MANAGED_DIRS) {
3661
- if (!existsSync6(path6.join(base, d))) continue;
3662
- for (const entry of await readdir5(path6.join(base, d), { recursive: true, withFileTypes: true })) {
3663
- if (entry.isFile()) out.push(path6.relative(base, path6.join(entry.parentPath, entry.name)).split(path6.sep).join("/"));
3664
- }
3665
- }
3666
- return out;
3667
- };
3668
- const [local, remote] = await Promise.all([list2(treeDir), list2(serverDir)]);
3887
+ const [local, remote] = await Promise.all([treeFiles(treeDir), treeFiles(serverDir)]);
3669
3888
  const remoteSet = new Set(remote);
3670
3889
  const files = [];
3671
3890
  for (const p of local) {
3672
3891
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
3673
- else if (await readFile5(path6.join(treeDir, p), "utf8") !== await readFile5(path6.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3892
+ else if (await readFile6(path8.join(treeDir, p), "utf8") !== await readFile6(path8.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
3674
3893
  }
3675
3894
  const localSet = new Set(local);
3676
3895
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
@@ -3679,16 +3898,25 @@ async function changedFiles(treeDir, serverDir) {
3679
3898
  addJsonFlag(addEnvFlag(
3680
3899
  program.command("status").description("Summarize a working tree").argument("<dir>", "working-tree directory")
3681
3900
  )).action(async (dir, flags) => {
3682
- const root = path6.resolve(dir);
3901
+ const root = path8.resolve(dir);
3683
3902
  assertTree(root);
3684
3903
  const config = await engine.implode({ root });
3685
3904
  const s = summarize(config);
3686
- const metaPath = path6.join(root, "channelvault.json");
3905
+ const metaPath = path8.join(root, "channelvault.json");
3687
3906
  const meta = existsSync6(metaPath) ? await readJson(metaPath) : null;
3688
3907
  if (flags.json) {
3689
- writeJson2({ root, source: meta?.source ?? null, pulledAt: meta?.pulledAt ?? null, engineVersion: meta?.engineVersion ?? null, counts: s });
3908
+ writeJson2({
3909
+ root,
3910
+ source: meta?.source ?? null,
3911
+ pulledAt: meta?.pulledAt ?? null,
3912
+ engineVersion: meta?.engineVersion ?? null,
3913
+ counts: s,
3914
+ xmlForbiddenChars: forbiddenXmlChars(config)
3915
+ });
3690
3916
  return;
3691
3917
  }
3918
+ for (const p of await xmlProblems(root, config)) process.stderr.write(`warning: ${p}
3919
+ `);
3692
3920
  if (meta) {
3693
3921
  process.stdout.write(`source: ${meta.source}
3694
3922
  `);
@@ -3710,7 +3938,7 @@ program.hook("preAction", async (_program, command) => {
3710
3938
  const name = command.name();
3711
3939
  if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name)) return;
3712
3940
  if (name === "diff") errorExitCode = 2;
3713
- const root = path6.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3941
+ const root = path8.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
3714
3942
  unlock = await lockTree(root);
3715
3943
  await recoverTree(root, envFilePath(root, command.opts()));
3716
3944
  });