@ubercode/channelvault 0.3.0-rc.4 → 0.3.0-rc.5

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 as spawnSync2 } from "child_process";
5
- import { cp, lstat as lstat4, mkdir as mkdir6, mkdtemp, readdir as readdir6, readFile as readFile6, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
- import { existsSync as existsSync8 } from "fs";
5
+ import { cp, lstat as lstat4, mkdir as mkdir7, mkdtemp, readdir as readdir6, readFile as readFile6, rm as rm4, writeFile as writeFile6 } from "fs/promises";
6
+ import { existsSync as existsSync9 } from "fs";
7
7
  import { tmpdir } from "os";
8
8
  import { createRequire } from "module";
9
- import * as path9 from "path";
9
+ import * as path10 from "path";
10
10
  import { createInterface } from "readline/promises";
11
11
  import { Writable } from "stream";
12
12
  import { Command, CommanderError } from "commander";
@@ -958,6 +958,29 @@ function hasPlaceholder(value) {
958
958
  PLACEHOLDER.lastIndex = 0;
959
959
  return PLACEHOLDER.test(value);
960
960
  }
961
+ function placeholderNames(config) {
962
+ const names = /* @__PURE__ */ new Set();
963
+ mapLeaves(config, (value) => {
964
+ for (const m of value.matchAll(PLACEHOLDER)) names.add(m[1]);
965
+ return value;
966
+ });
967
+ return names;
968
+ }
969
+ function placeholderUse(tree, server) {
970
+ const onServer = /* @__PURE__ */ new Set();
971
+ mapLeaves(server, (value, leaf) => {
972
+ onServer.add(leaf.location);
973
+ return value;
974
+ });
975
+ const compared = /* @__PURE__ */ new Set();
976
+ const treeOnly = /* @__PURE__ */ new Set();
977
+ mapLeaves(tree, (value, leaf) => {
978
+ for (const m of value.matchAll(PLACEHOLDER)) (onServer.has(leaf.location) ? compared : treeOnly).add(m[1]);
979
+ return value;
980
+ });
981
+ for (const name of compared) treeOnly.delete(name);
982
+ return { compared, treeOnly };
983
+ }
961
984
  function fill(value, env, missing) {
962
985
  return value.replace(PLACEHOLDER, (whole, name) => {
963
986
  const v = env[name];
@@ -1003,12 +1026,12 @@ function configMapKeyOf(entry) {
1003
1026
  return Array.isArray(key) && typeof key[0] === "string" ? key[0] : void 0;
1004
1027
  }
1005
1028
  function mapLeaves(config, visit) {
1006
- const walk = (node, key, path10, labels, section, cmKey) => {
1029
+ const walk = (node, key, path11, labels, section, cmKey) => {
1007
1030
  if (typeof node === "string") {
1008
- return visit(node, { location: path10.join("/"), key, labels, section, configMapKey: cmKey });
1031
+ return visit(node, { location: path11.join("/"), key, labels, section, configMapKey: cmKey });
1009
1032
  }
1010
1033
  if (Array.isArray(node)) {
1011
- return node.map((el, i) => walk(el, key, [...path10.slice(0, -1), `${path10[path10.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1034
+ return node.map((el, i) => walk(el, key, [...path11.slice(0, -1), `${path11[path11.length - 1]}${elementSegment(el, i)}`], labels, section, cmKey));
1012
1035
  }
1013
1036
  if (node && typeof node === "object") {
1014
1037
  const name = node["name"];
@@ -1016,7 +1039,7 @@ function mapLeaves(config, visit) {
1016
1039
  const mapKey = section === "configurationMap" && CONFIG_PROPERTY in node ? configMapKeyOf(node) : cmKey;
1017
1040
  const out = {};
1018
1041
  for (const [k, v] of Object.entries(node)) {
1019
- out[k] = walk(v, k, [...path10, k], inner, section || k, mapKey);
1042
+ out[k] = walk(v, k, [...path11, k], inner, section || k, mapKey);
1020
1043
  }
1021
1044
  return out;
1022
1045
  }
@@ -1643,6 +1666,10 @@ var MirthClientImpl = class {
1643
1666
  async putCodeTemplateLibraries(libraries) {
1644
1667
  await this.sendJson("PUT", "/codeTemplateLibraries", { list: { codeTemplateLibrary: libraries } }, { override: true });
1645
1668
  }
1669
+ /** PUT /server/configurationMap: replaces the whole map. */
1670
+ async putConfigurationMap(map) {
1671
+ await this.sendJson("PUT", "/server/configurationMap", { map });
1672
+ }
1646
1673
  async putGlobalScripts(globalScripts) {
1647
1674
  await this.sendJson("PUT", "/server/globalScripts", { map: globalScripts });
1648
1675
  }
@@ -1657,15 +1684,15 @@ var MirthClientImpl = class {
1657
1684
  await this.request("POST", `/channels/${encodeURIComponent(id)}/_deploy`, { query: { returnErrors: true } });
1658
1685
  }
1659
1686
  /** Send a JSON body; Mirth answers some updates with `{"boolean": false}` instead of an error status. */
1660
- async sendJson(method, path10, body, query) {
1661
- const response = await this.request(method, path10, {
1687
+ async sendJson(method, path11, body, query) {
1688
+ const response = await this.request(method, path11, {
1662
1689
  query,
1663
1690
  headers: { "Content-Type": "application/json", Accept: "application/json" },
1664
1691
  body: JSON.stringify(body)
1665
1692
  });
1666
1693
  const text = await response.text();
1667
1694
  if (/^\s*\{\s*"boolean"\s*:\s*false\s*\}\s*$/.test(text)) {
1668
- throw new Error(`${method} ${path10}: the server refused the update`);
1695
+ throw new Error(`${method} ${path11}: the server refused the update`);
1669
1696
  }
1670
1697
  }
1671
1698
  // --- internal transport ---------------------------------------------------
@@ -1674,11 +1701,11 @@ var MirthClientImpl = class {
1674
1701
  * on a 401 while authenticated resets auth, re-logs in once, and retries.
1675
1702
  * Throws an {@link ApiError}-shaped error on a non-2xx response.
1676
1703
  */
1677
- async request(method, path10, options = {}, isRetry = false) {
1704
+ async request(method, path11, options = {}, isRetry = false) {
1678
1705
  if (!this.authenticated) {
1679
1706
  await this.login();
1680
1707
  }
1681
- const url = this.buildUrl(path10, options.query);
1708
+ const url = this.buildUrl(path11, options.query);
1682
1709
  const headers = {
1683
1710
  "X-Requested-With": "XMLHttpRequest",
1684
1711
  ...options.headers
@@ -1692,7 +1719,7 @@ var MirthClientImpl = class {
1692
1719
  if (response.status === 401 && this.authenticated && !isRetry) {
1693
1720
  this.authenticated = false;
1694
1721
  await this.login();
1695
- return this.request(method, path10, options, true);
1722
+ return this.request(method, path11, options, true);
1696
1723
  }
1697
1724
  if (!response.ok) {
1698
1725
  throw await this.toApiError(response);
@@ -1723,8 +1750,8 @@ var MirthClientImpl = class {
1723
1750
  return response;
1724
1751
  }
1725
1752
  /** Build an absolute URL with an optional query string. */
1726
- buildUrl(path10, query) {
1727
- const url = `${this.baseUrl}${path10}`;
1753
+ buildUrl(path11, query) {
1754
+ const url = `${this.baseUrl}${path11}`;
1728
1755
  if (!query || Object.keys(query).length === 0) {
1729
1756
  return url;
1730
1757
  }
@@ -2358,20 +2385,139 @@ function connectionJson(conn, serverId, envFile) {
2358
2385
  }
2359
2386
 
2360
2387
  // src/push/index.ts
2388
+ import { createHash as createHash3 } from "crypto";
2389
+
2390
+ // src/push/configMap.ts
2361
2391
  import { createHash as createHash2 } from "crypto";
2362
2392
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2393
+ function configMapOf(c) {
2394
+ return isObj(c["configurationMap"]) ? list(c["configurationMap"]["entry"]) : [];
2395
+ }
2396
+ function byKey(entries) {
2397
+ const out = /* @__PURE__ */ new Map();
2398
+ for (const e of entries) {
2399
+ const k = configMapKeyOf(e);
2400
+ if (k !== void 0) out.set(k, e);
2401
+ }
2402
+ return out;
2403
+ }
2404
+ function contentOf(entry) {
2405
+ const p = entry[CONFIG_PROPERTY];
2406
+ const part = (name) => {
2407
+ const v = isObj(p) ? p[name] : void 0;
2408
+ return v === null || v === void 0 ? "" : normalizeEol(typeof v === "string" ? v : JSON.stringify(v));
2409
+ };
2410
+ return JSON.stringify([part("value"), part("comment")]);
2411
+ }
2412
+ function sameEntry(a, b) {
2413
+ if (!a || !b) return a === b;
2414
+ return contentOf(a) === contentOf(b);
2415
+ }
2416
+ function sameConfigMap(a, b) {
2417
+ return otherDifferingKeys(a, b, []).length === 0;
2418
+ }
2419
+ function withSortedConfigMap(c) {
2420
+ const holder = c["configurationMap"];
2421
+ if (!isObj(holder) || holder["entry"] === void 0) return c;
2422
+ const entry = [...configMapOf(c)].sort((x, y) => (configMapKeyOf(x) ?? "").localeCompare(configMapKeyOf(y) ?? "", "en"));
2423
+ return { ...c, configurationMap: { ...holder, entry } };
2424
+ }
2425
+ function digest(name, entry) {
2426
+ return createHash2("sha256").update(`${name}\0${contentOf(entry)}`).digest("hex");
2427
+ }
2428
+ function configMapBaseline(c) {
2429
+ return Object.fromEntries([...byKey(configMapOf(c))].map(([k, e]) => [k, digest(k, e)]));
2430
+ }
2431
+ function baselineAfterPush(baseline, server, names) {
2432
+ if (!baseline) return void 0;
2433
+ const now = byKey(configMapOf(server));
2434
+ const next = { ...baseline };
2435
+ for (const name of names) {
2436
+ const e = now.get(name);
2437
+ if (e) next[name] = digest(name, e);
2438
+ else delete next[name];
2439
+ }
2440
+ return next;
2441
+ }
2442
+ function conflictOf(name, server, baseline) {
2443
+ const what = `configuration-map key "${name}"`;
2444
+ if (!baseline) return `${what}: no configuration-map baseline for this installation on this machine; pull or adopt to record one`;
2445
+ const recorded = baseline[name];
2446
+ if (recorded === void 0) return server ? `${what} was created on the server since the last pull` : void 0;
2447
+ if (!server) return `${what} was deleted on the server since the last pull`;
2448
+ return digest(name, server) === recorded ? void 0 : `${what} changed on the server since the last pull`;
2449
+ }
2450
+ function planConfigMap(local, remote, names, baseline) {
2451
+ const tree = byKey(configMapOf(local));
2452
+ const server = byKey(configMapOf(remote));
2453
+ const plan = { changes: [], conflicts: [], unchanged: [] };
2454
+ for (const name of new Set(names)) {
2455
+ const t = tree.get(name);
2456
+ const s = server.get(name);
2457
+ if (!t && !s) throw new UnknownConfigMapKey(name);
2458
+ if (sameEntry(t, s)) {
2459
+ plan.unchanged.push(name);
2460
+ continue;
2461
+ }
2462
+ plan.changes.push({ kind: "configMapKey", op: !s ? "create" : !t ? "delete" : "update", id: name, label: name });
2463
+ const conflict = conflictOf(name, s, baseline);
2464
+ if (conflict) plan.conflicts.push(conflict);
2465
+ }
2466
+ return plan;
2467
+ }
2468
+ var UnknownConfigMapKey = class extends Error {
2469
+ constructor(key) {
2470
+ super(`no configuration-map key named "${key}" in the tree or on the server`);
2471
+ this.key = key;
2472
+ }
2473
+ key;
2474
+ };
2475
+ function configMapMoved(names, before, after) {
2476
+ const [b, a] = [byKey(configMapOf(before)), byKey(configMapOf(after))];
2477
+ return names.filter((n) => !sameEntry(b.get(n), a.get(n)));
2478
+ }
2479
+ function otherDifferingKeys(a, b, names) {
2480
+ const [x, y] = [byKey(configMapOf(a)), byKey(configMapOf(b))];
2481
+ const skip = new Set(names);
2482
+ return [.../* @__PURE__ */ new Set([...x.keys(), ...y.keys()])].filter((k) => !skip.has(k) && !sameEntry(x.get(k), y.get(k))).sort();
2483
+ }
2484
+ function mergeConfigMap(server, local, names) {
2485
+ const tree = byKey(configMapOf(local));
2486
+ const wanted = new Set(names);
2487
+ const placed = /* @__PURE__ */ new Set();
2488
+ const entry = [];
2489
+ for (const e of configMapOf(server)) {
2490
+ const k = configMapKeyOf(e);
2491
+ if (k === void 0 || !wanted.has(k)) {
2492
+ entry.push(e);
2493
+ continue;
2494
+ }
2495
+ placed.add(k);
2496
+ const t = tree.get(k);
2497
+ if (t) entry.push(structuredClone(t));
2498
+ }
2499
+ for (const n of wanted) {
2500
+ const t = tree.get(n);
2501
+ if (!placed.has(n) && t) entry.push(structuredClone(t));
2502
+ }
2503
+ const holder = isObj(server["configurationMap"]) ? server["configurationMap"] : {};
2504
+ return { ...holder, entry };
2505
+ }
2506
+
2507
+ // src/push/index.ts
2508
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
2363
2509
  function list(v) {
2364
2510
  if (v == null || v === "") return [];
2365
- return (Array.isArray(v) ? v : [v]).filter(isObj);
2511
+ return (Array.isArray(v) ? v : [v]).filter(isObj2);
2366
2512
  }
2367
2513
  function channelsOf(c) {
2368
- return isObj(c["channels"]) ? list(c["channels"]["channel"]) : [];
2514
+ return isObj2(c["channels"]) ? list(c["channels"]["channel"]) : [];
2369
2515
  }
2370
2516
  function librariesOf(c) {
2371
- return isObj(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
2517
+ return isObj2(c["codeTemplateLibraries"]) ? list(c["codeTemplateLibraries"]["codeTemplateLibrary"]) : [];
2372
2518
  }
2373
2519
  function templatesOf2(library) {
2374
- return isObj(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
2520
+ return isObj2(library["codeTemplates"]) ? list(library["codeTemplates"]["codeTemplate"]) : [];
2375
2521
  }
2376
2522
  var idOf = (o) => String(o["id"]);
2377
2523
  var nameOf = (o) => String(o["name"] ?? o["id"]);
@@ -2382,14 +2528,14 @@ function normalizeEol(s) {
2382
2528
  function normalizeEolDeep(value) {
2383
2529
  if (typeof value === "string") return normalizeEol(value);
2384
2530
  if (Array.isArray(value)) return value.map((v) => normalizeEolDeep(v));
2385
- if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
2531
+ if (isObj2(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalizeEolDeep(v)]));
2386
2532
  return value;
2387
2533
  }
2388
2534
  function same(a, b) {
2389
2535
  if (a === b) return true;
2390
2536
  if (typeof a === "string" && typeof b === "string") return normalizeEol(a) === normalizeEol(b);
2391
2537
  if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((x, i) => same(x, b[i]));
2392
- if (isObj(a) && isObj(b)) {
2538
+ if (isObj2(a) && isObj2(b)) {
2393
2539
  const ka = Object.keys(a);
2394
2540
  return ka.length === Object.keys(b).length && ka.every((k) => k in b && same(a[k], b[k]));
2395
2541
  }
@@ -2398,9 +2544,9 @@ function same(a, b) {
2398
2544
  var ASSOCIATIONS = ["channelTags", "dependentIds", "dependencyIds"];
2399
2545
  function withSortedContexts(o) {
2400
2546
  const set = o["contextSet"];
2401
- const delegate = isObj(set) ? set["delegate"] : void 0;
2402
- const types = isObj(delegate) ? delegate["contextType"] : void 0;
2403
- if (!isObj(set) || !isObj(delegate) || !Array.isArray(types)) return o;
2547
+ const delegate = isObj2(set) ? set["delegate"] : void 0;
2548
+ const types = isObj2(delegate) ? delegate["contextType"] : void 0;
2549
+ if (!isObj2(set) || !isObj2(delegate) || !Array.isArray(types)) return o;
2404
2550
  const sorted = [...types].sort((a, b) => String(a).localeCompare(String(b), "en"));
2405
2551
  return { ...o, contextSet: { ...set, delegate: { ...delegate, contextType: sorted } } };
2406
2552
  }
@@ -2409,8 +2555,8 @@ function stripVolatile(o) {
2409
2555
  delete out["revision"];
2410
2556
  delete out["lastModified"];
2411
2557
  const exportData = out["exportData"];
2412
- if (isObj(exportData)) {
2413
- const metadata = isObj(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
2558
+ if (isObj2(exportData)) {
2559
+ const metadata = isObj2(exportData["metadata"]) ? { ...exportData["metadata"] } : void 0;
2414
2560
  if (metadata) {
2415
2561
  delete metadata["lastModified"];
2416
2562
  delete metadata["userId"];
@@ -2419,22 +2565,22 @@ function stripVolatile(o) {
2419
2565
  }
2420
2566
  return out;
2421
2567
  }
2422
- var groupsOf = (c) => isObj(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
2568
+ var groupsOf = (c) => isObj2(c["channelGroups"]) ? list(c["channelGroups"]["channelGroup"]) : [];
2423
2569
  function withoutVolatile(c) {
2424
2570
  const out = structuredClone(c);
2425
2571
  const strip = (o) => {
2426
2572
  delete o["revision"];
2427
2573
  delete o["lastModified"];
2428
2574
  const exportData = o["exportData"];
2429
- const md = isObj(exportData) ? exportData["metadata"] : void 0;
2430
- if (isObj(md)) {
2575
+ const md = isObj2(exportData) ? exportData["metadata"] : void 0;
2576
+ if (isObj2(md)) {
2431
2577
  delete md["lastModified"];
2432
2578
  delete md["userId"];
2433
2579
  }
2434
- if (isObj(exportData)) {
2580
+ if (isObj2(exportData)) {
2435
2581
  for (const key of ASSOCIATIONS) if (exportData[key] === null) delete exportData[key];
2436
2582
  }
2437
- if (isObj(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
2583
+ if (isObj2(o["contextSet"])) o["contextSet"] = withSortedContexts(o)["contextSet"];
2438
2584
  };
2439
2585
  for (const ch of channelsOf(out)) strip(ch);
2440
2586
  for (const lib of librariesOf(out)) {
@@ -2443,7 +2589,7 @@ function withoutVolatile(c) {
2443
2589
  }
2444
2590
  for (const g of groupsOf(out)) {
2445
2591
  strip(g);
2446
- for (const member of isObj(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
2592
+ for (const member of isObj2(g["channels"]) ? list(g["channels"]["channel"]) : []) delete member["revision"];
2447
2593
  }
2448
2594
  return out;
2449
2595
  }
@@ -2471,12 +2617,12 @@ function withRetainedMembers(local, remote, localIds, deletedIds) {
2471
2617
  const retained = templatesOf2(remote).filter((t) => !localIds.has(idOf(t)) && !deletedIds.has(idOf(t)));
2472
2618
  if (!retained.length) return local;
2473
2619
  return { ...local, codeTemplates: {
2474
- ...isObj(local["codeTemplates"]) ? local["codeTemplates"] : {},
2620
+ ...isObj2(local["codeTemplates"]) ? local["codeTemplates"] : {},
2475
2621
  codeTemplate: [...templatesOf2(local), ...retained]
2476
2622
  } };
2477
2623
  }
2478
2624
  function hashGlobalScripts(c) {
2479
- return createHash2("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
2625
+ return createHash3("sha256").update(JSON.stringify(normalizeEolDeep(c["globalScripts"] ?? null))).digest("hex");
2480
2626
  }
2481
2627
  function resourceIds(c) {
2482
2628
  const libs = librariesOf(c);
@@ -2508,7 +2654,7 @@ function adoptTarget(local, target) {
2508
2654
  return { config, known };
2509
2655
  }
2510
2656
  function knownFrom(raw) {
2511
- if (!isObj(raw)) return void 0;
2657
+ if (!isObj2(raw)) return void 0;
2512
2658
  const r = raw;
2513
2659
  const map = (v) => Array.isArray(v) ? Object.fromEntries(v.map((id) => [String(id), null])) : v ?? {};
2514
2660
  return {
@@ -2568,7 +2714,7 @@ function librariesInSync(local, remote) {
2568
2714
  }).map(idOf);
2569
2715
  }
2570
2716
  function channelsUsing(lib, allChannelIds) {
2571
- const ids = (v) => isObj(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
2717
+ const ids = (v) => isObj2(v) ? (Array.isArray(v["string"]) ? v["string"] : v["string"] != null ? [v["string"]] : []).map(String) : [];
2572
2718
  if (lib["includeNewChannels"] === true) {
2573
2719
  const disabled = new Set(ids(lib["disabledChannelIds"]));
2574
2720
  return allChannelIds.filter((id) => !disabled.has(id));
@@ -2713,11 +2859,11 @@ rename one of them, or delete or rename the other in a push of its own first`
2713
2859
  conflicts.push("global scripts changed on the server since the last pull");
2714
2860
  }
2715
2861
  }
2716
- const notPushed = everything ? [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].filter((k) => !HANDLED.has(k) && !k.startsWith("@") && !same(local[k], remote[k])).sort() : [];
2862
+ const notPushed = everything ? [.../* @__PURE__ */ new Set([...Object.keys(local), ...Object.keys(remote)])].filter((k) => !HANDLED.has(k) && !k.startsWith("@") && !(k === "configurationMap" ? sameConfigMap(local, remote) : same(local[k], remote[k]))).sort() : [];
2717
2863
  const enabled = new Set(
2718
2864
  [...effective.values()].filter((c) => {
2719
- const md = isObj(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
2720
- return !(isObj(md) && md["enabled"] === false);
2865
+ const md = isObj2(c["exportData"]) ? c["exportData"]["metadata"] : void 0;
2866
+ return !(isObj2(md) && md["enabled"] === false);
2721
2867
  }).map(idOf)
2722
2868
  );
2723
2869
  return {
@@ -2947,24 +3093,47 @@ async function refreshRevisions(root, server, ids) {
2947
3093
  }
2948
3094
  }
2949
3095
 
3096
+ // src/configMapBaselines.ts
3097
+ import { createHash as createHash4 } from "crypto";
3098
+ import { existsSync as existsSync7 } from "fs";
3099
+ import { mkdir as mkdir5 } from "fs/promises";
3100
+ import * as path7 from "path";
3101
+ var BASELINES_DIR = "config-map-baselines";
3102
+ function fileFor(serverId) {
3103
+ return path7.join(configDir(), BASELINES_DIR, `${createHash4("sha256").update(serverId).digest("hex").slice(0, 32)}.json`);
3104
+ }
3105
+ async function readConfigMapBaseline(serverId) {
3106
+ const file = fileFor(serverId);
3107
+ if (!existsSync7(file)) return void 0;
3108
+ const stored = await readJson(file);
3109
+ if (stored.serverId !== serverId || typeof stored.entries !== "object" || stored.entries === null) return void 0;
3110
+ return stored.entries;
3111
+ }
3112
+ async function writeConfigMapBaseline(serverId, entries) {
3113
+ const file = fileFor(serverId);
3114
+ await mkdir5(path7.dirname(file), { recursive: true, mode: 448 });
3115
+ await writePrivate(file, `${JSON.stringify({ serverId, entries }, null, 2)}
3116
+ `);
3117
+ }
3118
+
2950
3119
  // src/xml/chars.ts
2951
3120
  import { readFile as readFile5 } from "fs/promises";
2952
- import * as path8 from "path";
3121
+ import * as path9 from "path";
2953
3122
 
2954
3123
  // src/tree/transaction.ts
2955
3124
  import { randomUUID } from "crypto";
2956
- import { constants, existsSync as existsSync7 } from "fs";
2957
- import { copyFile as copyFile2, lstat as lstat3, mkdir as mkdir5, readdir as readdir5, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
3125
+ import { constants, existsSync as existsSync8 } from "fs";
3126
+ import { copyFile as copyFile2, lstat as lstat3, mkdir as mkdir6, readdir as readdir5, rename as rename3, rm as rm3, rmdir, unlink, writeFile as writeFile5 } from "fs/promises";
2958
3127
  import { hostname } from "os";
2959
- import * as path7 from "path";
3128
+ import * as path8 from "path";
2960
3129
  import { setTimeout as delay } from "timers/promises";
2961
3130
  var MANAGED_DIRS = ["server", "channels", "codeTemplates", "channelGroups"];
2962
3131
  async function treeFiles(base) {
2963
3132
  const out = [];
2964
3133
  for (const d of MANAGED_DIRS) {
2965
- if (!existsSync7(path7.join(base, d))) continue;
2966
- for (const entry of await readdir5(path7.join(base, d), { recursive: true, withFileTypes: true })) {
2967
- if (entry.isFile()) out.push(path7.relative(base, path7.join(entry.parentPath, entry.name)).split(path7.sep).join("/"));
3134
+ if (!existsSync8(path8.join(base, d))) continue;
3135
+ for (const entry of await readdir5(path8.join(base, d), { recursive: true, withFileTypes: true })) {
3136
+ if (entry.isFile()) out.push(path8.relative(base, path8.join(entry.parentPath, entry.name)).split(path8.sep).join("/"));
2968
3137
  }
2969
3138
  }
2970
3139
  return out;
@@ -2985,12 +3154,12 @@ async function move(from, to) {
2985
3154
  }
2986
3155
  }
2987
3156
  async function lockTree(root) {
2988
- await mkdir5(path7.dirname(root), { recursive: true });
3157
+ await mkdir6(path8.dirname(root), { recursive: true });
2989
3158
  const lock = `${await canonical(root)}.channelvault-lock`;
2990
- const ownerFile = path7.join(lock, "owner.json");
3159
+ const ownerFile = path8.join(lock, "owner.json");
2991
3160
  const owner = { pid: process.pid, host: hostname(), token: randomUUID() };
2992
3161
  try {
2993
- await mkdir5(lock);
3162
+ await mkdir6(lock);
2994
3163
  } catch (err) {
2995
3164
  if (err.code !== "EEXIST") throw err;
2996
3165
  if ((await lstat3(lock)).isSymbolicLink()) throw new Error(`refusing a linked working-tree lock: ${lock}`);
@@ -3010,9 +3179,9 @@ async function lockTree(root) {
3010
3179
  }
3011
3180
  };
3012
3181
  if (!dead()) throw new Error(`working tree is locked by process ${previous.pid} on ${previous.host}: ${lock}`);
3013
- const reaping = path7.join(lock, "reaping");
3182
+ const reaping = path8.join(lock, "reaping");
3014
3183
  try {
3015
- await mkdir5(reaping);
3184
+ await mkdir6(reaping);
3016
3185
  } catch {
3017
3186
  throw new Error(`another process is recovering the working-tree lock: ${lock}; retry`);
3018
3187
  }
@@ -3024,7 +3193,7 @@ async function lockTree(root) {
3024
3193
  await rmdir(reaping);
3025
3194
  }
3026
3195
  await rmdir(lock);
3027
- await mkdir5(lock);
3196
+ await mkdir6(lock);
3028
3197
  }
3029
3198
  try {
3030
3199
  await writeFile5(ownerFile, JSON.stringify(owner), { flag: "wx", mode: 384 });
@@ -3041,7 +3210,7 @@ async function lockTree(root) {
3041
3210
  }
3042
3211
  async function assertStage(root) {
3043
3212
  for (const suffix of ["", "next", "previous"]) {
3044
- const stage = path7.join(root, STAGING_DIR, suffix);
3213
+ const stage = path8.join(root, STAGING_DIR, suffix);
3045
3214
  const info = await lstat3(stage).catch((err) => {
3046
3215
  if (err.code !== "ENOENT") throw err;
3047
3216
  return void 0;
@@ -3050,10 +3219,10 @@ async function assertStage(root) {
3050
3219
  }
3051
3220
  }
3052
3221
  function targetOf(root, journal, name) {
3053
- return name === "env" ? journal.envFile : path7.join(root, name);
3222
+ return name === "env" ? journal.envFile : path8.join(root, name);
3054
3223
  }
3055
3224
  function copies(root, journal, name) {
3056
- return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path7.join(root, STAGING_DIR, "previous", name), next: path7.join(root, STAGING_DIR, "next", name) };
3225
+ return name === "env" ? { old: `${journal.envFile}.channelvault-${journal.id}.previous`, next: `${journal.envFile}.channelvault-${journal.id}.next` } : { old: path8.join(root, STAGING_DIR, "previous", name), next: path8.join(root, STAGING_DIR, "next", name) };
3057
3226
  }
3058
3227
  async function cleanup(root, journal) {
3059
3228
  if (journal.entries.some((e) => e.name === "env")) {
@@ -3061,7 +3230,7 @@ async function cleanup(root, journal) {
3061
3230
  await rm3(old, { force: true });
3062
3231
  await rm3(next, { force: true });
3063
3232
  }
3064
- await rm3(path7.join(root, STAGING_DIR), RM);
3233
+ await rm3(path8.join(root, STAGING_DIR), RM);
3065
3234
  }
3066
3235
  async function rollback(root, journal) {
3067
3236
  for (const entry of [...journal.entries].reverse()) {
@@ -3076,14 +3245,14 @@ async function rollback(root, journal) {
3076
3245
  }
3077
3246
  }
3078
3247
  async function pendingEnvFile(root) {
3079
- const file = path7.join(root, JOURNAL);
3080
- if (!existsSync7(file)) return null;
3248
+ const file = path8.join(root, JOURNAL);
3249
+ if (!existsSync8(file)) return null;
3081
3250
  const journal = await readJson(file).catch(() => null);
3082
3251
  return typeof journal?.envFile === "string" ? journal.envFile : null;
3083
3252
  }
3084
3253
  async function recoverTree(root, envFiles) {
3085
- const file = path7.join(root, JOURNAL);
3086
- if (!existsSync7(file)) return;
3254
+ const file = path8.join(root, JOURNAL);
3255
+ if (!existsSync8(file)) return;
3087
3256
  await assertStage(root);
3088
3257
  const journal = await readJson(file);
3089
3258
  const allowed = await Promise.all((Array.isArray(envFiles) ? envFiles : [envFiles]).map((f) => canonical(f)));
@@ -3097,17 +3266,17 @@ async function recoverTree(root, envFiles) {
3097
3266
  async function replaceTree(root, envFile, prepare) {
3098
3267
  await recoverTree(root, envFile);
3099
3268
  await assertStage(root);
3100
- const stage = path7.join(root, STAGING_DIR);
3269
+ const stage = path8.join(root, STAGING_DIR);
3101
3270
  await rm3(stage, RM);
3102
- const next = path7.join(stage, "next");
3103
- await mkdir5(next, { recursive: true });
3271
+ const next = path8.join(stage, "next");
3272
+ await mkdir6(next, { recursive: true });
3104
3273
  let journal;
3105
3274
  try {
3106
3275
  await prepare(next);
3107
3276
  const targetEnv = await canonical(envFile);
3108
3277
  journal = { version: 1, id: randomUUID(), state: "prepared", envFile: targetEnv, entries: [] };
3109
3278
  for (const name of ITEMS) {
3110
- if (!MANAGED_DIRS.includes(name) && !existsSync7(path7.join(next, name === "env" ? ".env" : name))) continue;
3279
+ if (!MANAGED_DIRS.includes(name) && !existsSync8(path8.join(next, name === "env" ? ".env" : name))) continue;
3111
3280
  const target = targetOf(root, journal, name);
3112
3281
  const info = await lstat3(target).catch((err) => {
3113
3282
  if (err.code !== "ENOENT") throw err;
@@ -3115,38 +3284,38 @@ async function replaceTree(root, envFile, prepare) {
3115
3284
  });
3116
3285
  journal.entries.push({ name, hadOld: info !== void 0 });
3117
3286
  }
3118
- await mkdir5(path7.join(stage, "previous"));
3119
- await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
3287
+ await mkdir6(path8.join(stage, "previous"));
3288
+ await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
3120
3289
  if (journal.entries.some((e) => e.name === "env")) {
3121
- await mkdir5(path7.dirname(targetEnv), { recursive: true });
3122
- await copyFile2(path7.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
3290
+ await mkdir6(path8.dirname(targetEnv), { recursive: true });
3291
+ await copyFile2(path8.join(next, ".env"), copies(root, journal, "env").next, constants.COPYFILE_EXCL);
3123
3292
  }
3124
3293
  for (const entry of journal.entries) {
3125
3294
  const target = targetOf(root, journal, entry.name);
3126
3295
  const files = copies(root, journal, entry.name);
3127
3296
  if (entry.hadOld) await move(target, files.old);
3128
- if (existsSync7(files.next)) {
3129
- await mkdir5(path7.dirname(target), { recursive: true });
3297
+ if (existsSync8(files.next)) {
3298
+ await mkdir6(path8.dirname(target), { recursive: true });
3130
3299
  await move(files.next, target);
3131
3300
  }
3132
3301
  }
3133
3302
  journal.state = "committed";
3134
- await writePrivate(path7.join(root, JOURNAL), JSON.stringify(journal));
3303
+ await writePrivate(path8.join(root, JOURNAL), JSON.stringify(journal));
3135
3304
  } catch (err) {
3136
- if (journal && existsSync7(path7.join(root, JOURNAL))) {
3305
+ if (journal && existsSync8(path8.join(root, JOURNAL))) {
3137
3306
  try {
3138
3307
  await rollback(root, journal);
3139
3308
  } catch (recoveryError) {
3140
- throw new Error(`replacement failed and recovery is pending in ${path7.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
3309
+ throw new Error(`replacement failed and recovery is pending in ${path8.join(root, JOURNAL)}; retry this command with the same env file`, { cause: recoveryError });
3141
3310
  }
3142
3311
  await cleanup(root, journal);
3143
- await unlink(path7.join(root, JOURNAL));
3312
+ await unlink(path8.join(root, JOURNAL));
3144
3313
  }
3145
3314
  await rm3(stage, RM);
3146
3315
  throw err;
3147
3316
  }
3148
3317
  await cleanup(root, journal);
3149
- await unlink(path7.join(root, JOURNAL));
3318
+ await unlink(path8.join(root, JOURNAL));
3150
3319
  }
3151
3320
 
3152
3321
  // src/xml/chars.ts
@@ -3173,7 +3342,7 @@ function forbiddenXmlChars(config) {
3173
3342
  async function forbiddenInFiles(root) {
3174
3343
  const out = [];
3175
3344
  for (const file of await treeFiles(root)) {
3176
- for (const p of positions(await readFile5(path8.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
3345
+ for (const p of positions(await readFile5(path9.join(root, file), "utf8"))) out.push(`${file}:${p.line}:${p.column} (${p.codePoint})`);
3177
3346
  }
3178
3347
  return out;
3179
3348
  }
@@ -3267,7 +3436,7 @@ function addBackupDirFlags(cmd) {
3267
3436
  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})`);
3268
3437
  }
3269
3438
  function backupDirOf(flags) {
3270
- return path9.resolve(flags.backupDir ?? defaultBackupDir());
3439
+ return path10.resolve(flags.backupDir ?? defaultBackupDir());
3271
3440
  }
3272
3441
  function keepOf(flags) {
3273
3442
  if (flags.keep === void 0) return DEFAULT_KEEP;
@@ -3372,9 +3541,18 @@ function summarize(config) {
3372
3541
  codeTemplates
3373
3542
  };
3374
3543
  }
3544
+ async function recordConfigMapBaseline(serverId, baseline) {
3545
+ if (!serverId) return;
3546
+ try {
3547
+ await writeConfigMapBaseline(serverId, baseline);
3548
+ } catch (err) {
3549
+ process.stderr.write(`note: could not record the configuration-map baseline (${err instanceof Error ? err.message : String(err)}); pushing configuration-map keys will need a pull that can
3550
+ `);
3551
+ }
3552
+ }
3375
3553
  async function readMeta(root) {
3376
- const metaPath = path9.join(root, "channelvault.json");
3377
- if (!existsSync8(metaPath)) return null;
3554
+ const metaPath = path10.join(root, "channelvault.json");
3555
+ if (!existsSync9(metaPath)) return null;
3378
3556
  let meta;
3379
3557
  try {
3380
3558
  meta = await readJson(metaPath);
@@ -3399,33 +3577,33 @@ async function writeMeta(root, source, config, previous, serverId, resources = r
3399
3577
  resources,
3400
3578
  serverId
3401
3579
  };
3402
- const file = path9.join(root, "channelvault.json");
3580
+ const file = path10.join(root, "channelvault.json");
3403
3581
  if (previous && JSON.stringify({ ...previous, pulledAt: "" }) === JSON.stringify({ ...meta, pulledAt: "" })) meta.pulledAt = previous.pulledAt;
3404
3582
  await writeFile6(file, JSON.stringify(meta, null, 2) + "\n", "utf8");
3405
3583
  }
3406
3584
  async function envFileFor(root, flags, conn) {
3407
- if (flags.dotenv) return path9.resolve(flags.dotenv);
3408
- const local = path9.join(root, ".env");
3585
+ if (flags.dotenv) return path10.resolve(flags.dotenv);
3586
+ const local = path10.join(root, ".env");
3409
3587
  if (!conn?.dotenv) return local;
3410
- if (!existsSync8(local) || samePath(await canonical(local), await canonical(conn.dotenv))) {
3588
+ if (!existsSync9(local) || samePath(await canonical(local), await canonical(conn.dotenv))) {
3411
3589
  await assertNoSwapPending(conn.dotenv);
3412
3590
  return conn.dotenv;
3413
3591
  }
3414
3592
  fail(`both ${local} and profile ${conn.profile}'s env file ${conn.dotenv} exist; pass --dotenv to choose one, or remove the one that is stale`, "env-ambiguous");
3415
3593
  }
3416
3594
  async function assertNoSwapPending(file) {
3417
- const dir = path9.dirname(file);
3418
- if (!existsSync8(dir)) return;
3419
- const prefix = `${path9.basename(file)}.channelvault-`;
3595
+ const dir = path10.dirname(file);
3596
+ if (!existsSync9(dir)) return;
3597
+ const prefix = `${path10.basename(file)}.channelvault-`;
3420
3598
  const pending = (await readdir6(dir)).filter((n) => n.startsWith(prefix) && /\.(next|previous)$/.test(n));
3421
3599
  if (pending.length > 0) {
3422
3600
  fail(`${file} is being replaced by a pull in another checkout (${pending.join(", ")} beside it); retry when it finishes, or rerun that checkout's command to finish an interrupted one`, "env-busy");
3423
3601
  }
3424
3602
  }
3425
3603
  async function recoveryCandidates(root, flags) {
3426
- if (flags.dotenv) return [path9.resolve(flags.dotenv)];
3604
+ if (flags.dotenv) return [path10.resolve(flags.dotenv)];
3427
3605
  const dotenvs = Object.values(await loadProfiles()).flatMap((p) => p.dotenv ? [p.dotenv] : []);
3428
- return [path9.join(root, ".env"), ...dotenvs];
3606
+ return [path10.join(root, ".env"), ...dotenvs];
3429
3607
  }
3430
3608
  async function loadEnv(file) {
3431
3609
  return { ...await readEnvFile(file), ...process.env };
@@ -3437,7 +3615,7 @@ function addExtractFlag(cmd) {
3437
3615
  return cmd.option("--extract-secrets", "move secrets found inside values (URLs, scripts, headers) to the env file", false);
3438
3616
  }
3439
3617
  async function existingTree(root) {
3440
- return existsSync8(path9.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3618
+ return existsSync9(path10.join(root, "server", "configuration.json")) ? engine.implode({ root }) : null;
3441
3619
  }
3442
3620
  async function renderedTree(root, envFile) {
3443
3621
  const tree = await engine.implode({ root });
@@ -3453,10 +3631,19 @@ function rememberSecret(value, opts = {}) {
3453
3631
  if (opts.stdout && value.length >= 8) everywhereSecrets.add(value);
3454
3632
  }
3455
3633
  function rememberSecrets(tree, env) {
3456
- mapLeaves(tree, (value) => {
3457
- for (const m of value.matchAll(/\{\{env:([A-Za-z_][A-Za-z0-9_]*)\}\}/g)) rememberSecret(env[m[1]]);
3458
- return value;
3459
- });
3634
+ for (const name of placeholderNames(tree)) rememberSecret(env[name]);
3635
+ }
3636
+ function assertEnvComplete(tree, server, env, envFile, conn) {
3637
+ const { compared, treeOnly } = placeholderUse(tree, server);
3638
+ const unset = (names) => [...names].filter((name) => env[name] === void 0).sort();
3639
+ const missing = unset(compared);
3640
+ if (missing.length > 0) {
3641
+ const fix = conn.dotenv && samePath(envFile, conn.dotenv) ? `set them in profile ${conn.profile}'s env file, or pass --dotenv <file>` : `pass --dotenv <file>, or ${conn.profile ? `set profile ${conn.profile}'s dotenv` : "use a connection profile with a dotenv"}`;
3642
+ const what = `no value for ${missing.join(", ")}, so those secrets can't be compared`;
3643
+ if (!existsSync9(envFile)) fail(`there is no env file at ${envFile}: ${what}; ${fix}`, "env-missing");
3644
+ fail(`${envFile} has ${what}; add them, or ${fix}`, "env-incomplete");
3645
+ }
3646
+ return unset(treeOnly);
3460
3647
  }
3461
3648
  for (const stream of [process.stdout, process.stderr]) {
3462
3649
  const write = stream.write.bind(stream);
@@ -3478,8 +3665,8 @@ function scrub(text, secrets = knownSecrets) {
3478
3665
  }
3479
3666
  var ALLOW_FILE = "channelvault.allow.json";
3480
3667
  async function readAllow(root) {
3481
- const file = path9.join(root, ALLOW_FILE);
3482
- if (!existsSync8(file)) return [];
3668
+ const file = path10.join(root, ALLOW_FILE);
3669
+ if (!existsSync9(file)) return [];
3483
3670
  const parsed = await readJson(file);
3484
3671
  return parsed.ignore ?? [];
3485
3672
  }
@@ -3503,30 +3690,31 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3503
3690
  const envUpdates = { ...templated.envUpdates, ...scan.envUpdates };
3504
3691
  rememberSecrets(config, { ...env, ...envUpdates });
3505
3692
  const echoes = findEchoes(config, { ...await readEnvFile(envFile), ...envUpdates });
3506
- const rel = path9.relative(root, envFile);
3507
- const envInTree = !rel.startsWith("..") && !path9.isAbsolute(rel);
3693
+ const rel = path10.relative(root, envFile);
3694
+ const envInTree = !rel.startsWith("..") && !path10.isAbsolute(rel);
3508
3695
  let backup = null;
3509
3696
  await replaceTree(root, envFile, async (next) => {
3510
3697
  await engine.explode(config, { root: next });
3511
3698
  await writeMeta(next, source, fetched, previousMeta, serverId);
3512
3699
  if (Object.keys(envUpdates).length > 0) {
3513
- const history = path9.join(root, ".secrets");
3514
- if (existsSync8(history)) {
3700
+ const history = path10.join(root, ".secrets");
3701
+ if (existsSync9(history)) {
3515
3702
  if ((await lstat4(history)).isSymbolicLink()) fail(`refusing a linked secret history directory: ${history}`);
3516
- await cp(history, path9.join(next, ".secrets"), { recursive: true });
3703
+ await cp(history, path10.join(next, ".secrets"), { recursive: true });
3517
3704
  }
3518
- const stagedBackup = await backupEnvFile(envFile, envUpdates, path9.join(next, ".secrets"));
3519
- if (stagedBackup) backup = path9.join(root, ".secrets", path9.basename(stagedBackup));
3705
+ const stagedBackup = await backupEnvFile(envFile, envUpdates, path10.join(next, ".secrets"));
3706
+ if (stagedBackup) backup = path10.join(root, ".secrets", path10.basename(stagedBackup));
3520
3707
  if (backup || envInTree) {
3521
- const ignore = path9.join(root, ".gitignore");
3522
- if (existsSync8(ignore)) await writeFile6(path9.join(next, ".gitignore"), await readFile6(ignore));
3708
+ const ignore = path10.join(root, ".gitignore");
3709
+ if (existsSync9(ignore)) await writeFile6(path10.join(next, ".gitignore"), await readFile6(ignore));
3523
3710
  await ensureEnvIgnored(next, envInTree ? envFile : void 0, root);
3524
3711
  }
3525
- const stagedEnv = path9.join(next, ".env");
3526
- if (existsSync8(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3712
+ const stagedEnv = path10.join(next, ".env");
3713
+ if (existsSync9(envFile)) await writeFile6(stagedEnv, await readFile6(envFile), { mode: 384 });
3527
3714
  await updateEnvFile(stagedEnv, envUpdates);
3528
3715
  }
3529
3716
  });
3717
+ await recordConfigMapBaseline(serverId, configMapBaseline(fetched));
3530
3718
  if (scan.findings.length > 0) process.stdout.write(`extracted ${scan.findings.length} secret(s) found in values
3531
3719
  `);
3532
3720
  const updated = Object.keys(envUpdates).length;
@@ -3540,24 +3728,24 @@ Rerun with --extract-secrets to move them to ${envFile}, or list false positives
3540
3728
  process.stderr.write(`warning: the value of ${e.name} also appears in plain text at ${e.where}
3541
3729
  `);
3542
3730
  }
3543
- if (existsSync8(envFile) && gitWouldCommit(envFile)) {
3731
+ if (existsSync9(envFile) && gitWouldCommit(envFile)) {
3544
3732
  process.stderr.write(`warning: git does not ignore ${envFile}, so its secret values could be committed; add it to .gitignore
3545
3733
  `);
3546
3734
  }
3547
3735
  }
3548
3736
  function gitWouldCommit(file) {
3549
- const r = spawnSync2("git", ["check-ignore", "-q", path9.basename(file)], { cwd: path9.dirname(file) });
3737
+ const r = spawnSync2("git", ["check-ignore", "-q", path10.basename(file)], { cwd: path10.dirname(file) });
3550
3738
  return r.status === 1;
3551
3739
  }
3552
3740
  async function preflightTree(root, envFile) {
3553
3741
  const [realRoot, realEnv] = await Promise.all([resolvedPath(root), resolvedPath(envFile)]);
3554
3742
  const doomed = [...MANAGED_DIRS, STAGING_DIR, JOURNAL, "channelvault.json", ".gitignore", ".secrets"].find(
3555
- (d) => isWithin(path9.resolve(envFile), path9.resolve(root, d)) || isWithin(realEnv, path9.join(realRoot, d))
3743
+ (d) => isWithin(path10.resolve(envFile), path10.resolve(root, d)) || isWithin(realEnv, path10.join(realRoot, d))
3556
3744
  );
3557
3745
  if (doomed) fail(`the env file ${envFile} is inside ${doomed}/, which this command replaces; keep it elsewhere`);
3558
3746
  const meta = await readMeta(root);
3559
3747
  if (meta) return meta;
3560
- const foreign = MANAGED_DIRS.filter((d) => existsSync8(path9.join(root, d)));
3748
+ const foreign = MANAGED_DIRS.filter((d) => existsSync9(path10.join(root, d)));
3561
3749
  if (foreign.length > 0) {
3562
3750
  fail(
3563
3751
  `${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).`
@@ -3566,7 +3754,7 @@ async function preflightTree(root, envFile) {
3566
3754
  return null;
3567
3755
  }
3568
3756
  function assertTree(root) {
3569
- if (!existsSync8(path9.join(root, "server", "configuration.json"))) {
3757
+ if (!existsSync9(path10.join(root, "server", "configuration.json"))) {
3570
3758
  fail(`${root} is not a channelvault tree (missing server/configuration.json). Run 'pull' or 'explode' first.`);
3571
3759
  }
3572
3760
  }
@@ -3618,15 +3806,24 @@ async function writeKnown(root, known) {
3618
3806
  const meta = await readMeta(root);
3619
3807
  if (!meta?.resources) return;
3620
3808
  meta.resources = known;
3621
- await writeFile6(path9.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
3809
+ await writeFile6(path10.join(root, "channelvault.json"), JSON.stringify(meta, null, 2) + "\n", "utf8");
3622
3810
  }
3623
3811
  function printNameChange(incoming, current) {
3624
3812
  const [to, from] = [configuredName(incoming), configuredName(current)];
3625
3813
  if (to !== from) process.stdout.write(`server name changes: ${from || "(none)"} -> ${to || "(none)"}
3626
3814
  `);
3627
3815
  }
3816
+ function withConfigMap(plan, map) {
3817
+ return { ...plan, changes: [...map.changes, ...plan.changes], conflicts: [...map.conflicts, ...plan.conflicts] };
3818
+ }
3628
3819
  function printChanges(plan) {
3629
- const kindLabel = { channel: "channel", library: "library", codeTemplate: "code template", globalScripts: "" };
3820
+ const kindLabel = {
3821
+ channel: "channel",
3822
+ library: "library",
3823
+ codeTemplate: "code template",
3824
+ globalScripts: "",
3825
+ configMapKey: "configuration-map key"
3826
+ };
3630
3827
  for (const c of plan.changes) process.stdout.write(` ${c.op.padEnd(6)} ${`${kindLabel[c.kind]} ${c.label}`.trim()}
3631
3828
  `);
3632
3829
  }
@@ -3641,7 +3838,7 @@ pull (and merge) first, or pass --force to overwrite the server's version`
3641
3838
  }
3642
3839
  const deletes = plan.changes.filter((c) => c.op === "delete").length;
3643
3840
  if (deletes > 0 && !flags.allowDeletes) {
3644
- problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow with --channel/--library`);
3841
+ problems.push(`the plan deletes ${deletes} resource(s) from the server; pass --allow-deletes, or narrow the push`);
3645
3842
  }
3646
3843
  return problems;
3647
3844
  }
@@ -3675,11 +3872,55 @@ function reportPlanOnly(flags, plan, problems, live, extra) {
3675
3872
  `);
3676
3873
  process.stdout.write("plan only: nothing was changed\n");
3677
3874
  }
3875
+ var mapKeyLabel = (key) => `configuration-map key "${key}"`;
3876
+ async function pushConfigMapKeys(client, local, planned, named, changed, baseline, serverId, flags) {
3877
+ const current = await client.getServerConfiguration();
3878
+ const moved = configMapMoved(named, planned, current);
3879
+ if (moved.length > 0 && !flags.force) {
3880
+ fail(`changed on the server just before saving the configuration map: ${moved.map(mapKeyLabel).join(", ")}; nothing was saved. Pull and try again, or pass --force`);
3881
+ }
3882
+ try {
3883
+ await client.putConfigurationMap(mergeConfigMap(current, local, changed));
3884
+ } catch (err) {
3885
+ fail(`saving the configuration map failed; nothing else was pushed: ${err instanceof Error ? err.message : String(err)}`);
3886
+ }
3887
+ let after;
3888
+ try {
3889
+ after = await client.getServerConfiguration();
3890
+ } catch (err) {
3891
+ fail(`saved the configuration map, but could not read it back to check it: ${err instanceof Error ? err.message : String(err)}. Nothing else was pushed. ${exportBrokenHint(flags)}`);
3892
+ }
3893
+ const tree = new Map(configMapOf(local).map((e) => [configMapKeyOf(e), e]));
3894
+ const saved = new Map(configMapOf(after).map((e) => [configMapKeyOf(e), e]));
3895
+ const wrong = changed.filter((k) => !sameEntry(tree.get(k), saved.get(k)));
3896
+ if (wrong.length > 0) {
3897
+ fail(`saved the configuration map, but these keys do not read back as the tree has them: ${wrong.join(", ")}. Nothing else was pushed. Review the server; the undo command above restores the whole server as it was before this push`);
3898
+ }
3899
+ const others = otherDifferingKeys(current, after, changed);
3900
+ if (others.length > 0) {
3901
+ fail(`saved the named configuration-map keys, but other keys changed at the same time (probably a concurrent edit): ${others.join(", ")}. Nothing else was pushed. Review them on the server before pushing again`);
3902
+ }
3903
+ const next = baselineAfterPush(baseline, after, changed);
3904
+ if (next) await recordConfigMapBaseline(serverId, next);
3905
+ process.stdout.write(`saved ${changed.length} configuration-map key(s): ${changed.join(", ")}
3906
+ `);
3907
+ }
3678
3908
  async function scopedPush(client, root, local, scope, target, flags, live) {
3679
3909
  const remote = await client.getServerConfiguration();
3680
3910
  const known = await readKnown(root);
3681
3911
  const plan = planPush(local, remote, scope, known);
3682
- const problems = [...await bindingProblems(root, live.serverId), ...planProblems(plan, flags), ...await xmlProblems(root, local)];
3912
+ const mapKeys = flags.configMapKey ?? [];
3913
+ const mapBaseline = mapKeys.length > 0 ? await readConfigMapBaseline(live.serverId) : void 0;
3914
+ let mapPlan = { changes: [], conflicts: [], unchanged: [] };
3915
+ try {
3916
+ if (mapKeys.length > 0) mapPlan = planConfigMap(local, remote, mapKeys, mapBaseline);
3917
+ } catch (err) {
3918
+ if (err instanceof UnknownConfigMapKey) fail(err.message, "config-map-key-unknown");
3919
+ throw err;
3920
+ }
3921
+ const mapChanged = mapPlan.changes.map((c) => c.id);
3922
+ const shown = withConfigMap(plan, mapPlan);
3923
+ const problems = [...await bindingProblems(root, live.serverId), ...planProblems(shown, flags), ...await xmlProblems(root, local)];
3683
3924
  const names = new Map(
3684
3925
  [...channelsOf(remote), ...channelsOf(local)].map((c) => [String(c["id"]), String(c["name"])])
3685
3926
  );
@@ -3689,16 +3930,16 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
3689
3930
  const notDeployed = flags.deploy ? plan.deployIds.filter((id) => !deployed.has(id)) : [];
3690
3931
  if (flags.planOnly && flags.json) {
3691
3932
  const redeploy = flags.deploy ? { redeploy: toDeploy.map(nameOf2), notRedeployed: notDeployed.map(nameOf2) } : {};
3692
- reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped", ...redeploy });
3933
+ reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped", ...redeploy });
3693
3934
  return;
3694
3935
  }
3695
- if (plan.changes.length === 0) {
3936
+ if (shown.changes.length === 0) {
3696
3937
  process.stdout.write(`nothing to push: ${target} already matches the tree
3697
3938
  `);
3698
3939
  } else {
3699
3940
  process.stdout.write(`Push to ${target}:
3700
3941
  `);
3701
- printChanges(plan);
3942
+ printChanges(shown);
3702
3943
  if (toDeploy.length > 0) process.stdout.write(`then redeploy: ${toDeploy.map(nameOf2).join(", ")}
3703
3944
  `);
3704
3945
  if (notDeployed.length > 0) {
@@ -3707,7 +3948,15 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
3707
3948
  }
3708
3949
  }
3709
3950
  if (plan.notPushed.length > 0) {
3710
- process.stdout.write(`not pushed (differs; use --whole-server): ${plan.notPushed.join(", ")}
3951
+ const mapHint = plan.notPushed.includes("configurationMap") ? ", or --config-map-key for named configuration-map keys" : "";
3952
+ process.stdout.write(`not pushed (differs; use --whole-server${mapHint}): ${plan.notPushed.join(", ")}
3953
+ `);
3954
+ }
3955
+ if (mapPlan.unchanged.length > 0) process.stdout.write(`configuration-map keys already as in the tree: ${mapPlan.unchanged.join(", ")}
3956
+ `);
3957
+ if (mapKeys.length > 0) {
3958
+ const others = otherDifferingKeys(local, remote, mapKeys);
3959
+ if (others.length > 0) process.stdout.write(`other configuration-map keys differ (not pushed): ${others.join(", ")}
3711
3960
  `);
3712
3961
  }
3713
3962
  if (plan.serverOnly.length > 0) {
@@ -3715,29 +3964,30 @@ async function scopedPush(client, root, local, scope, target, flags, live) {
3715
3964
  `);
3716
3965
  }
3717
3966
  if (flags.planOnly) {
3718
- reportPlanOnly(flags, plan, problems, live, { target, mode: "scoped" });
3967
+ reportPlanOnly(flags, shown, problems, live, { target, mode: "scoped" });
3719
3968
  return;
3720
3969
  }
3721
3970
  if (problems.length > 0) fail(problems.join("\n"));
3722
- if (plan.changes.length === 0) return;
3971
+ if (shown.changes.length === 0) return;
3723
3972
  if (!flags.yes && !await confirm("Continue?")) {
3724
3973
  process.stdout.write("aborted.\n");
3725
3974
  return;
3726
3975
  }
3727
3976
  const fresh = await client.getServerConfiguration();
3728
- const moved = changedSince(plan, remote, fresh);
3977
+ const moved = [...configMapMoved(mapKeys, remote, fresh).map(mapKeyLabel), ...changedSince(plan, remote, fresh)];
3729
3978
  if (moved.length > 0 && !flags.force) {
3730
3979
  fail(`changed on the server while this push was being confirmed:
3731
3980
  ${moved.join("\n ")}
3732
3981
  pull and try again, or pass --force`);
3733
3982
  }
3734
- await backupBeforePush(client, live.conn, flags);
3983
+ await backupBeforePush(client, live.conn, { ...flags, overwriteConfigMap: mapChanged.length > 0 });
3735
3984
  const afterBackup = await client.getServerConfiguration();
3736
- const changedDuringBackup = changedSince(plan, fresh, afterBackup);
3985
+ const changedDuringBackup = [...configMapMoved(mapKeys, fresh, afterBackup).map(mapKeyLabel), ...changedSince(plan, fresh, afterBackup)];
3737
3986
  if (!flags.force && changedDuringBackup.length) {
3738
3987
  fail(`changed on the server during backup: ${changedDuringBackup.join(", ")}; pull and try again`);
3739
3988
  }
3740
3989
  await assertBinding(client, root);
3990
+ if (mapChanged.length > 0) await pushConfigMapKeys(client, local, afterBackup, mapKeys, mapChanged, mapBaseline, live.serverId, flags);
3741
3991
  const result = await applyPlan(client, plan, local, afterBackup, scope, { force: flags.force === true });
3742
3992
  let baselineError;
3743
3993
  let changedAgain = [];
@@ -3771,13 +4021,13 @@ changed again after saving (pull and review before retrying): ${changedAgain.joi
3771
4021
  if (baselineError) process.stderr.write(`warning: could not refresh the local sync baseline: ${scrub(baselineError)}
3772
4022
  `);
3773
4023
  const { change, error } = result.failed;
3774
- fail(`applied ${result.applied.length} of ${plan.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
4024
+ fail(`applied ${result.applied.length + mapChanged.length} of ${shown.changes.length}; ${change.op} ${change.label} failed: ${error}${againNote}${notRedeployed}`);
3775
4025
  }
3776
4026
  if (changedAgain.length > 0) {
3777
- fail(`applied ${result.applied.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
4027
+ fail(`applied ${result.applied.length + mapChanged.length} change(s), but these changed again after saving: ${changedAgain.join(", ")}; pull and review before retrying${notRedeployed}${baselineError ? `
3778
4028
  ${baselineError}` : ""}`);
3779
4029
  }
3780
- process.stdout.write(`pushed ${result.applied.length} change(s)
4030
+ process.stdout.write(`pushed ${result.applied.length + mapChanged.length} change(s)
3781
4031
  `);
3782
4032
  if (toDeploy.length > 0) {
3783
4033
  const { deployed: deployed2, skipped, failures } = await deployChannels(client, toDeploy, nameOf2);
@@ -3792,7 +4042,7 @@ ${baselineError}` : ""}`);
3792
4042
  if (baselineError) {
3793
4043
  const note = unverified.length > 0 ? `
3794
4044
  not checked after saving (these cannot be read one at a time): ${unverified.join(", ")}` : "";
3795
- fail(`pushed ${result.applied.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
4045
+ fail(`pushed ${result.applied.length + mapChanged.length} change(s), but could not refresh the local sync baseline: ${baselineError}${note}`);
3796
4046
  }
3797
4047
  printCommitHint(root);
3798
4048
  }
@@ -3902,6 +4152,7 @@ async function wholeServerPush(client, root, local, target, flags, live) {
3902
4152
  const ids = resourceIds(local);
3903
4153
  await refreshRevisions(root, after, /* @__PURE__ */ new Set([...Object.keys(ids.channels), ...Object.keys(ids.libraries), ...Object.keys(ids.codeTemplates)]));
3904
4154
  if (known) await writeKnown(root, resourceIds(after));
4155
+ if (flags.overwriteConfigMap) await recordConfigMapBaseline(live.serverId, configMapBaseline(after));
3905
4156
  process.stdout.write(`pushed ${root} -> ${target}
3906
4157
  `);
3907
4158
  printCommitHint(root);
@@ -3912,8 +4163,8 @@ addExtractFlag(addEnvFlag(
3912
4163
  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")
3913
4164
  )).action(async (backupPath, dir, flags) => {
3914
4165
  const config = xml.parse(await readFile6(backupPath, "utf8"));
3915
- const root = path9.resolve(dir);
3916
- await writeTree(root, config, `file:${path9.resolve(backupPath)}`, flags, await envFileFor(root, flags));
4166
+ const root = path10.resolve(dir);
4167
+ await writeTree(root, config, `file:${path10.resolve(backupPath)}`, flags, await envFileFor(root, flags));
3917
4168
  const s = summarize(config);
3918
4169
  process.stdout.write(`exploded ${s.channels} channels, ${s.codeTemplates} code templates -> ${root}
3919
4170
  `);
@@ -3921,22 +4172,22 @@ addExtractFlag(addEnvFlag(
3921
4172
  addEnvFlag(
3922
4173
  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)
3923
4174
  ).action(async (dir, outPath, flags) => {
3924
- const root = path9.resolve(dir);
4175
+ const root = path10.resolve(dir);
3925
4176
  assertTree(root);
3926
4177
  const config = await renderedTree(root, await envFileFor(root, flags));
3927
4178
  await assertCompatibleOrigin(root, config, "xml", flags.force === true);
3928
4179
  const xmlStr = xml.build(config);
3929
4180
  await writeFile6(outPath, xmlStr, "utf8");
3930
- process.stdout.write(`imploded ${root} -> ${path9.resolve(outPath)}
4181
+ process.stdout.write(`imploded ${root} -> ${path10.resolve(outPath)}
3931
4182
  `);
3932
4183
  });
3933
4184
  addExtractFlag(addEnvFlag(addConnectionFlags(
3934
4185
  program.command("pull").description("Pull the live server configuration into a working tree").argument("<dir>", "working-tree directory")
3935
4186
  ))).action(async (dir, flags) => {
3936
- const root = path9.resolve(dir);
4187
+ const root = path10.resolve(dir);
3937
4188
  const conn = await selectConnection(root, flags);
3938
4189
  const envFile = await envFileFor(root, flags, conn);
3939
- if (!isWithin(path9.resolve(envFile), root)) await lockAlso(envFile);
4190
+ if (!isWithin(path10.resolve(envFile), root)) await lockAlso(envFile);
3940
4191
  const previous = await preflightTree(root, envFile);
3941
4192
  const { config, serverId } = await withClient(conn, async (client, serverId2) => {
3942
4193
  if (previous?.serverId && previous.serverId !== serverId2) {
@@ -3954,7 +4205,7 @@ addExtractFlag(addEnvFlag(addConnectionFlags(
3954
4205
  addJsonFlag(addEnvFlag(addConnectionFlags(
3955
4206
  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)
3956
4207
  ))).action(async (dir, flags) => {
3957
- const root = path9.resolve(dir);
4208
+ const root = path10.resolve(dir);
3958
4209
  assertTree(root);
3959
4210
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
3960
4211
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) fail("no terminal to confirm on; review with `adopt --plan-only` and pass --yes");
@@ -3996,19 +4247,20 @@ Local content is preserved; the following differences become reviewed edits for
3996
4247
  await engine.explode(rebased.config, { root: next });
3997
4248
  await writeMeta(next, target, rebased.config, previous, serverId, adopted.known);
3998
4249
  });
4250
+ await recordConfigMapBaseline(serverId, configMapBaseline(remote));
3999
4251
  process.stdout.write(`adopted installation ${serverId}; review with push --plan-only before writing the server
4000
4252
  `);
4001
4253
  }, { envFile, quiet: flags.json });
4002
4254
  });
4003
4255
  addBackupDirFlags(addEnvFlag(addConnectionFlags(
4004
- program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
4256
+ program.command("push").description("Push changed channels, code templates and global scripts to the live server").argument("<dir>", "working-tree directory").option("--channel <name>", "only this channel (name or id); repeatable", collect).option("--library <name>", "only this code template library (name or id); repeatable", collect).option("--global-scripts", "with --channel/--library: also push global scripts").option("--config-map-key <name>", "push this configuration-map key (alone: only the named keys); repeatable", collect).option("--allow-deletes", "delete server resources that are missing from the tree", false).option("--deploy", "redeploy the changed channels and the channels using changed code templates", false).option("--force", "push even if the server changed since the last pull (overwrites the server's version)", false).option("--ignore-origin", "push a tree that was exploded from an XML backup (normally refused)", false).option("--whole-server", "replace the entire server configuration instead (settings, config map, groups too)", false).option("--overwrite-config-map", "with --whole-server: also overwrite the configuration map", false).option("--no-backup", "skip the backup of the server taken before anything changes").option("--plan-only", "show what would be pushed and what would stop it; change nothing (no prompt)", false).option("--json", "with --plan-only: print the plan as one JSON document", false).option("-y, --yes", "skip the confirmation prompt", false)
4005
4257
  ))).action(
4006
4258
  async (dir, flags) => {
4007
- if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts)) {
4008
- fail("--whole-server replaces everything; it cannot be combined with --channel, --library or --global-scripts");
4259
+ if (flags.wholeServer && (flags.channel || flags.library || flags.globalScripts || flags.configMapKey)) {
4260
+ fail("--whole-server replaces everything; it cannot be combined with --channel, --library, --global-scripts or --config-map-key");
4009
4261
  }
4010
4262
  if (flags.overwriteConfigMap && !flags.wholeServer) fail("--overwrite-config-map needs --whole-server");
4011
- const root = path9.resolve(dir);
4263
+ const root = path10.resolve(dir);
4012
4264
  assertTree(root);
4013
4265
  if (flags.json && !flags.planOnly) fail("--json needs --plan-only");
4014
4266
  if (!flags.yes && !flags.planOnly && !process.stdin.isTTY) {
@@ -4024,7 +4276,8 @@ addBackupDirFlags(addEnvFlag(addConnectionFlags(
4024
4276
  await withClient(conn, (client, serverId) => wholeServerPush(client, root, config, target, flags, { conn, serverId, envFile }), { envFile, quiet });
4025
4277
  return;
4026
4278
  }
4027
- const scope = { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
4279
+ const keysOnly = flags.configMapKey !== void 0 && !flags.channel && !flags.library && !flags.globalScripts;
4280
+ const scope = keysOnly ? { channels: [], libraries: [] } : { channels: flags.channel, libraries: flags.library, globalScripts: flags.globalScripts };
4028
4281
  await withClient(conn, (client, serverId) => scopedPush(client, root, config, scope, target, flags, { conn, serverId, envFile }), { envFile, quiet });
4029
4282
  }
4030
4283
  );
@@ -4036,10 +4289,10 @@ addBackupDirFlags(addConnectionFlags(
4036
4289
  const file = await withClient(conn, async (client) => {
4037
4290
  const text = await client.getServerConfigurationXml();
4038
4291
  if (!flags.out) return saveServerBackup(client, text, conn, flags);
4039
- const out = path9.resolve(flags.out);
4292
+ const out = path10.resolve(flags.out);
4040
4293
  parseBackup(text, "the server configuration");
4041
- if (existsSync8(out)) fail(`${out} already exists; choose another name`);
4042
- await mkdir6(path9.dirname(out), { recursive: true });
4294
+ if (existsSync9(out)) fail(`${out} already exists; choose another name`);
4295
+ await mkdir7(path10.dirname(out), { recursive: true });
4043
4296
  await writePrivate(out, text);
4044
4297
  if (gitWouldCommit(out)) {
4045
4298
  process.stderr.write(`warning: git does not ignore ${out}, which holds credentials in plain text; add it to .gitignore
@@ -4052,14 +4305,14 @@ addBackupDirFlags(addConnectionFlags(
4052
4305
  });
4053
4306
  async function chooseBackup(dir, file, serverId, target) {
4054
4307
  if (file) {
4055
- const chosen = path9.resolve(file);
4056
- if (!existsSync8(chosen)) fail(`${chosen} does not exist`);
4308
+ const chosen = path10.resolve(file);
4309
+ if (!existsSync9(chosen)) fail(`${chosen} does not exist`);
4057
4310
  return chosen;
4058
4311
  }
4059
4312
  const mine = await backupsOf(dir, serverId);
4060
4313
  if (mine.length === 0) {
4061
4314
  const others = (await originsIn(dir)).map((o) => o.host);
4062
- const legacy = path9.resolve(LEGACY_BACKUP_DIR);
4315
+ const legacy = path10.resolve(LEGACY_BACKUP_DIR);
4063
4316
  const inLegacy = legacy !== dir && (await backupsOf(legacy, serverId)).length > 0;
4064
4317
  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)}` : ""));
4065
4318
  }
@@ -4083,7 +4336,7 @@ async function restoreWithBrokenExport(client, serverId, file, flags, target) {
4083
4336
  if (unsafe) fail(`${chosen} holds ${unsafe}`);
4084
4337
  const origin = await originOf(dir, chosen);
4085
4338
  if (!origin && !flags.force) {
4086
- fail(`${chosen} is not in ${path9.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
4339
+ fail(`${chosen} is not in ${path10.join(dir, MANIFEST)}, and without the server's export its name cannot be compared either; pass --force to restore it anyway`);
4087
4340
  }
4088
4341
  if (origin && origin.serverId !== serverId && !flags.force) {
4089
4342
  fail(`${chosen} was taken from ${origin.host} (server ID ${origin.serverId}), not this server (${serverId}); pass --force to restore it here anyway`);
@@ -4146,7 +4399,7 @@ addBackupDirFlags(addConnectionFlags(
4146
4399
  if (fromContent !== "" && fromServer !== "" && fromContent !== fromServer && !flags.force) {
4147
4400
  fail(`${chosen} is a backup of ${fromContent}, not ${fromServer}; pass --force to restore it here anyway`);
4148
4401
  }
4149
- process.stderr.write(`warning: ${chosen} is not in ${path9.join(dir, MANIFEST)}, so which server it came from cannot be checked
4402
+ process.stderr.write(`warning: ${chosen} is not in ${path10.join(dir, MANIFEST)}, so which server it came from cannot be checked
4150
4403
  `);
4151
4404
  }
4152
4405
  const [bv, sv] = [backup["@_version"], current["@_version"]];
@@ -4205,7 +4458,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
4205
4458
  })
4206
4459
  ))).action(async (dir, flags) => {
4207
4460
  errorExitCode = 2;
4208
- const root = path9.resolve(dir);
4461
+ const root = path10.resolve(dir);
4209
4462
  assertTree(root);
4210
4463
  const conn = await selectConnection(root, flags);
4211
4464
  const envFile = await envFileFor(root, flags, conn);
@@ -4217,10 +4470,13 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
4217
4470
  return { fetched: await client.getServerConfiguration(), serverId: serverId2 };
4218
4471
  }, { envFile, quiet: flags.json });
4219
4472
  const tree = await engine.implode({ root });
4220
- const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, await loadEnv(envFile));
4473
+ const env = await loadEnv(envFile);
4474
+ const unsetTreeOnly = assertEnvComplete(tree, fetched, env, envFile, conn);
4475
+ const { config: templatedRemote, envUpdates, notes } = templatize(fetched, tree, env);
4221
4476
  const messages = [
4222
4477
  ...Object.keys(envUpdates).map((name) => `${name} differs between the server and the env file`),
4223
4478
  ...notes,
4479
+ ...unsetTreeOnly.length > 0 ? [`no value yet for ${unsetTreeOnly.join(", ")}, used only by resources the server doesn't have`] : [],
4224
4480
  ...await xmlProblems(root, tree)
4225
4481
  ];
4226
4482
  const allow = await readAllow(root);
@@ -4228,23 +4484,23 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
4228
4484
  if (staleRevisions.length > 0) {
4229
4485
  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`);
4230
4486
  }
4231
- const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(tree))), { mode: "redact", allow });
4232
- const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withoutVolatile(templatedRemote))), { mode: "redact", allow });
4487
+ const treeView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(tree)))), { mode: "redact", allow });
4488
+ const serverView = scanSecrets(redactKnownSecrets(normalizeEolDeep(withSortedConfigMap(withoutVolatile(templatedRemote)))), { mode: "redact", allow });
4233
4489
  if (treeView.findings.length > 0) {
4234
4490
  messages.push(`the tree holds ${treeView.findings.length} unextracted secret(s), redacted below; pull --extract-secrets`);
4235
4491
  }
4236
4492
  if (serverView.findings.length > 0) messages.push(`${serverView.findings.length} possible secret(s) on the server are redacted below`);
4237
4493
  if (!flags.json) for (const m of messages) process.stderr.write(`note: ${m}
4238
4494
  `);
4239
- const tmp = await mkdtemp(path9.join(tmpdir(), "channelvault-diff-"));
4495
+ const tmp = await mkdtemp(path10.join(tmpdir(), "channelvault-diff-"));
4240
4496
  try {
4241
- await engine.explode(treeView.config, { root: path9.join(tmp, "tree") });
4242
- await engine.explode(serverView.config, { root: path9.join(tmp, "server") });
4243
- await mkdir6(path9.join(tmp, ".empty"));
4497
+ await engine.explode(treeView.config, { root: path10.join(tmp, "tree") });
4498
+ await engine.explode(serverView.config, { root: path10.join(tmp, "server") });
4499
+ await mkdir7(path10.join(tmp, ".empty"));
4244
4500
  const chunks = [];
4245
4501
  for (const d of MANAGED_DIRS) {
4246
- const local = existsSync8(path9.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
4247
- const server = existsSync8(path9.join(tmp, "server", d)) ? `server/${d}` : ".empty";
4502
+ const local = existsSync9(path10.join(tmp, "tree", d)) ? `tree/${d}` : ".empty";
4503
+ const server = existsSync9(path10.join(tmp, "server", d)) ? `server/${d}` : ".empty";
4248
4504
  if (local === ".empty" && server === ".empty") continue;
4249
4505
  const result = spawnSync2(
4250
4506
  "git",
@@ -4266,7 +4522,7 @@ addJsonFlag(addEnvFlag(addConnectionFlags(
4266
4522
  const clean = out === "" && secretDrift.length === 0;
4267
4523
  if (!clean) process.exitCode = 1;
4268
4524
  if (flags.json) {
4269
- const files = await changedFiles(path9.join(tmp, "tree"), path9.join(tmp, "server"));
4525
+ const files = await changedFiles(path10.join(tmp, "tree"), path10.join(tmp, "server"));
4270
4526
  writeJson2({ clean, serverId, connection: connectionJson(conn, serverId, envFile), files, secretDrift, staleRevisions, notes: messages, patch: out });
4271
4527
  } else if (clean) {
4272
4528
  process.stdout.write("no differences \u2014 working tree matches the server.\n");
@@ -4287,7 +4543,7 @@ async function changedFiles(treeDir, serverDir) {
4287
4543
  const files = [];
4288
4544
  for (const p of local) {
4289
4545
  if (!remoteSet.has(p)) files.push({ path: p, change: "only-in-tree" });
4290
- else if (await readFile6(path9.join(treeDir, p), "utf8") !== await readFile6(path9.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
4546
+ else if (await readFile6(path10.join(treeDir, p), "utf8") !== await readFile6(path10.join(serverDir, p), "utf8")) files.push({ path: p, change: "modified" });
4291
4547
  }
4292
4548
  const localSet = new Set(local);
4293
4549
  for (const p of remote) if (!localSet.has(p)) files.push({ path: p, change: "only-on-server" });
@@ -4296,7 +4552,7 @@ async function changedFiles(treeDir, serverDir) {
4296
4552
  addJsonFlag(addEnvFlag(
4297
4553
  program.command("status").description("Summarize a working tree, and say which connection profile live commands would use").argument("<dir>", "working-tree directory")
4298
4554
  )).action(async (dir, flags) => {
4299
- const root = path9.resolve(dir);
4555
+ const root = path10.resolve(dir);
4300
4556
  assertTree(root);
4301
4557
  const config = await engine.implode({ root });
4302
4558
  const s = summarize(config);
@@ -4389,7 +4645,7 @@ function existingProfile(profiles, name) {
4389
4645
  if (!profile) fail(`no profile named ${name} (${Object.keys(profiles).join(", ") || "none saved"})`, "profile-unknown");
4390
4646
  return profile;
4391
4647
  }
4392
- var profileCommand = program.command("profile").description(`Manage connection profiles (${path9.join("~", ".channelvault", "profiles.json")}; passwords in its credentials file)`);
4648
+ var profileCommand = program.command("profile").description(`Manage connection profiles (${path10.join("~", ".channelvault", "profiles.json")}; passwords in its credentials file)`);
4393
4649
  addJsonFlag(profileCommand.command("list").description("List the saved profiles (never their passwords)")).action(async (flags) => {
4394
4650
  const profiles = await loadProfiles();
4395
4651
  const credentials = await readCredentials();
@@ -4427,7 +4683,7 @@ profileCommand.command("add").description("Add a profile at a terminal: confirm
4427
4683
  const profile = { host: flags.host, port, user: flags.user };
4428
4684
  if (flags.https === false) profile.https = false;
4429
4685
  if (flags.insecure) profile.insecure = true;
4430
- if (flags.dotenv) profile.dotenv = path9.resolve(flags.dotenv);
4686
+ if (flags.dotenv) profile.dotenv = path10.resolve(flags.dotenv);
4431
4687
  if (flags.tlsFingerprint !== void 0) {
4432
4688
  const pin = normalizeFingerprint(flags.tlsFingerprint);
4433
4689
  if (!pin) fail("--tls-fingerprint must be a SHA-256 certificate fingerprint: 64 hex digits, colons allowed", "bad-fingerprint");
@@ -4534,14 +4790,14 @@ var locked = [];
4534
4790
  async function lockAlso(file) {
4535
4791
  const key = await canonical(file);
4536
4792
  if (locked.some((l) => samePath(l, key))) return;
4537
- unlocks.push(await lockTree(path9.resolve(file)));
4793
+ unlocks.push(await lockTree(path10.resolve(file)));
4538
4794
  locked.push(key);
4539
4795
  }
4540
4796
  program.hook("preAction", async (_program, command) => {
4541
4797
  const name = command.name();
4542
4798
  if (!["explode", "pull", "adopt", "push", "implode", "diff", "status"].includes(name) || command.parent !== program) return;
4543
4799
  if (name === "diff") errorExitCode = 2;
4544
- const root = path9.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
4800
+ const root = path10.resolve(String(command.processedArgs[name === "explode" ? 1 : 0]));
4545
4801
  unlocks.push(await lockTree(root));
4546
4802
  const pending = await pendingEnvFile(root);
4547
4803
  if (pending === null) return;