@kaynooo/cli-edit 0.6.0 → 0.7.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.
Files changed (2) hide show
  1. package/dist/cli.js +101 -43
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -4,13 +4,34 @@
4
4
  // src/cli.ts
5
5
  import { accessSync, chmodSync, constants, existsSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
6
6
  import { normalize, resolve } from "path";
7
- import process9 from "process";
7
+ import process11 from "process";
8
8
  // ../kit/src/args.ts
9
- import process5 from "process";
9
+ import process7 from "process";
10
10
  import { parseArgs } from "util";
11
11
 
12
- // ../kit/src/style.ts
12
+ // ../kit/src/format.ts
13
+ import process4 from "process";
14
+
15
+ // ../kit/src/mode.ts
13
16
  import process2 from "process";
17
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
18
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
19
+ function isSet(value) {
20
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
21
+ }
22
+ function outputMode(stream = process2.stdout, env = process2.env) {
23
+ const chosen = env.KIT_MODE;
24
+ if (chosen !== undefined && MODES.has(chosen))
25
+ return chosen;
26
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
27
+ return "agent";
28
+ if (stream.isTTY === true)
29
+ return "terminal";
30
+ return isSet(env.CI) ? "ci" : "pipe";
31
+ }
32
+
33
+ // ../kit/src/style.ts
34
+ import process3 from "process";
14
35
 
15
36
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
16
37
  function x(s) {
@@ -273,21 +294,26 @@ function le(i = {}) {
273
294
  }
274
295
  var t = le();
275
296
 
297
+ // ../kit/src/theme.ts
298
+ 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"]);
299
+ var MAX_FILE_BYTES = 64 * 1024;
300
+ var warned = new Set;
301
+
276
302
  // ../kit/src/style.ts
277
- function takesControlCodes(stream, env = process2.env) {
278
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
303
+ function takesControlCodes(stream, env = process3.env) {
304
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
279
305
  }
280
- function paint(stream, env = process2.env) {
306
+ function paint(stream, env = process3.env) {
281
307
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
282
308
  }
283
- var STATUSES = {
284
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
285
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
286
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
287
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
288
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
309
+ var STATUS_WORDS = {
310
+ passed: ["passed", "success", "succeeded", "ok"],
311
+ failed: ["failed", "failure", "error", "errored"],
312
+ running: ["running", "in_progress", "started", "holding"],
313
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
314
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
289
315
  };
290
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
316
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
291
317
 
292
318
  // ../kit/src/format.ts
293
319
  function upTo(text, separator) {
@@ -295,32 +321,35 @@ function upTo(text, separator) {
295
321
  return end === -1 ? text : text.slice(0, end);
296
322
  }
297
323
  var ESCAPE = String.fromCharCode(27);
324
+ function jsonText(value, replacer, { stream = process4.stdout, env = process4.env } = {}) {
325
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
326
+ }
298
327
  function printJson(value) {
299
- console.log(JSON.stringify(value, undefined, 2));
328
+ console.log(jsonText(value));
300
329
  }
301
330
 
302
331
  // ../kit/src/help.ts
303
- import process3 from "process";
332
+ import process5 from "process";
304
333
  var OPTIONAL = /\[[^\]]+\]/g;
305
334
  var USAGE_PREFIX = /^usage:\s*/i;
306
335
  var FULL_STOP = /\.$/;
307
- function usageLine(usage, colors = paint(process3.stdout)) {
336
+ function usageLine(usage, colors = paint(process5.stdout)) {
308
337
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
309
338
  }
310
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
339
+ function helpText(usage, options, colors = paint(process5.stdout), { examples = [], replaces, exits = [] } = {}) {
311
340
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
312
341
  `);
313
342
  }
314
- function exitRows(exits, colors = paint(process3.stdout)) {
343
+ function exitRows(exits, colors = paint(process5.stdout)) {
315
344
  if (exits.length === 0)
316
345
  return [];
317
346
  const width = Math.max(...exits.map(([code]) => String(code).length));
318
347
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
319
348
  }
320
- function replacesRows(replaces, colors = paint(process3.stdout)) {
321
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
349
+ function replacesRows(replaces, colors = paint(process5.stdout)) {
350
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
322
351
  }
323
- function wantsHelpJson(env = process3.env) {
352
+ function wantsHelpJson(env = process5.env) {
324
353
  return env.KIT_HELP === "json";
325
354
  }
326
355
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -339,12 +368,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
339
368
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
340
369
  };
341
370
  }
342
- function exampleRows(examples, colors = paint(process3.stdout)) {
343
- if (examples.length === 0)
371
+ function exampleRows(examples, colors = paint(process5.stdout)) {
372
+ if (examples.length === 0 || outputMode() === "agent")
344
373
  return [];
345
374
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
346
375
  }
347
- function optionRows(options, colors = paint(process3.stdout)) {
376
+ function optionRows(options, colors = paint(process5.stdout)) {
348
377
  const rows = Object.entries(options).map(([name, option]) => {
349
378
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
350
379
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -376,7 +405,7 @@ function closest(name, names) {
376
405
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
377
406
  }
378
407
  // ../kit/src/input.ts
379
- import process4 from "process";
408
+ import process6 from "process";
380
409
  var WHOLE = /^\d+$/;
381
410
  function wholeNumber(value, name, fallback, min = 1) {
382
411
  if (value === undefined)
@@ -388,7 +417,7 @@ function wholeNumber(value, name, fallback, min = 1) {
388
417
  }
389
418
  async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
390
419
  if (path === "-") {
391
- if (process4.stdin.isTTY)
420
+ if (process6.stdin.isTTY)
392
421
  fail(noStdin);
393
422
  return Bun.stdin.text();
394
423
  }
@@ -447,7 +476,7 @@ var OUTPUT_OPTIONS = {
447
476
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
448
477
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
449
478
  };
450
- function applyOutput(color, plain, env = process5.env) {
479
+ function applyOutput(color, plain, env = process7.env) {
451
480
  const when = plain === true ? "never" : color ?? "auto";
452
481
  if (when === "auto")
453
482
  return;
@@ -624,13 +653,13 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
624
653
  // ../kit/src/cli.ts
625
654
  import { readFileSync, realpathSync } from "fs";
626
655
  import { dirname as dirname2, join as join2 } from "path";
627
- import process7 from "process";
656
+ import process9 from "process";
628
657
 
629
658
  // ../kit/src/usage.ts
630
659
  import { appendFileSync, mkdirSync } from "fs";
631
660
  import { homedir } from "os";
632
661
  import { dirname, isAbsolute, join } from "path";
633
- import process6 from "process";
662
+ import process8 from "process";
634
663
 
635
664
  // ../kit/src/logs.ts
636
665
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -644,14 +673,14 @@ var usageError;
644
673
  function noteUsageError(message) {
645
674
  usageError = message;
646
675
  }
647
- function stateHome(env = process6.env) {
676
+ function stateHome(env = process8.env) {
648
677
  const dir = env.XDG_STATE_HOME;
649
678
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
650
679
  }
651
- function usagePath(env = process6.env) {
680
+ function usagePath(env = process8.env) {
652
681
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
653
682
  }
654
- function usageRecorded(env = process6.env) {
683
+ function usageRecorded(env = process8.env) {
655
684
  const off = env.KAYNOOO_CLI_NO_USAGE;
656
685
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
657
686
  }
@@ -665,7 +694,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
665
694
  usageError = undefined;
666
695
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
667
696
  }
668
- function recordUsage(entry, env = process6.env) {
697
+ function recordUsage(entry, env = process8.env) {
669
698
  if (!usageRecorded(env))
670
699
  return;
671
700
  try {
@@ -683,8 +712,8 @@ var LEVEL_OPTIONS = {
683
712
  };
684
713
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
685
714
  function printError(prefix, message, hint, cause) {
686
- const colors = paint(process7.stderr);
687
- const styled = takesControlCodes(process7.stderr);
715
+ const colors = paint(process9.stderr);
716
+ const styled = takesControlCodes(process9.stderr);
688
717
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
689
718
  const under = (label, text, tint) => text === undefined ? "" : `
690
719
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -777,7 +806,7 @@ function packageVersion(entry = Bun.main) {
777
806
  return "0.0.0";
778
807
  }
779
808
  }
780
- async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
809
+ async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
781
810
  if (argv[0] === COMPLETE)
782
811
  return printCandidates(leafCandidates(run, argv.slice(1)));
783
812
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -967,7 +996,7 @@ function applyPairs(original, pairs) {
967
996
  // src/cli.ts
968
997
  var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
969
998
 
970
- 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:
999
+ 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:
971
1000
 
972
1001
  sub src/a.php <<'EOF'
973
1002
  <<<<<<< SEARCH
@@ -1072,7 +1101,7 @@ function dedupe(paths) {
1072
1101
  }
1073
1102
  function writeAtomic(path, text) {
1074
1103
  const target = realpathSync2(path);
1075
- const temp = `${target}.sub-${process9.pid}`;
1104
+ const temp = `${target}.sub-${process11.pid}`;
1076
1105
  try {
1077
1106
  writeFileSync2(temp, text);
1078
1107
  chmodSync(temp, (statSync(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
@@ -1082,6 +1111,37 @@ function writeAtomic(path, text) {
1082
1111
  throw error;
1083
1112
  }
1084
1113
  }
1114
+ var STDIN_SILENCE_MS = 3000;
1115
+ async function blocksOnStdin(files) {
1116
+ const extra = files.slice(1).filter((path) => !existsSync(path));
1117
+ const strings = extra.length === 0 ? "" : `${extra.map((path) => `no file ${path}`).join(", ")}: with several strings on the command line use --from and --to, as in sub --from old --to new ${files[0]}
1118
+
1119
+ `;
1120
+ const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
1121
+
1122
+ ${USAGE}`;
1123
+ if (process11.stdin.isTTY)
1124
+ fail(hint);
1125
+ return new Promise((resolve) => {
1126
+ const chunks = [];
1127
+ const timer = setTimeout(() => {
1128
+ console.error(`error: sub: ${hint}`);
1129
+ process11.exit(2);
1130
+ }, STDIN_SILENCE_MS);
1131
+ process11.stdin.on("data", (chunk) => {
1132
+ clearTimeout(timer);
1133
+ chunks.push(chunk);
1134
+ });
1135
+ process11.stdin.on("end", () => {
1136
+ clearTimeout(timer);
1137
+ if (chunks.length === 0 && extra.length > 0) {
1138
+ console.error(`error: sub: ${hint}`);
1139
+ process11.exit(2);
1140
+ }
1141
+ resolve(Buffer.concat(chunks).toString("utf8"));
1142
+ });
1143
+ });
1144
+ }
1085
1145
  async function plan(values, files, defaults) {
1086
1146
  const edits = new Map;
1087
1147
  const spellings = new Map(files.map((path) => [canonical(path), path]));
@@ -1107,9 +1167,7 @@ ${USAGE}`);
1107
1167
  edits.set(path, pairs);
1108
1168
  return edits;
1109
1169
  }
1110
- const blocks = parseBlocks(await readInput("-", { noStdin: `give --from and --to, or pipe SEARCH/REPLACE blocks on stdin
1111
-
1112
- ${USAGE}` }));
1170
+ const blocks = parseBlocks(await blocksOnStdin(files));
1113
1171
  if (typeof blocks === "string")
1114
1172
  fail(`blocks: ${blocks}`);
1115
1173
  for (const [i, block] of blocks.entries()) {
@@ -1187,7 +1245,7 @@ ${error instanceof Error ? error.message : String(error)}`);
1187
1245
  if (values.quiet !== true)
1188
1246
  console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, +${diff.added} -${diff.removed}`);
1189
1247
  if (values.diff === true && diff.unified !== "")
1190
- process9.stdout.write(diff.unified);
1248
+ process11.stdout.write(diff.unified);
1191
1249
  }
1192
1250
  if (json)
1193
1251
  printJson({ dryRun: values["dry-run"] === true, files: done });
@@ -1195,4 +1253,4 @@ ${error instanceof Error ? error.message : String(error)}`);
1195
1253
  console.log("dry run: nothing written");
1196
1254
  return 0;
1197
1255
  }
1198
- process9.exitCode = await runMain({ name: "sub", run: main });
1256
+ process11.exitCode = await runMain({ name: "sub", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-edit",
3
3
  "type": "module",
4
- "version": "0.6.0",
4
+ "version": "0.7.0",
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",
@@ -36,6 +36,6 @@
36
36
  "sub": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-kit": "0.21.1"
39
+ "@kaynooo/cli-kit": "0.22.0"
40
40
  }
41
41
  }