@nice-code/commander 0.103.0 → 0.105.0

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/build/cli.mjs CHANGED
@@ -152,7 +152,7 @@ function validStartStamp(value) {
152
152
  function isInstanceRecord(value) {
153
153
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
154
154
  const record = value;
155
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 7;
155
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 7;
156
156
  }
157
157
  async function writeInstanceRecord(path, record) {
158
158
  await mkdir(dirname(path), {
@@ -211,7 +211,8 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
211
211
  protocolVersion: record["protocolVersion"],
212
212
  packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown",
213
213
  startStamp: validStartStamp(record["startStamp"]) ? record["startStamp"] ?? null : null,
214
- skew: sameProtocol ? "realm-schema" : "protocol"
214
+ skew: sameProtocol ? "realm-schema" : "protocol",
215
+ servesOwnClient: record["servesOwnClient"] === true
215
216
  };
216
217
  }
217
218
  /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
@@ -22167,6 +22168,20 @@ var RealmRuleTrie = class {
22167
22168
  params
22168
22169
  };
22169
22170
  }
22171
+ /**
22172
+ * Whether some rule's pattern can match a path strictly BENEATH `path` (a `**` at or above it
22173
+ * counts). Ignores `view` conditions — the answer is about schema reachability, not access.
22174
+ */
22175
+ reachesBeneath(path) {
22176
+ return this._reachesBeneath(this._root, path, 0);
22177
+ }
22178
+ _reachesBeneath(node, path, depth) {
22179
+ if (node.deep != null) return true;
22180
+ if (depth === path.length) return (node.lit?.size ?? 0) > 0 || node.var != null || node.star != null;
22181
+ const litChild = node.lit?.get(path[depth]);
22182
+ if (litChild != null && this._reachesBeneath(litChild, path, depth + 1)) return true;
22183
+ return node.var != null && this._reachesBeneath(node.var.node, path, depth + 1);
22184
+ }
22170
22185
  _match(node, path, depth) {
22171
22186
  if (depth === path.length) return node.exact;
22172
22187
  const seg = path[depth];
@@ -22726,14 +22741,22 @@ const OMIT = {
22726
22741
  value: void 0,
22727
22742
  anyVisible: false
22728
22743
  };
22729
- function pruneNode(ctx, node, value, path) {
22744
+ /** Does `path` pass through a record entry? Its containers are then data, not structure. */
22745
+ function underRecordEntry(schemaRoot, path) {
22746
+ for (let depth = 1; depth < path.length; depth++) {
22747
+ const parent = schemaNodeAtPath(schemaRoot, path.slice(0, depth));
22748
+ if (parent != null && unwrapOptional(parent).kind === "record") return true;
22749
+ }
22750
+ return false;
22751
+ }
22752
+ function pruneNode(ctx, node, value, path, inEntry = underRecordEntry(ctx.schemaRoot, path)) {
22730
22753
  if (value === void 0) return OMIT;
22731
22754
  const inner = unwrapOptional(node);
22732
22755
  if (inner.kind === "object") {
22733
22756
  const out = {};
22734
22757
  let anyVisible = false;
22735
22758
  for (const [key, child] of Object.entries(inner.entries)) {
22736
- const pruned = pruneNode(ctx, child, value[key], [...path, key]);
22759
+ const pruned = pruneNode(ctx, child, value[key], [...path, key], inEntry);
22737
22760
  if (pruned.anyVisible) {
22738
22761
  out[key] = pruned.value;
22739
22762
  anyVisible = true;
@@ -22748,15 +22771,16 @@ function pruneNode(ctx, node, value, path) {
22748
22771
  const out = {};
22749
22772
  let anyVisible = false;
22750
22773
  if (value != null && typeof value === "object") for (const [key, entry] of Object.entries(value)) {
22751
- const pruned = pruneNode(ctx, inner.value, entry, [...path, key]);
22774
+ const pruned = pruneNode(ctx, inner.value, entry, [...path, key], true);
22752
22775
  if (pruned.anyVisible) {
22753
22776
  out[key] = pruned.value;
22754
22777
  anyVisible = true;
22755
22778
  }
22756
22779
  }
22780
+ const structural = !inEntry && ctx.trie.reachesBeneath(path);
22757
22781
  return {
22758
22782
  value: out,
22759
- anyVisible: anyVisible || leafVisible(ctx, path)
22783
+ anyVisible: anyVisible || structural || leafVisible(ctx, path)
22760
22784
  };
22761
22785
  }
22762
22786
  return leafVisible(ctx, path) ? {
@@ -24471,6 +24495,11 @@ const COMMANDER_TICKET_PATH = "/ticket";
24471
24495
  /** CLI liveness/discovery probe (instance-record root token only). */
24472
24496
  const COMMANDER_HEALTH_PATH = "/health";
24473
24497
  /**
24498
+ * Plain-HTTP shutdown, capability-gated. It needs no realm, so a page from another build — one
24499
+ * that can never attach the status realm — can still stop the daemon it is stuck on.
24500
+ */
24501
+ const COMMANDER_SHUTDOWN_PATH = "/shutdown";
24502
+ /**
24474
24503
  * ws tickets ride the subprotocol negotiation (browsers cannot set arbitrary ws headers):
24475
24504
  * the client offers `commander-auth.<ticket>`, the daemon selects it to complete the upgrade.
24476
24505
  */
@@ -24815,7 +24844,10 @@ async function findSkewedDaemon(config) {
24815
24844
  return {
24816
24845
  message: `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ${skewed.packageVersion}) ${difference} — this CLI (build ${await commanderPackageVersion()}) cannot talk to it. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`,
24817
24846
  pid: skewed.pid,
24818
- startStamp: skewed.startStamp
24847
+ port: skewed.port,
24848
+ packageVersion: skewed.packageVersion,
24849
+ startStamp: skewed.startStamp,
24850
+ servesOwnClient: skewed.servesOwnClient
24819
24851
  };
24820
24852
  }
24821
24853
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
@@ -27040,6 +27072,7 @@ async function candidates() {
27040
27072
  }
27041
27073
  /** Try each opener in turn; resolves true when one spawns without an immediate failure. */
27042
27074
  async function openBrowser(url) {
27075
+ if (process.env["NICE_COMMANDER_NO_BROWSER"] === "1") return false;
27043
27076
  for (const candidate of await candidates()) if (await new Promise((resolve) => {
27044
27077
  try {
27045
27078
  const child = spawn(candidate.command, candidate.args(url), {
@@ -27058,20 +27091,88 @@ async function openBrowser(url) {
27058
27091
  }
27059
27092
  //#endregion
27060
27093
  //#region src/cli/commands/ui.ts
27094
+ /** How long a wire-requested shutdown gets to finish its ladder before a signal follows it. */
27095
+ const FRESH_EXIT_WAIT_MS = 3e4;
27061
27096
  async function cmdUi(ctx) {
27062
- const bad = unknownFlags(ctx.args.flags, []);
27097
+ const bad = unknownFlags(ctx.args.flags, ["--fresh"]);
27063
27098
  if (bad != null) throw new CliExit(EXIT.usage, bad);
27099
+ const { out } = ctx;
27100
+ if (ctx.args.flags.get("--fresh") === true) await stopExistingDaemon(ctx);
27101
+ else {
27102
+ const skewed = await findSkewedDaemon(ctx.config);
27103
+ if (skewed?.servesOwnClient === true) {
27104
+ const url = `http://127.0.0.1:${skewed.port}`;
27105
+ const opened = await openBrowser(url);
27106
+ if (out.json) out.printJson({
27107
+ url,
27108
+ opened,
27109
+ attached: true,
27110
+ daemonBuild: skewed.packageVersion
27111
+ });
27112
+ else {
27113
+ out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27114
+ out.print(out.paint("gray", `attached to the running daemon (build ${skewed.packageVersion}; this CLI is ${await commanderPackageVersion()}). \`nice-commander ui --fresh\` restarts it on this build — that stops everything it runs.`));
27115
+ }
27116
+ return EXIT.ok;
27117
+ }
27118
+ }
27064
27119
  const handle = await ensureDaemonRunning(ctx.config);
27065
27120
  ctx.spawnedDaemon = handle.spawned;
27066
27121
  const url = `http://127.0.0.1:${handle.record.port}`;
27067
27122
  const opened = await openBrowser(url);
27068
- if (ctx.out.json) ctx.out.printJson({
27123
+ if (out.json) out.printJson({
27069
27124
  url,
27070
- opened
27125
+ opened,
27126
+ attached: !handle.spawned
27071
27127
  });
27072
- else ctx.out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27128
+ else {
27129
+ if (handle.replaced != null) out.print(out.paint("gray", `replaced an idle daemon from build ${handle.replaced.packageVersion} (pid ${handle.replaced.pid})`));
27130
+ out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27131
+ }
27073
27132
  return EXIT.ok;
27074
27133
  }
27134
+ /**
27135
+ * `--fresh`: stop this config's daemon, whatever build it is, and wait until it has exited — the
27136
+ * boot that follows must not find (and reuse) a daemon that is still walking its ladder.
27137
+ * The wire goes first when it speaks our build: a signal is the fallback, because on Windows it
27138
+ * is a hard kill that skips the ladder.
27139
+ */
27140
+ async function stopExistingDaemon(ctx) {
27141
+ const { config, out } = ctx;
27142
+ const live = await findDaemon(config);
27143
+ const skewed = live == null ? await findSkewedDaemon(config) : null;
27144
+ const target = live != null ? {
27145
+ pid: live.record.pid,
27146
+ startStamp: live.record.startStamp
27147
+ } : skewed != null ? {
27148
+ pid: skewed.pid,
27149
+ startStamp: skewed.startStamp
27150
+ } : null;
27151
+ if (target == null) return;
27152
+ if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27153
+ if (live != null) try {
27154
+ const client = await connectDaemon(live);
27155
+ try {
27156
+ await client.shutdown();
27157
+ } finally {
27158
+ client.dispose();
27159
+ }
27160
+ if (await waitForExit(target.pid, FRESH_EXIT_WAIT_MS)) return;
27161
+ } catch (error) {
27162
+ if (!(error instanceof CliExit)) throw error;
27163
+ }
27164
+ const result = await signalDaemonShutdown(target);
27165
+ if (result.outcome === "exited" || result.outcome === "not-running") return;
27166
+ throw new CliExit(EXIT.failure, result.outcome === "still-stopping" ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment` : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly pid reuse), so nothing was stopped — verify it yourself, then retry`);
27167
+ }
27168
+ async function waitForExit(pid, timeoutMs) {
27169
+ const deadline = Date.now() + timeoutMs;
27170
+ while (Date.now() < deadline) {
27171
+ if (!pidAlive$1(pid)) return true;
27172
+ await new Promise((resolve) => setTimeout(resolve, 150));
27173
+ }
27174
+ return !pidAlive$1(pid);
27175
+ }
27075
27176
  //#endregion
27076
27177
  //#region src/daemon/savedFilters.ts
27077
27178
  const STORE_VERSION = 1;
@@ -27194,7 +27295,10 @@ const COMMAND_HELP = [
27194
27295
  non-zero. Children inherit THIS shell's environment;
27195
27296
  daemon-owned processes (up) inherit the daemon's
27196
27297
  boot-time snapshot instead — see doctor.`],
27197
- ["ui", " ui ensure the daemon and open the browser (prints URL)"],
27298
+ ["ui", ` ui [--fresh] open the browser at this config's daemon (prints URL),
27299
+ starting one if none runs. A running daemon is attached
27300
+ to, even from an older build. --fresh stops it (and
27301
+ everything it runs) and starts one on this build.`],
27198
27302
  ["doctor", ` doctor [--reap] [--reap-strays [--yes] [--force]]
27199
27303
  diagnostics: ledger, capability, endpoints (each port
27200
27304
  owner marked STRAY or not), env.
@@ -27274,7 +27378,7 @@ async function withTimeout(ctx, run) {
27274
27378
  async function main() {
27275
27379
  const argv = process.argv.slice(2);
27276
27380
  if (argv[0] === "daemon") {
27277
- const { runCommanderDaemon } = await import("./main-KhpDJbPT.mjs");
27381
+ const { runCommanderDaemon } = await import("./main-C5HqmZgp.mjs");
27278
27382
  return runCommanderDaemon(argv.slice(1));
27279
27383
  }
27280
27384
  const parsed = parseCliArgs(argv);
@@ -27319,6 +27423,6 @@ main().then((code) => {
27319
27423
  process.exitCode = EXIT.failure;
27320
27424
  });
27321
27425
  //#endregion
27322
- export { serveChannel as A, loadCommanderConfigFile as B, commanderPackageVersion as C, createRealmAcceptor as D, resolveCommanderDataDir as E, validateCommanderConfig as F, readInstanceRecord as G, stopSetWithDependencies as H, effectiveEnv as I, writeInstanceRecord as J, recordDaemonAlive as K, envVarViews as L, RuntimeCoordinate as M, createMemoryStorageAdapter_json as N, createRealmServerEngine as O, wsAcceptorCarrier as P, overrideFingerprint as R, commanderRuntimeError as S, ensureStateDir as T, withDependencies as U, orderByDependency as V, savedFilterId as W, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_WS_PATH as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, createDefaultServeLogger as j, httpAcceptorCarrier as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, removeInstanceRecord as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_TICKET_PATH as v, commanderStatePaths as w, commanderStatusRealm as x, COMMANDER_TICKET_PROTOCOL_PREFIX as y, hashCanonical as z };
27426
+ export { httpAcceptorCarrier as A, hashCanonical as B, commanderRuntimeError as C, resolveCommanderDataDir as D, ensureStateDir as E, wsAcceptorCarrier as F, savedFilterId as G, orderByDependency as H, validateCommanderConfig as I, removeInstanceRecord as J, readInstanceRecord as K, effectiveEnv as L, createDefaultServeLogger as M, RuntimeCoordinate as N, createRealmAcceptor as O, createMemoryStorageAdapter_json as P, envVarViews as R, commanderStatusRealm as S, commanderStatePaths as T, stopSetWithDependencies as U, loadCommanderConfigFile as V, withDependencies as W, writeInstanceRecord as Y, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_TICKET_PROTOCOL_PREFIX as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, serveChannel as j, createRealmServerEngine as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, recordDaemonAlive as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_SHUTDOWN_PATH as v, commanderPackageVersion as w, COMMANDER_WS_PATH as x, COMMANDER_TICKET_PATH as y, overrideFingerprint as z };
27323
27427
 
27324
27428
  //# sourceMappingURL=cli.mjs.map