@kaynooo/cli-edit 0.11.1 → 0.11.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.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.js +440 -202
  3. package/package.json +6 -6
package/README.md CHANGED
@@ -35,3 +35,5 @@ EOF
35
35
  - `--quiet` prints nothing on success. Each written file prints `<path>: N replacements on lines L, +added -removed`; `--diff` adds its unified diff (through the system's `diff`), `--dry-run` shows the same without writing.
36
36
  - The file is rewritten in place, so its mode, owner and missing trailing newline stay.
37
37
  - Exit codes: 0 written, 1 a replacement did not match as expected, 2 a usage error.
38
+ - A folder given as a file is walked, `.gitignore` respected and binary files left out; a file in it where nothing matches is skipped and listed (`--skip-missing`), the count checks holding for the others.
39
+ - A producer silent on stdin for 3 s is taken for no heredoc at all, so write a slow one to a file first.
package/dist/cli.js CHANGED
@@ -1,23 +1,19 @@
1
1
  #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
2
  // @bun
3
+ var __esm = (fn, res, err) => () => {
4
+ if (fn)
5
+ try {
6
+ res = fn(fn = 0);
7
+ } catch (e) {
8
+ err = [e];
9
+ }
10
+ if (err)
11
+ throw err[0];
12
+ return res;
13
+ };
3
14
 
4
- // src/cli.ts
5
- import { accessSync, chmodSync, constants as constants2, existsSync as existsSync5, readFileSync as readFileSync5, realpathSync as realpathSync3, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
6
- import { normalize, resolve as resolve4 } from "path";
7
- import process17 from "process";
8
- // ../kit/src/args.ts
9
- import process10 from "process";
10
- import { parseArgs } from "util";
11
-
12
- // ../kit/src/format.ts
13
- import process7 from "process";
14
-
15
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
16
- var ct = /[aeiou]y$/;
17
- var N = new Map;
18
- var Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
19
- var Gt = /(?:knife|life|wife)$/;
20
- function K(t, e, { plural: r, zero: n = "singular" } = {}) {
15
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
+ function G(t, e, { plural: r, zero: n = "singular" } = {}) {
21
17
  if (e === 1 || e === 0 && n === "singular")
22
18
  return t;
23
19
  if (r !== undefined)
@@ -30,16 +26,26 @@ function K(t, e, { plural: r, zero: n = "singular" } = {}) {
30
26
  return `${t.slice(0, -1)}ves`;
31
27
  return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
32
28
  }
33
- function go(t, e, { zero: r = "plural", ...n } = {}) {
34
- return `${t} ${K(e, t, { ...n, zero: r })}`;
35
- }
36
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
37
- var z = new Map;
29
+ function bo(t, e, { zero: r = "plural", ...n } = {}) {
30
+ return `${t} ${G(e, t, { ...n, zero: r })}`;
31
+ }
32
+ var ct, N, Ot, Gt, be, W;
33
+ var init_chunk_rkhsft4a = __esm(() => {
34
+ ct = /[aeiou]y$/;
35
+ N = new Map;
36
+ Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
37
+ Gt = /(?:knife|life|wife)$/;
38
+ be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
39
+ W = new Map;
40
+ });
41
+
42
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
43
+ var init_text = __esm(() => {
44
+ init_chunk_rkhsft4a();
45
+ });
38
46
 
39
47
  // ../kit/src/mode.ts
40
48
  import process2 from "process";
41
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
42
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
43
49
  function isSet(value) {
44
50
  return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
45
51
  }
@@ -53,12 +59,13 @@ function outputMode(stream = process2.stdout, env = process2.env) {
53
59
  return "terminal";
54
60
  return isSet(env.CI) ? "ci" : "pipe";
55
61
  }
62
+ var MODES, AGENT_VARIABLES;
63
+ var init_mode = __esm(() => {
64
+ MODES = new Set(["terminal", "ci", "agent", "pipe"]);
65
+ AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
66
+ });
56
67
 
57
- // ../kit/src/style.ts
58
- import process6 from "process";
59
-
60
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
61
- var G2 = /^[a-f0-9]+$/i;
68
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
62
69
  function b(r) {
63
70
  let e = r.startsWith("#") ? r.slice(1) : r;
64
71
  if (!G2.test(e))
@@ -69,11 +76,6 @@ function b(r) {
69
76
  throw Error(`Invalid hex color length: ${e.length}`);
70
77
  return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
71
78
  }
72
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
73
- let [l, n, c] = b(r);
74
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
75
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
76
- var h = new Set(["", "1", "2", "3", "true"]);
77
79
  function C(r, e = globalThis.process?.env ?? {}) {
78
80
  if (e.FORCE_COLOR !== undefined)
79
81
  return h.has(e.FORCE_COLOR);
@@ -87,7 +89,7 @@ function f(r, e = []) {
87
89
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
88
90
  let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
89
91
  return new Proxy(c, { get(t, i) {
90
- let a = B2[i];
92
+ let a = B[i];
91
93
  if (Array.isArray(a)) {
92
94
  let s = g.get(i);
93
95
  if (s === undefined)
@@ -110,13 +112,21 @@ function f(r, e = []) {
110
112
  function Fe(r = {}) {
111
113
  return f(r);
112
114
  }
113
- var o = Fe();
115
+ var G2, B, h, o;
116
+ var init_chunk_x450vn3m = __esm(() => {
117
+ G2 = /^[a-f0-9]+$/i;
118
+ B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
119
+ let [l, n, c] = b(r);
120
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
121
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
122
+ h = new Set(["", "1", "2", "3", "true"]);
123
+ o = Fe();
124
+ });
114
125
 
115
- // ../kit/src/theme.ts
116
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
117
- import { homedir as homedir2 } from "os";
118
- import { join as join3, resolve as resolve2 } from "path";
119
- import process5 from "process";
126
+ // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
127
+ var init_colors = __esm(() => {
128
+ init_chunk_x450vn3m();
129
+ });
120
130
 
121
131
  // ../kit/src/config.ts
122
132
  import { existsSync } from "fs";
@@ -132,15 +142,21 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
132
142
  return;
133
143
  }
134
144
  }
145
+ var init_config = __esm(() => {
146
+ init_args();
147
+ });
135
148
 
136
149
  // ../kit/src/user-config.ts
137
150
  import { existsSync as existsSync2, readFileSync } from "fs";
138
151
  import { homedir } from "os";
139
- import { join as join2 } from "path";
152
+ import { isAbsolute, join as join2 } from "path";
140
153
  import process4 from "process";
154
+ function xdgFolder(value, fallback) {
155
+ return value !== undefined && isAbsolute(value) ? value : fallback;
156
+ }
141
157
  function configBase(where = {}) {
142
158
  const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
143
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
159
+ return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
144
160
  }
145
161
  function userConfigPath(bin, where = {}) {
146
162
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
@@ -163,36 +179,18 @@ function readUserConfig(bin, where = {}, legacy = []) {
163
179
  return {};
164
180
  }
165
181
  }
182
+ var init_user_config = () => {};
166
183
 
167
184
  // ../kit/src/theme.ts
168
- var ENDS = new Map;
169
- var DEFAULT = {
170
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
171
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
172
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
173
- bins: {},
174
- gradient: ["#c084fc", "#67e8f9"]
175
- };
176
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
177
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
178
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
179
- var PRESETS = {
180
- default: {},
181
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
182
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
183
- ascii: { glyphs: ASCII }
184
- };
185
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
186
- var HEX = /^#[0-9a-f]{6}$/i;
187
- var CONTROL = /\p{Cc}/u;
188
- var MAX_FILE_BYTES = 64 * 1024;
189
- var SPACES = /\s+/;
185
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
186
+ import { homedir as homedir2 } from "os";
187
+ import { join as join3, resolve as resolve2 } from "path";
188
+ import process5 from "process";
190
189
  function isColorSpec(spec) {
191
190
  if (typeof spec === "number")
192
191
  return Number.isInteger(spec) && spec >= 0 && spec <= 255;
193
192
  return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
194
193
  }
195
- var CUBE = [0, 95, 135, 175, 215, 255];
196
194
  function cubeLevel(channel) {
197
195
  return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
198
196
  }
@@ -297,7 +295,6 @@ function applyFile(theme, file, where, warn) {
297
295
  function endsWalk(home) {
298
296
  return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
299
297
  }
300
- var warned = new Set;
301
298
  function warnOnce(message) {
302
299
  if (warned.has(message))
303
300
  return;
@@ -334,8 +331,6 @@ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(
334
331
  }
335
332
  return { theme, sources, preset };
336
333
  }
337
- var current;
338
- var currentKey = "";
339
334
  function activeTheme() {
340
335
  const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
341
336
  if (current === undefined || key !== currentKey) {
@@ -344,8 +339,38 @@ function activeTheme() {
344
339
  }
345
340
  return current;
346
341
  }
342
+ var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
343
+ var init_theme = __esm(() => {
344
+ init_config();
345
+ init_user_config();
346
+ ENDS = new Map;
347
+ DEFAULT = {
348
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
349
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
350
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
351
+ bins: {},
352
+ gradient: ["#c084fc", "#67e8f9"]
353
+ };
354
+ BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
355
+ MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
356
+ ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
357
+ PRESETS = {
358
+ default: {},
359
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
360
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
361
+ ascii: { glyphs: ASCII }
362
+ };
363
+ STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
364
+ HEX = /^#[0-9a-f]{6}$/i;
365
+ CONTROL = /\p{Cc}/u;
366
+ MAX_FILE_BYTES = 64 * 1024;
367
+ SPACES = /\s+/;
368
+ CUBE = [0, 95, 135, 175, 215, 255];
369
+ warned = new Set;
370
+ });
347
371
 
348
372
  // ../kit/src/style.ts
373
+ import process6 from "process";
349
374
  function takesControlCodes(stream, env = process6.env) {
350
375
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
351
376
  }
@@ -356,17 +381,23 @@ function role(name, stream, env = process6.env) {
356
381
  const colors = paint(stream, env);
357
382
  return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
358
383
  }
359
- var STATUS_WORDS = {
360
- passed: ["passed", "success", "succeeded", "ok"],
361
- failed: ["failed", "failure", "error", "errored"],
362
- running: ["running", "in_progress", "started", "holding"],
363
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
364
- skipped: ["skipped", "cancelled", "canceled", "manual"]
365
- };
366
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
384
+ var STATUS_WORDS, STATUS_OF;
385
+ var init_style = __esm(() => {
386
+ init_colors();
387
+ init_mode();
388
+ init_theme();
389
+ STATUS_WORDS = {
390
+ passed: ["passed", "success", "succeeded", "ok"],
391
+ failed: ["failed", "failure", "error", "errored"],
392
+ running: ["running", "in_progress", "started", "holding"],
393
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
394
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
395
+ };
396
+ STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
397
+ });
367
398
 
368
399
  // ../kit/src/format.ts
369
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
400
+ import process7 from "process";
370
401
  function formatSeconds(total) {
371
402
  let rest = Math.max(0, Math.round(total));
372
403
  const amounts = UNITS.map(([unit, size]) => {
@@ -387,21 +418,44 @@ function upTo(text, separator) {
387
418
  const end = text.indexOf(separator);
388
419
  return end === -1 ? text : text.slice(0, end);
389
420
  }
390
- var ESCAPE = String.fromCharCode(27);
391
421
  function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
392
422
  return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
393
423
  }
394
424
  function printJson(value) {
395
425
  console.log(jsonText(value));
396
426
  }
427
+ var UNITS, ESCAPE;
428
+ var init_format = __esm(() => {
429
+ init_mode();
430
+ init_style();
431
+ UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
432
+ ESCAPE = String.fromCharCode(27);
433
+ });
397
434
 
398
435
  // ../kit/src/help.ts
399
436
  import process8 from "process";
400
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
401
- var USAGE_PREFIX = /^usage:\s*/i;
402
- var FULL_STOP = /\.$/;
403
437
  function usageLine(usage, colors = paint(process8.stdout)) {
404
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
438
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
439
+ `);
440
+ const blank = lines.indexOf("");
441
+ const synopses = blank === -1 ? lines : lines.slice(0, blank);
442
+ const details = blank === -1 ? [] : lines.slice(blank + 1);
443
+ const colon = synopses[0].indexOf(": ");
444
+ const inline = synopses[0].slice(colon + 2);
445
+ const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
446
+ if (colon !== -1)
447
+ synopses[0] = synopses[0].slice(0, colon);
448
+ const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
449
+ `)}`;
450
+ const lead = summary === undefined ? [] : ["", colors.bold(prose(summary, colors))];
451
+ const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
452
+ return [head, ...lead, ...rest].join(`
453
+ `);
454
+ }
455
+ function prose(line, colors) {
456
+ if (colors.cyan("x") === "x")
457
+ return line;
458
+ return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
405
459
  }
406
460
  function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
407
461
  return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
@@ -436,7 +490,6 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
436
490
  return [];
437
491
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
438
492
  }
439
- var MAX_INLINE_CHOICES = 24;
440
493
  function optionRows(options, colors = paint(process8.stdout)) {
441
494
  const rows = Object.entries(options).map(([name, option]) => {
442
495
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
@@ -451,6 +504,15 @@ function optionRows(options, colors = paint(process8.stdout)) {
451
504
  const width = Math.max(0, ...rows.map((row) => row.width));
452
505
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
453
506
  }
507
+ var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
508
+ var init_help = __esm(() => {
509
+ init_mode();
510
+ init_style();
511
+ OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
512
+ USAGE_PREFIX = /^usage:\s*/i;
513
+ FULL_STOP = /\.$/;
514
+ PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
515
+ });
454
516
 
455
517
  // ../kit/src/text.ts
456
518
  function distance(a, b) {
@@ -478,9 +540,10 @@ function closest(name, names) {
478
540
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
479
541
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
480
542
  }
543
+ var init_text2 = () => {};
544
+
481
545
  // ../kit/src/input.ts
482
546
  import process9 from "process";
483
- var WHOLE = /^\d+$/;
484
547
  function wholeNumber(value, name, fallback, min = 1) {
485
548
  if (value === undefined)
486
549
  return fallback;
@@ -500,40 +563,25 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
500
563
  fail(`no file ${path}`);
501
564
  return file.text();
502
565
  }
566
+ var WHOLE;
567
+ var init_input = __esm(() => {
568
+ init_args();
569
+ WHOLE = /^\d+$/;
570
+ });
503
571
 
504
572
  // ../kit/src/args.ts
505
- var DASHES = /^-+/;
573
+ import process10 from "process";
574
+ import { parseArgs } from "util";
506
575
  function jsonOption(holds) {
507
576
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
508
577
  }
509
- class Exit extends Error {
510
- code;
511
- hint;
512
- constructor(message, code, hint) {
513
- super(message);
514
- this.code = code;
515
- this.hint = hint;
516
- }
517
- }
518
578
  function fail(message, code = 2, hint) {
519
579
  throw new Exit(message, code, hint);
520
580
  }
521
-
522
- class UsageError extends Exit {
523
- constructor(message, hint) {
524
- super(message, 2, hint);
525
- }
526
- }
527
581
  function badUsage(message) {
528
582
  throw new UsageError(message);
529
583
  }
530
584
 
531
- class HelpShown extends Exit {
532
- constructor() {
533
- super("help shown", 0);
534
- }
535
- }
536
-
537
585
  class Completing {
538
586
  options;
539
587
  positionals;
@@ -544,11 +592,6 @@ class Completing {
544
592
  this.candidates = candidates;
545
593
  }
546
594
  }
547
- var completion = { active: false };
548
- var OUTPUT_OPTIONS = {
549
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
550
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
551
- };
552
595
  function applyOutput(color, plain, env = process10.env) {
553
596
  const when = plain === true ? "never" : color ?? "auto";
554
597
  if (when === "auto")
@@ -702,7 +745,6 @@ function parseError(error) {
702
745
  const message = upTo(error instanceof Error ? error.message : String(error), ". ");
703
746
  return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
704
747
  }
705
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
706
748
  function nearestOption(message, options, allowNegative) {
707
749
  const typed = UNKNOWN_OPTION.exec(message)?.[1];
708
750
  if (typed === undefined)
@@ -718,6 +760,68 @@ function nearestOption(message, options, allowNegative) {
718
760
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
719
761
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
720
762
  }
763
+ var DASHES, EXIT, Exit, UsageError, HelpShown, completion, OUTPUT_OPTIONS, UNKNOWN_OPTION;
764
+ var init_args = __esm(() => {
765
+ init_format();
766
+ init_help();
767
+ init_text2();
768
+ init_help();
769
+ init_input();
770
+ DASHES = /^-+/;
771
+ EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
772
+ Exit = class Exit extends Error {
773
+ code;
774
+ hint;
775
+ [EXIT] = true;
776
+ constructor(message, code, hint) {
777
+ super(message);
778
+ this.code = code;
779
+ this.hint = hint;
780
+ }
781
+ static [Symbol.hasInstance](value) {
782
+ if (this !== Exit)
783
+ return Function.prototype[Symbol.hasInstance].call(this, value);
784
+ return typeof value === "object" && value !== null && value[EXIT] === true;
785
+ }
786
+ };
787
+ UsageError = class UsageError extends Exit {
788
+ constructor(message, hint) {
789
+ super(message, 2, hint);
790
+ }
791
+ };
792
+ HelpShown = class HelpShown extends Exit {
793
+ constructor() {
794
+ super("help shown", 0);
795
+ }
796
+ };
797
+ completion = { active: false };
798
+ OUTPUT_OPTIONS = {
799
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
800
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
801
+ };
802
+ UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
803
+ });
804
+
805
+ // ../kit/src/folders.ts
806
+ function ignoredFolders(extra = [], where = {}) {
807
+ const configured = readUserConfig("config", where).ignore;
808
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
809
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
810
+ }
811
+ var SKIPPED_FOLDERS;
812
+ var init_folders = __esm(() => {
813
+ init_user_config();
814
+ SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
815
+ });
816
+
817
+ // src/cli.ts
818
+ import { accessSync, chmodSync, constants as constants2, existsSync as existsSync5, readFileSync as readFileSync5, realpathSync as realpathSync3, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
819
+ import { dirname as dirname4, normalize, resolve as resolve4 } from "path";
820
+ import process18 from "process";
821
+
822
+ // ../kit/src/index.ts
823
+ init_args();
824
+
721
825
  // ../kit/src/argv.ts
722
826
  import { readFileSync as readFileSync3, realpathSync } from "fs";
723
827
  import { resolve as resolve3 } from "path";
@@ -742,10 +846,23 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
742
846
  const after = at === -1 ? [] : cmdline.slice(at + 1);
743
847
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
744
848
  }
849
+ // ../kit/src/chart.ts
850
+ init_format();
851
+ init_mode();
852
+ init_style();
853
+ init_theme();
854
+ // ../kit/src/ci.ts
855
+ init_args();
856
+ init_format();
857
+
858
+ // ../kit/src/progress.ts
859
+ init_format();
860
+
745
861
  // ../kit/src/process.ts
746
862
  import { constants } from "os";
747
863
  import process12 from "process";
748
864
  var KILL_GRACE_MS = 2000;
865
+ var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
749
866
  function exitCodeOf(code, signal) {
750
867
  if (code !== null)
751
868
  return code;
@@ -753,10 +870,10 @@ function exitCodeOf(code, signal) {
753
870
  return 128 + signal;
754
871
  return signal === null ? 129 : 128 + constants.signals[signal];
755
872
  }
756
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
873
+ async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
757
874
  const chunks = [];
758
875
  const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
759
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
876
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
760
877
  const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
761
878
  const timers = [];
762
879
  const killGroup = (killing) => {
@@ -796,12 +913,19 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
796
913
  stop();
797
914
  continue;
798
915
  }
916
+ if (state.truncated)
917
+ continue;
918
+ let kept = data;
799
919
  if (state.kept + data.length > maxBytes) {
920
+ let cut = maxBytes - state.kept;
921
+ while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
922
+ cut--;
923
+ kept = data.subarray(0, cut);
800
924
  state.truncated = true;
801
- continue;
802
925
  }
803
- state.kept += data.length;
804
- chunks.push({ stream: name, data });
926
+ state.kept += kept.length;
927
+ if (kept.length > 0)
928
+ chunks.push({ stream: name, data: kept });
805
929
  }
806
930
  };
807
931
  try {
@@ -818,6 +942,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
818
942
  const joined = () => Buffer.concat(chunks.map(({ data }) => data));
819
943
  let output;
820
944
  let text;
945
+ let stdout;
821
946
  return {
822
947
  code: exitCodeOf(proc.exitCode, proc.signalCode),
823
948
  chunks,
@@ -828,19 +953,70 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
828
953
  },
829
954
  get text() {
830
955
  return text ??= (output ??= joined()).toString();
956
+ },
957
+ get stdout() {
958
+ return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
831
959
  }
832
960
  };
833
961
  }
834
962
 
835
963
  // ../kit/src/progress.ts
964
+ init_style();
965
+ init_theme();
836
966
  var ESC = String.fromCharCode(27);
837
967
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
838
968
  var RESET_STYLE = `${ESC}[0m`;
839
969
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
970
+
971
+ // ../kit/src/ci.ts
972
+ init_style();
973
+
974
+ // ../kit/src/tool.ts
975
+ init_format();
840
976
  // ../kit/src/cli.ts
977
+ init_args();
841
978
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
842
979
  import { dirname as dirname3, join as join5 } from "path";
843
- import process15 from "process";
980
+ import process16 from "process";
981
+
982
+ // ../kit/src/askpass.ts
983
+ import process13 from "process";
984
+ var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
985
+ async function askpassClient(argv) {
986
+ const socketPath = process13.env[SOCKET_VARIABLE];
987
+ if (socketPath === undefined)
988
+ return;
989
+ const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
990
+ const { promise, resolve } = Promise.withResolvers();
991
+ let received = "";
992
+ try {
993
+ await Bun.connect({
994
+ unix: socketPath,
995
+ socket: {
996
+ open: (socket) => void socket.write(`${JSON.stringify(request)}
997
+ `),
998
+ data: (_, chunk) => {
999
+ received += chunk.toString();
1000
+ },
1001
+ close: () => resolve(received),
1002
+ error: () => resolve("")
1003
+ }
1004
+ });
1005
+ } catch {
1006
+ return 1;
1007
+ }
1008
+ const reply = await promise;
1009
+ if (reply === "")
1010
+ return 1;
1011
+ const { answer } = JSON.parse(reply);
1012
+ if (request.notice === true)
1013
+ return 0;
1014
+ if (answer === undefined)
1015
+ return 1;
1016
+ process13.stdout.write(`${answer}
1017
+ `);
1018
+ return 0;
1019
+ }
844
1020
 
845
1021
  // ../kit/src/completions.ts
846
1022
  var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
@@ -903,34 +1079,42 @@ compdef __kaynooo_cli_complete ${bins.join(" ")}
903
1079
  }
904
1080
 
905
1081
  // ../kit/src/notify.ts
906
- import process13 from "process";
1082
+ init_format();
1083
+ init_mode();
1084
+ import process14 from "process";
907
1085
  var NOTIFY_AFTER_MS = 1e4;
908
1086
  var CANCELLED = 130;
909
1087
  function base64(text) {
910
1088
  return Buffer.from(text).toString("base64");
911
1089
  }
912
- function notification(title, body, env = process13.env) {
913
- const id = `kit${process13.pid}`;
1090
+ function notification(title, body, env = process14.env) {
1091
+ const id = `kit${process14.pid}`;
914
1092
  const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
915
1093
  return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
916
1094
  }
917
- function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
1095
+ function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
918
1096
  if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
919
1097
  return;
920
1098
  stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
921
1099
  }
922
1100
 
1101
+ // ../kit/src/cli.ts
1102
+ init_style();
1103
+ init_text2();
1104
+
923
1105
  // ../kit/src/usage.ts
924
1106
  import { appendFileSync, mkdirSync } from "fs";
925
1107
  import { homedir as homedir3 } from "os";
926
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
927
- import process14 from "process";
1108
+ import { dirname as dirname2, join as join4 } from "path";
1109
+ import process15 from "process";
928
1110
 
929
1111
  // ../kit/src/logs.ts
1112
+ init_user_config();
930
1113
  var DAY_MS = 24 * 60 * 60 * 1000;
931
1114
  var CLI_FOLDER = "kaynooo-cli";
932
1115
 
933
1116
  // ../kit/src/usage.ts
1117
+ init_user_config();
934
1118
  var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
935
1119
  var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
936
1120
  var LONGEST_NAME = 40;
@@ -938,14 +1122,13 @@ var usageError;
938
1122
  function noteUsageError(message) {
939
1123
  usageError = message;
940
1124
  }
941
- function stateHome(env = process14.env) {
942
- const dir = env.XDG_STATE_HOME;
943
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1125
+ function stateHome(env = process15.env) {
1126
+ return xdgFolder(env.XDG_STATE_HOME, join4(homedir3(), ".local", "state"));
944
1127
  }
945
- function usagePath(env = process14.env) {
1128
+ function usagePath(env = process15.env) {
946
1129
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
947
1130
  }
948
- function usageRecorded(env = process14.env) {
1131
+ function usageRecorded(env = process15.env) {
949
1132
  const off = env.KAYNOOO_CLI_NO_USAGE;
950
1133
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
951
1134
  }
@@ -954,12 +1137,12 @@ function flagNames(argv) {
954
1137
  const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
955
1138
  return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
956
1139
  }
957
- function usageEntry(bin, command, argv, code, now = new Date) {
1140
+ function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
958
1141
  const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
959
1142
  usageError = undefined;
960
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1143
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
961
1144
  }
962
- function recordUsage(entry, env = process14.env) {
1145
+ function recordUsage(entry, env = process15.env) {
963
1146
  if (!usageRecorded(env))
964
1147
  return;
965
1148
  try {
@@ -981,8 +1164,8 @@ var TOP_OPTIONS = {
981
1164
  completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
982
1165
  };
983
1166
  function printError(prefix, message, hint, cause) {
984
- const colors = paint(process15.stderr);
985
- const styled = takesControlCodes(process15.stderr);
1167
+ const colors = paint(process16.stderr);
1168
+ const styled = takesControlCodes(process16.stderr);
986
1169
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
987
1170
  const under = (label, text, tint) => text === undefined ? "" : `
988
1171
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1093,6 +1276,9 @@ function packageVersion(entry = Bun.main) {
1093
1276
  }
1094
1277
  }
1095
1278
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1279
+ const answered = await askpassClient(argv);
1280
+ if (answered !== undefined)
1281
+ return answered;
1096
1282
  if (argv[0] === COMPLETE)
1097
1283
  return printCandidates(leafCandidates(run, argv.slice(1)));
1098
1284
  if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
@@ -1111,24 +1297,56 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1111
1297
  notifyEnd(name, code, performance.now() - started);
1112
1298
  if (usage !== false) {
1113
1299
  try {
1114
- recordUsage(usageEntry(name, undefined, argv, code));
1300
+ recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1115
1301
  } catch {}
1116
1302
  }
1117
1303
  return code;
1118
1304
  }
1119
- // ../kit/src/folders.ts
1120
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1121
- function ignoredFolders(extra = [], where = {}) {
1122
- const configured = readUserConfig("config", where).ignore;
1123
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1124
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1125
- }
1305
+
1306
+ // ../kit/src/index.ts
1307
+ init_config();
1308
+
1309
+ // ../kit/src/excerpt.ts
1310
+ init_text2();
1311
+
1312
+ // ../kit/src/index.ts
1313
+ init_folders();
1314
+ init_format();
1315
+
1316
+ // ../kit/src/git.ts
1317
+ init_args();
1318
+ // ../kit/src/limit.ts
1319
+ init_args();
1320
+
1321
+ // ../kit/src/index.ts
1322
+ init_mode();
1323
+
1324
+ // ../kit/src/report.ts
1325
+ init_style();
1326
+ init_text2();
1126
1327
  // ../kit/src/secrets.ts
1127
1328
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1329
+ var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1128
1330
  // ../kit/src/sessions.ts
1129
1331
  var {Glob } = globalThis.Bun;
1130
1332
  var SESSION_FILES = new Glob("*.json");
1131
1333
  var ACCOUNT_DIRS = new Glob("*/sessions");
1334
+
1335
+ // ../kit/src/index.ts
1336
+ init_style();
1337
+ init_text2();
1338
+ init_theme();
1339
+ init_user_config();
1340
+
1341
+ // ../kit/src/watch.ts
1342
+ init_args();
1343
+ init_input();
1344
+ init_style();
1345
+ // ../kit/src/workspace-root.ts
1346
+ init_user_config();
1347
+ // src/cli.ts
1348
+ init_text();
1349
+
1132
1350
  // src/blocks.ts
1133
1351
  var LINE_BREAK = /\r?\n/;
1134
1352
  var OPENER = /^(<{7,}) SEARCH$/;
@@ -1211,10 +1429,13 @@ async function diffTexts(path, before, after) {
1211
1429
  }
1212
1430
 
1213
1431
  // src/replace.ts
1432
+ init_text();
1214
1433
  var CRLF = /\r?\n/g;
1215
1434
  var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
1216
1435
  var DIGITS = /^\d+$/;
1436
+ var PROPERTY_ESCAPE = /\\p\{/i;
1217
1437
  var ESCAPE2 = /\\\\|\\([nt])/g;
1438
+ var SPECIAL = /[.*+?^${}()|[\]\\]/g;
1218
1439
  var LONGEST_LIST = 8;
1219
1440
  function linesOf(text, indexes) {
1220
1441
  const lines = [];
@@ -1234,11 +1455,8 @@ function listLines(lines) {
1234
1455
  const shown = lines.slice(0, LONGEST_LIST).join(", ");
1235
1456
  return lines.length > LONGEST_LIST ? `${shown} and ${lines.length - LONGEST_LIST} more` : shown;
1236
1457
  }
1237
- function literalIndexes(text, from) {
1238
- const found = [];
1239
- for (let at = text.indexOf(from);at !== -1; at = text.indexOf(from, at + from.length))
1240
- found.push(at);
1241
- return found;
1458
+ function literal(from) {
1459
+ return new RegExp(from.split(CRLF).map((part) => part.replaceAll(SPECIAL, String.raw`\$&`)).join(String.raw`\r?\n`), "g");
1242
1460
  }
1243
1461
  function firstLineHint(text, from) {
1244
1462
  const first = from.split(`
@@ -1247,15 +1465,22 @@ function firstLineHint(text, from) {
1247
1465
  return "";
1248
1466
  const lines = text.split(`
1249
1467
  `).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
1250
- return lines.length === 0 ? "" : ` (its first line is on ${K("line", lines.length)} ${listLines(lines)})`;
1468
+ return lines.length === 0 ? "" : ` (its first line is on ${G("line", lines.length)} ${listLines(lines)})`;
1251
1469
  }
1252
1470
  function compile(source, { ignoreCase, dotAll } = {}) {
1253
- return new RegExp(source, `gm${ignoreCase === true ? "i" : ""}${dotAll === true ? "s" : ""}`);
1471
+ const flags = `gm${ignoreCase === true ? "i" : ""}${dotAll === true ? "s" : ""}`;
1472
+ try {
1473
+ return new RegExp(source, `${flags}u`);
1474
+ } catch (error) {
1475
+ if (PROPERTY_ESCAPE.test(source))
1476
+ throw error;
1477
+ return new RegExp(source, flags);
1478
+ }
1254
1479
  }
1255
1480
  function escapes(to) {
1256
1481
  return to.replace(ESCAPE2, (whole, letter) => {
1257
1482
  if (letter === undefined)
1258
- return whole;
1483
+ return whole.slice(1);
1259
1484
  return letter === "n" ? `
1260
1485
  ` : "\t";
1261
1486
  });
@@ -1278,13 +1503,11 @@ function applyPairs(original, pairs) {
1278
1503
  let text = original;
1279
1504
  for (const [i, pair] of pairs.entries()) {
1280
1505
  const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
1281
- const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
1282
- `) : pair.from;
1283
1506
  const typed = pair.regex === true ? escapes(pair.to) : pair.to;
1284
1507
  const to = crlf ? typed.replace(CRLF, `\r
1285
1508
  `) : typed;
1286
- const pattern = pair.regex === true ? compile(from, pair) : undefined;
1287
- const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
1509
+ const pattern = pair.regex === true ? compile(pair.from, pair) : literal(pair.from);
1510
+ const indexes = [...text.matchAll(pattern)].map((match) => match.index);
1288
1511
  const found = linesOf(text, indexes);
1289
1512
  matched += indexes.length;
1290
1513
  const expected = pair.count ?? 1;
@@ -1292,12 +1515,16 @@ function applyPairs(original, pairs) {
1292
1515
  const wanted = pair.all === true ? "at least 1" : String(expected);
1293
1516
  let where = ` on lines ${listLines(found)}: add context to --from, or pass --count ${indexes.length} or --all`;
1294
1517
  if (indexes.length === 0)
1295
- where = pattern === undefined ? firstLineHint(text, from) : "";
1296
- problems.push(`${label}matched ${go(indexes.length, "time")}, expected ${wanted}${where}`);
1518
+ where = pair.regex === true ? "" : firstLineHint(text, pair.from);
1519
+ problems.push(`${label}matched ${bo(indexes.length, "time")}, expected ${wanted}${where}`);
1297
1520
  continue;
1298
1521
  }
1299
1522
  lines.push(...found);
1300
- text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
1523
+ text = pair.regex === true ? text.replace(pattern, bracedGroups(to)) : text.replace(pattern, (match) => crlf && match.includes(`
1524
+ `) ? typed.replace(CRLF, match.includes(`\r
1525
+ `) ? `\r
1526
+ ` : `
1527
+ `) : to);
1301
1528
  }
1302
1529
  return { text, lines, problems, matched };
1303
1530
  }
@@ -1339,9 +1566,9 @@ async function filesIn(dir) {
1339
1566
  // src/cli.ts
1340
1567
  var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
1341
1568
 
1342
- A folder given as a file is walked, .gitignore respected and binary files left out; a file in it where nothing matches is skipped and listed, the count checks holding for the others.
1569
+ A folder given as a file is walked, .gitignore respected and binary files left out.
1343
1570
 
1344
- Multi-line text: give no --from, --to or --pairs and pipe SEARCH/REPLACE blocks on stdin from a quoted heredoc, which needs no escaping; a producer silent for 3 s is taken for no heredoc at all, so write a slow one to a file first. The blocks apply in order to the files on the command line, each matching exactly once unless --count or --all says otherwise:
1571
+ Multi-line text: give no --from, --to or --pairs and pipe SEARCH/REPLACE blocks on stdin from a quoted heredoc, which needs no escaping. The blocks apply in order to the files on the command line, each matching exactly once unless --count or --all says otherwise:
1345
1572
 
1346
1573
  sub src/a.php <<'EOF'
1347
1574
  <<<<<<< SEARCH
@@ -1351,15 +1578,15 @@ new lines
1351
1578
  >>>>>>> REPLACE
1352
1579
  EOF
1353
1580
 
1354
- A line naming a file before a block makes it apply to that file alone, so one call edits several files (no file argument needed when every block names one). An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both. When the text holds a marker line itself (a Markdown '=======' underline), open with more characters, '<<<<<<<<<< SEARCH', and divide and close with as many '=' and '>' too.`;
1581
+ A line naming a file before a block makes it apply to that file alone, and an empty REPLACE deletes the SEARCH text.`;
1355
1582
  var EXITS = [[0, "it wrote every replacement"], [1, "one did not match or a file cannot be written (nothing is written)"], [2, "a usage error"]];
1356
1583
  var OPTIONS = {
1357
1584
  from: { type: "string", short: "f", description: "text to find, taken literally" },
1358
1585
  to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
1359
1586
  count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
1360
- all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file" },
1587
+ all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file, or exactly --count" },
1361
1588
  "skip-missing": { type: "boolean", description: "with --all, leave a file where no pair matches alone and list it, instead of failing; the counts still hold for the files that match" },
1362
- regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}, and a \n or \t in it is a newline or a tab" },
1589
+ regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}, and a \\n or \\t in it is a newline or a tab, \\\\ a backslash" },
1363
1590
  "ignore-case": { type: "boolean", short: "i", description: "with --regex, match without regard to case" },
1364
1591
  dotall: { type: "boolean", short: "s", description: "with --regex, let . match a newline too" },
1365
1592
  pairs: { type: "string", short: "p", description: "JSON array of {from, to, count?, all?, regex?, ignoreCase?, dotAll?} applied in order: inline when it starts with [, else a file or - for stdin" },
@@ -1390,14 +1617,14 @@ function pairFrom(item, i, defaults) {
1390
1617
  const { from, to, count, all, regex, ignoreCase, dotAll, ...rest } = item;
1391
1618
  const unknown = Object.keys(rest);
1392
1619
  if (unknown.length > 0)
1393
- fail(`${label}unknown ${K("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
1620
+ fail(`${label}unknown ${G("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
1394
1621
  if (typeof from !== "string" || typeof to !== "string")
1395
1622
  fail(`${label}from and to must both be strings`);
1396
1623
  if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
1397
1624
  fail(`${label}count takes a whole number from 1`);
1398
1625
  if (!isFlag(all) || !isFlag(regex) || !isFlag(ignoreCase) || !isFlag(dotAll))
1399
1626
  fail(`${label}all, regex, ignoreCase and dotAll take true or false`);
1400
- const pair = { from, to, count: count ?? defaults.count ?? 1, all: all ?? defaults.all, regex: regex ?? defaults.regex, ignoreCase: ignoreCase ?? defaults.ignoreCase, dotAll: dotAll ?? defaults.dotAll };
1627
+ const pair = { from, to, count: count ?? defaults.count ?? 1, all: count === undefined ? all ?? defaults.all : false, regex: regex ?? defaults.regex, ignoreCase: ignoreCase ?? defaults.ignoreCase, dotAll: dotAll ?? defaults.dotAll };
1401
1628
  if ((pair.ignoreCase === true || pair.dotAll === true) && pair.regex !== true)
1402
1629
  fail(`${label}ignoreCase and dotAll need regex`);
1403
1630
  checkPattern(pair, label);
@@ -1419,6 +1646,7 @@ async function readPairs(path, defaults) {
1419
1646
  function writable(path) {
1420
1647
  try {
1421
1648
  accessSync(path, constants2.W_OK);
1649
+ accessSync(dirname4(realpathSync3(path)), constants2.W_OK);
1422
1650
  return true;
1423
1651
  } catch {
1424
1652
  return false;
@@ -1448,17 +1676,37 @@ function dedupe(paths) {
1448
1676
  }
1449
1677
  return [...byFile.values()];
1450
1678
  }
1451
- function writeAtomic(path, text) {
1452
- const target = realpathSync3(path);
1453
- const temp = `${target}.sub-${process17.pid}`;
1454
- try {
1455
- writeFileSync2(temp, text);
1456
- chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
1457
- renameSync(temp, target);
1458
- } catch (error) {
1459
- rmSync2(temp, { force: true });
1460
- throw error;
1679
+ function writeAll(writes) {
1680
+ const staged = [];
1681
+ for (const { path, text } of writes) {
1682
+ try {
1683
+ const target = realpathSync3(path);
1684
+ const temp = `${target}.sub-${process18.pid}`;
1685
+ staged.push({ temp, target });
1686
+ writeFileSync2(temp, text);
1687
+ chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
1688
+ } catch (error) {
1689
+ for (const { temp } of staged)
1690
+ rmSync2(temp, { force: true });
1691
+ return { path, problem: error instanceof Error ? error.message : String(error) };
1692
+ }
1461
1693
  }
1694
+ for (const [index, { temp, target }] of staged.entries()) {
1695
+ try {
1696
+ renameSync(temp, target);
1697
+ } catch (error) {
1698
+ for (const left of staged.slice(index))
1699
+ rmSync2(left.temp, { force: true });
1700
+ throw error;
1701
+ }
1702
+ }
1703
+ return;
1704
+ }
1705
+ function nothingWritten(problems, json) {
1706
+ console.error(json ? JSON.stringify({ error: "nothing written", failures: problems }) : `${role("problem", process18.stderr)("sub: nothing written")}
1707
+ ${problems.map(({ path, problem }) => path === "" ? problem : `${path}: ${problem}`).join(`
1708
+ `)}`);
1709
+ return 1;
1462
1710
  }
1463
1711
  var STDIN_SILENCE_MS = 3000;
1464
1712
  async function blocksOnStdin(files) {
@@ -1469,23 +1717,23 @@ async function blocksOnStdin(files) {
1469
1717
  const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
1470
1718
 
1471
1719
  ${USAGE}`;
1472
- if (process17.stdin.isTTY)
1720
+ if (process18.stdin.isTTY)
1473
1721
  fail(hint);
1474
1722
  return new Promise((resolve) => {
1475
1723
  const chunks = [];
1476
1724
  const timer = setTimeout(() => {
1477
1725
  console.error(`error: sub: ${hint}`);
1478
- process17.exit(2);
1726
+ process18.exit(2);
1479
1727
  }, STDIN_SILENCE_MS);
1480
- process17.stdin.on("data", (chunk) => {
1728
+ process18.stdin.on("data", (chunk) => {
1481
1729
  clearTimeout(timer);
1482
1730
  chunks.push(chunk);
1483
1731
  });
1484
- process17.stdin.on("end", () => {
1732
+ process18.stdin.on("end", () => {
1485
1733
  clearTimeout(timer);
1486
1734
  if (chunks.length === 0 && extra.length > 0) {
1487
1735
  console.error(`error: sub: ${hint}`);
1488
- process17.exit(2);
1736
+ process18.exit(2);
1489
1737
  }
1490
1738
  resolve(Buffer.concat(chunks).toString("utf8"));
1491
1739
  });
@@ -1550,13 +1798,11 @@ async function main(argv) {
1550
1798
  return inside;
1551
1799
  }));
1552
1800
  const files = dedupe(given.flat());
1553
- if (values.count !== undefined && values.all === true)
1554
- fail("--count and --all exclude each other");
1555
1801
  if (values["skip-missing"] === true && values.all !== true)
1556
1802
  fail("--skip-missing needs --all");
1557
1803
  if ((values["ignore-case"] === true || values.dotall === true) && values.regex !== true)
1558
1804
  fail("--ignore-case and --dotall need --regex");
1559
- const defaults = { count: values.count === undefined ? undefined : wholeNumber(values.count, "count", 1), all: values.all === true, regex: values.regex === true, ignoreCase: values["ignore-case"] === true, dotAll: values.dotall === true };
1805
+ const defaults = { count: values.count === undefined ? undefined : wholeNumber(values.count, "count", 1), all: values.all === true && values.count === undefined, regex: values.regex === true, ignoreCase: values["ignore-case"] === true, dotAll: values.dotall === true };
1560
1806
  const edits = await plan(values, files, defaults);
1561
1807
  const changes = [];
1562
1808
  const problems = [];
@@ -1586,44 +1832,36 @@ async function main(argv) {
1586
1832
  const json = values.json === true;
1587
1833
  if (skipped.length > 0 && changes.length === 0 && problems.length === 0)
1588
1834
  problems.push({ path: skipped.join(", "), problem: "no match in any file" });
1589
- if (problems.length > 0) {
1590
- if (json)
1591
- console.error(JSON.stringify({ error: "nothing written", failures: problems }));
1592
- else
1593
- console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1594
- ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1595
- `)}`);
1596
- return 1;
1597
- }
1835
+ if (problems.length > 0)
1836
+ return nothingWritten(problems, json);
1598
1837
  try {
1599
1838
  for (const change of changes)
1600
1839
  change.diff = await diffTexts(change.path, change.before, change.after);
1601
1840
  } catch (error) {
1602
- console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1603
- ${error instanceof Error ? error.message : String(error)}`);
1604
- return 1;
1841
+ return nothingWritten([{ path: "", problem: error instanceof Error ? error.message : String(error) }], json);
1605
1842
  }
1606
1843
  const done = [];
1607
- for (const { path, before, after, lines, diff } of changes) {
1844
+ const failed = values["dry-run"] === true ? undefined : writeAll(changes.filter(({ before, after, diff }) => diff !== undefined && after !== before).map(({ path, after }) => ({ path, text: after })));
1845
+ if (failed !== undefined)
1846
+ return nothingWritten([failed], json);
1847
+ for (const { path, lines, diff } of changes) {
1608
1848
  if (diff === undefined)
1609
1849
  continue;
1610
- if (values["dry-run"] !== true && after !== before)
1611
- writeAtomic(path, after);
1612
1850
  if (json) {
1613
1851
  done.push({ path, replacements: lines.length, lines, added: diff.added, removed: diff.removed, ...values.diff === true ? { diff: diff.unified } : {} });
1614
1852
  continue;
1615
1853
  }
1616
1854
  if (values.quiet !== true)
1617
- console.log(`${role("path", process17.stdout)(path)}: ${go(lines.length, "replacement")} on ${K("line", lines.length, { zero: "plural" })} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process17.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process17.stdout)(`-${diff.removed}`)}`);
1855
+ console.log(`${role("path", process18.stdout)(path)}: ${bo(lines.length, "replacement")} on ${G("line", lines.length, { zero: "plural" })} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process18.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process18.stdout)(`-${diff.removed}`)}`);
1618
1856
  if (values.diff === true && diff.unified !== "")
1619
- process17.stdout.write(diff.unified);
1857
+ process18.stdout.write(diff.unified);
1620
1858
  }
1621
1859
  if (json)
1622
1860
  printJson({ dryRun: values["dry-run"] === true, files: done, ...values["skip-missing"] === true ? { skipped } : {} });
1623
1861
  else if (values.quiet !== true && skipped.length > 0)
1624
- console.log(`skipped ${go(skipped.length, "file")} with no match: ${skipped.join(", ")}`);
1862
+ console.log(`skipped ${bo(skipped.length, "file")} with no match: ${skipped.join(", ")}`);
1625
1863
  if (!json && values["dry-run"] === true && values.quiet !== true)
1626
1864
  console.log("dry run: nothing written");
1627
1865
  return 0;
1628
1866
  }
1629
- process17.exitCode = await runMain({ name: "sub", run: main });
1867
+ process18.exitCode = await runMain({ name: "sub", run: main });
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-edit",
3
3
  "type": "module",
4
- "version": "0.11.1",
4
+ "version": "0.11.5",
5
5
  "description": "sub: text replaced in files for Claude Code, written only when every replacement matches as often as expected.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
8
- "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/edit#readme",
8
+ "homepage": "https://github.com/Kayno0o/cli/tree/main/packages/edit#readme",
9
9
  "repository": {
10
10
  "type": "git",
11
- "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
11
+ "url": "git+https://github.com/Kayno0o/cli.git",
12
12
  "directory": "packages/edit"
13
13
  },
14
- "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
14
+ "bugs": "https://github.com/Kayno0o/cli/issues",
15
15
  "keywords": [
16
16
  "claude-code",
17
17
  "cli",
@@ -36,9 +36,9 @@
36
36
  "sub": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "dependencies": {
39
- "@kaynooo/utils": "3.0.0"
39
+ "@kaynooo/utils": "3.1.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@kaynooo/cli-kit": "0.41.0"
42
+ "@kaynooo/cli-kit": "0.46.2"
43
43
  }
44
44
  }