@muhkoo/cli 0.14.0-alpha.7 → 0.14.0-alpha.9

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.
@@ -42,13 +42,116 @@ export function planPath({ last, local, remote }) {
42
42
  return "conflict"; // both moved
43
43
  }
44
44
 
45
- /** Plan every path across the three views. Returns a list of {path, action}. */
46
- export function planSync({ last, local, remote }) {
45
+ /**
46
+ * Plan every path across the three views. Returns a list of {path, action}.
47
+ *
48
+ * `unknown` lists paths — or directories, covering everything beneath them —
49
+ * that one side deliberately did not look at: refused, over the size limit,
50
+ * unreadable. Such a path is not ABSENT, and the difference is the whole game:
51
+ * "not in this view" plus "in the last-synced state" is how a deletion is
52
+ * recognised, so a filter read as an absence plans a delete. That is how the
53
+ * local `.git` was deleted when only one side refused it, how a 100MB asset
54
+ * lost its history to a size limit only one side applied, and how one failed
55
+ * read would have cost the local copy. Nothing is planned for an unknown path,
56
+ * so its state entry stays exactly as it was.
57
+ */
58
+ export function planSync({ last, local, remote, unknown = [] }) {
59
+ const isUnknown = coveredBy(unknown);
47
60
  const paths = new Set([...Object.keys(last), ...Object.keys(local), ...Object.keys(remote)]);
48
61
  const plan = [];
49
62
  for (const path of [...paths].sort()) {
63
+ if (isUnknown(path)) continue;
50
64
  const action = planPath({ last: last[path], local: local[path], remote: remote[path] });
51
65
  if (action !== "none") plan.push({ path, action });
52
66
  }
53
67
  return plan;
54
68
  }
69
+
70
+ /**
71
+ * `(path) => boolean`: is `path`, or a directory above it, in `prefixes`?
72
+ *
73
+ * Walked one segment at a time down a tree of them. Slicing and hashing each
74
+ * prefix afresh cost a path its length times its depth — a thousand remote
75
+ * paths 61 deep of 240-character names held the event loop for half a second.
76
+ */
77
+ function coveredBy(prefixes) {
78
+ const END = Symbol("end");
79
+ const root = new Map();
80
+ for (const p of prefixes) {
81
+ let node = root;
82
+ for (const seg of p.split("/").slice(1)) {
83
+ if (!node.has(seg)) node.set(seg, new Map());
84
+ node = node.get(seg);
85
+ }
86
+ node.set(END, true);
87
+ }
88
+ if (!root.size) return () => false;
89
+ return (path) => {
90
+ let node = root;
91
+ for (let at = 1; ; ) {
92
+ const next = path.indexOf("/", at);
93
+ node = node.get(next === -1 ? path.slice(at) : path.slice(at, next));
94
+ if (!node) return false;
95
+ if (node.has(END)) return true;
96
+ if (next === -1) return false;
97
+ at = next + 1;
98
+ }
99
+ };
100
+ }
101
+
102
+ /**
103
+ * The circuit breaker: hold back a pass's deletions in a direction when there
104
+ * are more than MASS_DELETE_FLOOR of them AND they would leave fewer than half
105
+ * of the paths tracked — measured against the most this session has tracked
106
+ * (`peak`), so deletes sliced across passes add up rather than each slice
107
+ * being judged against what the last one left.
108
+ *
109
+ * Deletion is the one action that cannot be undone — a delete drops the VFS
110
+ * history record, and a local delete removes what may be the last copy — and
111
+ * the ways a sync goes wrong all look the same from here: a remote root that
112
+ * was renamed or went missing, a walk that came back empty, a local directory
113
+ * wiped by a checkout, read as "the user deleted everything". People delete a
114
+ * few files at a time; they do not delete most of a project between two
115
+ * passes of a sync. Half is the line: past it, the plan is more likely a
116
+ * broken view than an edit.
117
+ *
118
+ * The floor exists for small projects, where "most of the files" is two or
119
+ * three and an ordinary cleanup crosses half. Three is small enough that a
120
+ * broken view of a small project costs at most three files — the same as the
121
+ * cleanups it lets through — and large enough that deleting a couple of files
122
+ * from a four-file project is not treated as an emergency.
123
+ *
124
+ * An EMPTY view is held whatever the count. The count rule alone let a small
125
+ * project's local copy go when the remote came back empty — three of three
126
+ * is not more than the floor — and an empty side with a non-empty history is
127
+ * the broken view in its plainest form. `views` gives how many files each
128
+ * side holds this pass; a delete-local needs something remote, and a
129
+ * delete-remote something local. The cost is that deleting the LAST file of a
130
+ * project has to be done by hand, which the warning says how to do.
131
+ *
132
+ * Held deletes are dropped from the plan outright, so their state entries stay
133
+ * as they were: the next pass sees the same picture rather than "forgotten
134
+ * files" to copy back.
135
+ *
136
+ * What this is NOT: a defence against whatever can write the filesystem. It
137
+ * catches broken views — a renamed root, an empty walk, a wiped checkout. A
138
+ * remote party can add filler files first, so that its deletions are a
139
+ * minority of what is tracked; `--allow-delete` trusts the remote, and the
140
+ * breaker does not change that.
141
+ */
142
+ export const MASS_DELETE_FLOOR = 3;
143
+
144
+ export function holdMassDeletes(plan, last, views = {}, peak = 0) {
145
+ const tracked = Object.keys(last).length;
146
+ const most = Math.max(tracked, peak);
147
+ const held = [];
148
+ for (const [action, other] of [["delete-local", "remote"], ["delete-remote", "local"]]) {
149
+ const count = plan.filter((p) => p.action === action).length;
150
+ if (!count) continue;
151
+ if (views[other] === 0) held.push({ action, count, tracked, empty: true });
152
+ else if (count > MASS_DELETE_FLOOR && tracked - count < most / 2) held.push({ action, count, tracked });
153
+ }
154
+ if (!held.length) return { plan, held };
155
+ const holding = new Set(held.map((h) => h.action));
156
+ return { plan: plan.filter((p) => !holding.has(p.action)), held };
157
+ }
package/src/lib/ui.js CHANGED
@@ -1,11 +1,53 @@
1
1
  /**
2
2
  * Minimal terminal UI helpers — colors, status lines, tables, and prompts.
3
- * No dependencies; respects `NO_COLOR` and non-TTY output.
3
+ * No dependencies; respects `NO_COLOR`, `FORCE_COLOR` and non-TTY output.
4
+ *
5
+ * Everything printed here is made PRINTABLE first. Commit messages, branch
6
+ * names, authors and file names are written by whatever holds the user's
7
+ * seed, and a terminal obeys escape sequences in anything it prints: OSC 52
8
+ * sets the clipboard in kitty, Alacritty, Windows Terminal and tmux, so a
9
+ * planted "fix typo" could load `curl … | sh` for the user to paste. The
10
+ * escaping lives in these helpers, not at call sites, so no call site can
11
+ * forget it. The CLI's own line breaks are separate arguments, and its
12
+ * colours are marks rendered after the escaping — the only control codes that
13
+ * get through.
4
14
  */
5
15
 
16
+ import { randomUUID } from "node:crypto";
17
+
6
18
  const ESC = String.fromCharCode(27);
7
- const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
8
- const wrap = (code) => (s) => (useColor ? `${ESC}[${code}m${s}${ESC}[0m` : String(s));
19
+ // FORCE_COLOR=0 and =false mean "no colour" to supports-color and chalk, so
20
+ // they must not turn it on here — into a log or a pipe.
21
+ const force = process.env.FORCE_COLOR;
22
+ const forced = Boolean(force) && force !== "0" && force !== "false";
23
+ const useColor = Boolean((forced || (process.stdout.isTTY && force !== "0" && force !== "false")) && !process.env.NO_COLOR);
24
+
25
+ /**
26
+ * A colour is a mark, rendered as an escape code only after the text around
27
+ * it has been escaped. The mark carries a nonce made when this process
28
+ * started, so no text written before — a commit message, a file name — can
29
+ * contain one.
30
+ */
31
+ const MARK = `\ue000${randomUUID().replace(/-/g, "")}:`;
32
+ const MARKS = new RegExp(`${MARK}(\\d+)m`, "g");
33
+ const wrap = (code) => (s) => (useColor ? `${MARK}${code}m${s}${MARK}0m` : String(s));
34
+
35
+ /**
36
+ * Control characters (C0 — newlines and tabs included — DEL and C1), bidi
37
+ * overrides and isolates, line and paragraph separators, and the invisible
38
+ * characters that make one name look like another.
39
+ */
40
+ const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u061c\u200b\u200e\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g;
41
+ const escapeChar = (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`;
42
+
43
+ /** `value` with every unprintable character written as a visible \uXXXX escape. */
44
+ export function printable(value) {
45
+ return String(value).replace(UNPRINTABLE, escapeChar);
46
+ }
47
+
48
+ /** One line of output: escaped, then the CLI's own colours rendered. */
49
+ const render = (line) => printable(line).replace(MARKS, (_, code) => `${ESC}[${code}m`);
50
+ const lines = (all) => all.map(render).join("\n");
9
51
 
10
52
  export const c = {
11
53
  bold: wrap("1"),
@@ -17,28 +59,48 @@ export const c = {
17
59
  cyan: wrap("36"),
18
60
  };
19
61
 
20
- export function info(msg = "") {
21
- console.log(msg);
62
+ // Each argument is one line: a newline INSIDE an argument is escaped like
63
+ // any other control character, so a message that runs to several lines
64
+ // passes them as separate arguments.
65
+ export function info(...all) {
66
+ console.log(lines(all));
22
67
  }
23
- export function ok(msg) {
24
- console.log(`${c.green("✓")} ${msg}`);
68
+ export function ok(first, ...more) {
69
+ console.log(lines([`${c.green("✓")} ${first}`, ...more]));
25
70
  }
26
- export function warn(msg) {
27
- console.log(`${c.yellow("⚠")} ${msg}`);
71
+ export function warn(first, ...more) {
72
+ console.log(lines([`${c.yellow("⚠")} ${first}`, ...more]));
28
73
  }
29
- export function step(msg) {
30
- console.log(`${c.dim("→")} ${msg}`);
74
+ export function step(first, ...more) {
75
+ console.log(lines([`${c.dim("→")} ${first}`, ...more]));
31
76
  }
32
77
 
33
78
  /** Print an error and exit non-zero. */
34
- export function die(msg) {
35
- console.error(`\n${c.red("✗")} ${msg}\n`);
79
+ export function die(first, ...more) {
80
+ console.error(lines(["", `${c.red("✗")} ${first}`, ...more, ""]));
36
81
  process.exit(1);
37
82
  }
38
83
 
39
- /** Pretty-print JSON to stdout (used by `--json` and `get` commands). */
84
+ /**
85
+ * Pretty-print JSON to stdout (used by `--json` and `get` commands). Still
86
+ * valid JSON: what JSON.stringify leaves raw — C1, bidi and the rest — is
87
+ * written as \uXXXX, which parses back to the same string.
88
+ */
89
+ const JSON_UNPRINTABLE = /[\u007f-\u009f\u061c\u200b\u200e\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]/g;
40
90
  export function json(obj) {
41
- console.log(JSON.stringify(obj, null, 2));
91
+ console.log(JSON.stringify(obj, null, 2).replace(MARKS, "").replace(JSON_UNPRINTABLE, escapeChar));
92
+ }
93
+
94
+ /**
95
+ * A file's text, as the user asked to see it (`vfs cat`). Piped or
96
+ * redirected, it is written exactly as it is. To a terminal, its own line
97
+ * breaks (LF, CRLF) and tabs are kept and every other control character is
98
+ * escaped — a lone CR included, since it lets one line print over another.
99
+ */
100
+ const TEXT_UNPRINTABLE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u061c\u200b\u200e\u200f\u2028-\u202e\u2060\u2066-\u2069\ufeff]|\r(?!\n)/g;
101
+ export function writeText(text) {
102
+ const s = String(text);
103
+ process.stdout.write(process.stdout.isTTY ? s.replace(TEXT_UNPRINTABLE, escapeChar) : s);
42
104
  }
43
105
 
44
106
  /**
@@ -52,15 +114,22 @@ export function redact(s) {
52
114
  .replace(/\b[A-Za-z0-9._-]{40,}\b/g, (m) => m.slice(0, 6) + "…[redacted]");
53
115
  }
54
116
 
55
- /** Render a simple aligned table from rows of strings. */
117
+ /**
118
+ * Render a simple aligned table from rows of strings. Cells are escaped
119
+ * before they are measured, so a planted escape cannot misalign a column, and
120
+ * a colour mark takes no width.
121
+ */
56
122
  export function table(headers, rows) {
57
- const widths = headers.map((h, i) =>
58
- Math.max(h.length, ...rows.map((r) => String(r[i] ?? "").length)),
59
- );
60
- const line = (cells) =>
61
- cells.map((cell, i) => String(cell ?? "").padEnd(widths[i])).join(" ");
62
- console.log(c.bold(line(headers)));
63
- for (const r of rows) console.log(line(r));
123
+ const cells = (row) => row.map((cell) => printable(cell ?? ""));
124
+ const head = cells(headers);
125
+ const body = rows.map(cells);
126
+ const width = (cell) => cell.replace(MARKS, "").length;
127
+ const widths = head.map((h, i) => Math.max(width(h), ...body.map((r) => width(r[i] ?? ""))));
128
+ const line = (row) =>
129
+ row.map((cell, i) => cell + " ".repeat(Math.max(0, widths[i] - width(cell ?? "")))).join(" ");
130
+ const out = (text) => text.replace(MARKS, (_, code) => `${ESC}[${code}m`);
131
+ console.log(out(c.bold(line(head))));
132
+ for (const r of body) console.log(out(line(r)));
64
133
  }
65
134
 
66
135
  /** Prompt for a line of input on stdin. */
package/src/lib/vfs.js CHANGED
@@ -23,6 +23,11 @@ import { die, info, step, prompt, promptHidden } from "./ui.js";
23
23
  *
24
24
  * Returns the client so callers can reach `client.vfs` — and anything else the
25
25
  * SDK offers — rather than a narrow wrapper that would drift from it.
26
+ *
27
+ * `args.readOnly` (a dry run) saves nothing to ~/.muhkoo: no pairing, no reset
28
+ * of a stale working directory, and a revoked pairing is reported but left for
29
+ * the next ordinary command to forget. `--no-pair` (or `pair: false`) skips the
30
+ * pairing alone, unlocking for this command only.
26
31
  */
27
32
  export async function openClient(args) {
28
33
  const cfg = await loadConfig();
@@ -65,7 +70,7 @@ export async function openClient(args) {
65
70
  // back to the root rather than making every later command fail.
66
71
  if (cfg.vfsCwd && cfg.vfsCwd !== "/") {
67
72
  await client.vfs.cd(cfg.vfsCwd).catch(async () => {
68
- await saveConfig({ ...cfg, vfsCwd: "/" });
73
+ if (!args.readOnly) await saveConfig({ ...cfg, vfsCwd: "/" });
69
74
  info(`Working directory ${cfg.vfsCwd} is gone — back to /.`);
70
75
  });
71
76
  }
@@ -100,19 +105,27 @@ async function unlock({ args, cfg, baseUrl, client }) {
100
105
  // password prompt would quietly re-pair a machine whose access was
101
106
  // deliberately withdrawn.
102
107
  if (/revoked|no longer paired/i.test(msg)) {
103
- await saveConfig({ ...cfg, deviceFactorId: undefined, deviceKey: undefined });
108
+ if (!args.readOnly) await saveConfig({ ...cfg, deviceFactorId: undefined, deviceKey: undefined });
104
109
  die(msg);
105
110
  }
106
- info(`Stored device key did not work (${msg}) — signing in to re-pair.`);
111
+ info(`Stored device key did not work (${msg}) — signing in${pairs(args) ? " to re-pair" : " for this command only"}.`);
107
112
  }
108
113
  }
109
114
 
110
115
  await pairThisMachine({ args, cfg, baseUrl, client });
111
116
  }
112
117
 
113
- /** Sign in once, pair this machine, and unlock the passed client. */
118
+ /**
119
+ * Sign in once, pair this machine, and unlock the passed client — or, with
120
+ * `--no-pair` or read-only, sign in and unlock for this command alone.
121
+ */
114
122
  async function pairThisMachine({ args, cfg, baseUrl, client }) {
115
- info("This machine is not paired yet — signing in once to pair it.");
123
+ const pairing = pairs(args);
124
+ info(
125
+ pairing
126
+ ? "This machine is not paired yet — signing in once to pair it."
127
+ : "This machine is not paired — signing in for this command only; nothing is stored.",
128
+ );
116
129
  const username = args.username || cfg.username || (await prompt("Username: "));
117
130
  const password = args.password || process.env.MUHKOO_PASSWORD || (await promptHidden("Password: "));
118
131
  if (!username || !password) die("A username and password are required to pair this machine.");
@@ -127,8 +140,8 @@ async function pairThisMachine({ args, cfg, baseUrl, client }) {
127
140
  const seed = authed.auth.zk.seedBase64;
128
141
  if (!seed) die("Signed in, but no encryption key was recovered — the account may have no password factor.");
129
142
 
130
- if (args.pair === false) {
131
- client.auth.zk.unlockWithSeed(seed); // --no-pair: unlock now, store nothing
143
+ if (!pairing) {
144
+ client.auth.zk.unlockWithSeed(seed); // unlock now, store nothing
132
145
  return;
133
146
  }
134
147
 
@@ -141,6 +154,16 @@ async function pairThisMachine({ args, cfg, baseUrl, client }) {
141
154
  info(`Paired this machine as "${label}". Revoke it any time: muhkoo devices rm ${factorId}`);
142
155
  }
143
156
 
157
+ /**
158
+ * Does this command pair a machine that is not paired? Not with `--no-pair`,
159
+ * and not read-only. The parser hands `--no-pair` over as `"no-pair": true`
160
+ * (or the word after it); only `pair: false` was ever read, so the flag did
161
+ * nothing.
162
+ */
163
+ function pairs(args) {
164
+ return args.pair !== false && !args["no-pair"] && !args.readOnly;
165
+ }
166
+
144
167
  /** A name the owner will recognise in `muhkoo devices ls`. */
145
168
  function deviceLabel() {
146
169
  return `${userInfo().username}@${hostname()}`;
@@ -162,7 +185,8 @@ function resolveAppKey(args, cfg) {
162
185
  }
163
186
 
164
187
  /**
165
- * Turn the shard store's 401 into an instruction.
188
+ * Turn the shard store's 401 into an instruction: the lines to print, or null
189
+ * when `err` is some other failure.
166
190
  *
167
191
  * "API key required to store shards" is accurate and useless — it names a
168
192
  * concept the person at the terminal has no reason to know, and says nothing
@@ -170,13 +194,12 @@ function resolveAppKey(args, cfg) {
170
194
  */
171
195
  export function explainWriteFailure(err, cfg) {
172
196
  const msg = err?.message ?? String(err);
173
- if (!/API key required|store shards|401/.test(msg)) return msg;
197
+ if (!/API key required|store shards|401/.test(msg)) return null;
174
198
  const known = Object.keys(cfg?.vfsApps ?? {});
175
- return (
176
- "Writing stores bytes, which are metered to an app — so a write needs one signed in.\n" +
177
- (known.length
178
- ? `Try: muhkoo vfs use-app ${known[0]}`
179
- : "Sign one in with: muhkoo vfs use-app <slug> --key <appKey>\n" +
180
- "App keys are shown when an app is created (muhkoo apps create).")
181
- );
199
+ return [
200
+ "Writing stores bytes, which are metered to an app — so a write needs one signed in.",
201
+ ...(known.length
202
+ ? [`Try: muhkoo vfs use-app ${known[0]}`]
203
+ : ["Sign one in with: muhkoo vfs use-app <slug> --key <appKey>", "App keys are shown when an app is created (muhkoo apps create)."]),
204
+ ];
182
205
  }
@@ -124,7 +124,7 @@ export async function webLogin({ baseUrl, appId }) {
124
124
 
125
125
  step("Opening your browser to sign in…");
126
126
  const opened = openBrowser(authUrl);
127
- info(`${opened ? "If it didn't open, visit:" : "Open this URL to sign in:"}\n ${c.cyan(authUrl)}\n`);
127
+ info(`${opened ? "If it didn't open, visit:" : "Open this URL to sign in:"}`, ` ${c.cyan(authUrl)}`, "");
128
128
 
129
129
  let code;
130
130
  try {