@kaynooo/cli-stack 0.5.0 → 0.6.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 +323 -94
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -1,14 +1,35 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process10 from "process";
5
+ import process15 from "process";
6
6
  // ../kit/src/args.ts
7
- import process4 from "process";
7
+ import process9 from "process";
8
8
  import { parseArgs } from "util";
9
9
 
10
- // ../kit/src/style.ts
10
+ // ../kit/src/format.ts
11
+ import process7 from "process";
12
+
13
+ // ../kit/src/mode.ts
11
14
  import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+
31
+ // ../kit/src/style.ts
32
+ import process6 from "process";
12
33
 
13
34
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
14
35
  function x(s) {
@@ -271,33 +292,235 @@ function le(i = {}) {
271
292
  }
272
293
  var t = le();
273
294
 
274
- // ../kit/src/style.ts
275
- var MARKS = {
276
- ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
277
- warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
278
- problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
279
- note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
295
+ // ../kit/src/theme.ts
296
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
297
+ import { homedir as homedir2 } from "os";
298
+ import { join as join3, resolve as resolve2 } from "path";
299
+ import process5 from "process";
300
+
301
+ // ../kit/src/config.ts
302
+ import { existsSync } from "fs";
303
+ import { dirname, join, resolve } from "path";
304
+ import process3 from "process";
305
+ function findUp(names, from = process3.cwd(), stop = () => false) {
306
+ const wanted = typeof names === "string" ? [names] : names;
307
+ for (let dir = resolve(from);; dir = dirname(dir)) {
308
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
309
+ if (found !== undefined)
310
+ return found;
311
+ if (stop(dir) || dirname(dir) === dir)
312
+ return;
313
+ }
314
+ }
315
+
316
+ // ../kit/src/user-config.ts
317
+ import { homedir } from "os";
318
+ import { join as join2 } from "path";
319
+ import process4 from "process";
320
+ function configBase(where = {}) {
321
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
322
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
323
+ }
324
+ function userConfigPath(bin, where = {}) {
325
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
326
+ }
327
+
328
+ // ../kit/src/theme.ts
329
+ var DEFAULT = {
330
+ colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
331
+ glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
332
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
333
+ bins: {}
334
+ };
335
+ var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
336
+ var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
337
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
338
+ var PRESETS = {
339
+ default: {},
340
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
341
+ mono: { colors: MONO, accents: ["bold"] },
342
+ ascii: { glyphs: ASCII }
280
343
  };
281
- function takesControlCodes(stream, env = process2.env) {
282
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
344
+ 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"]);
345
+ var HEX = /^#[0-9a-f]{6}$/i;
346
+ var CONTROL = /\p{Cc}/u;
347
+ var MAX_FILE_BYTES = 64 * 1024;
348
+ var SPACES = /\s+/;
349
+ function isColorSpec(spec) {
350
+ if (typeof spec === "number")
351
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
352
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
353
+ }
354
+ var CUBE = [0, 95, 135, 175, 215, 255];
355
+ function cubeLevel(channel) {
356
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
357
+ }
358
+ function nearest256(hex) {
359
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
360
+ const levels = rgb.map(cubeLevel);
361
+ const cube = levels.map((level) => CUBE[level]);
362
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
363
+ const greyValue = 8 + grey * 10;
364
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
365
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
366
+ }
367
+ function hasTrueColor(env) {
368
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
369
+ }
370
+ function tinted(colors, spec, env = process5.env) {
371
+ if (typeof spec === "number")
372
+ return colors.ansi256(spec);
373
+ return spec.trim().split(SPACES).reduce((chain, token) => {
374
+ if (HEX.test(token))
375
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
376
+ return chain[token] ?? chain;
377
+ }, colors);
378
+ }
379
+ function isRecord(value) {
380
+ return typeof value === "object" && value !== null && !Array.isArray(value);
381
+ }
382
+ function readThemeFile(path, warn) {
383
+ try {
384
+ const stat = statSync(path, { throwIfNoEntry: false });
385
+ if (stat === undefined)
386
+ return;
387
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
388
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
389
+ return;
390
+ }
391
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
392
+ if (isRecord(parsed))
393
+ return parsed;
394
+ warn(`${path} is not a JSON object, theme ignored`);
395
+ } catch (error) {
396
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
397
+ }
398
+ return;
399
+ }
400
+ function applyPreset(theme, name, warn, where) {
401
+ if (name === undefined)
402
+ return;
403
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
404
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
405
+ return;
406
+ }
407
+ const preset = PRESETS[name];
408
+ Object.assign(theme.colors, preset.colors);
409
+ Object.assign(theme.glyphs, preset.glyphs);
410
+ if (preset.accents !== undefined)
411
+ theme.accents = [...preset.accents];
412
+ return name;
413
+ }
414
+ function applyFile(theme, file, where, warn) {
415
+ if (isRecord(file.colors)) {
416
+ for (const [key, value] of Object.entries(file.colors)) {
417
+ if (!Object.hasOwn(DEFAULT.colors, key))
418
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
419
+ else if (!isColorSpec(value))
420
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
421
+ else
422
+ theme.colors[key] = value;
423
+ }
424
+ }
425
+ if (isRecord(file.glyphs)) {
426
+ for (const [key, value] of Object.entries(file.glyphs)) {
427
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
428
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
429
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
430
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
431
+ else
432
+ theme.glyphs[key] = value;
433
+ }
434
+ }
435
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
436
+ theme.accents = [...file.accents];
437
+ else if (file.accents !== undefined)
438
+ warn(`${where}: accents must be a non-empty list of colours`);
439
+ if (isRecord(file.bins)) {
440
+ for (const [bin, value] of Object.entries(file.bins)) {
441
+ if (isColorSpec(value))
442
+ theme.bins[bin] = value;
443
+ else
444
+ warn(`${where}: bin ${bin} has no valid colour`);
445
+ }
446
+ }
447
+ }
448
+ function endsWalk(home) {
449
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
283
450
  }
284
- function paint(stream, env = process2.env) {
451
+ var warned = new Set;
452
+ function warnOnce(message) {
453
+ if (warned.has(message))
454
+ return;
455
+ warned.add(message);
456
+ console.error(`warning: theme ${message}`);
457
+ }
458
+ function isPath(chosen) {
459
+ return chosen.includes("/") || chosen.endsWith(".json");
460
+ }
461
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
462
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
463
+ const sources = [];
464
+ const chosen = env.KIT_THEME ?? "";
465
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
466
+ if (isPath(chosen))
467
+ wanted.push(resolve2(from, chosen));
468
+ const files = [];
469
+ for (const path of wanted) {
470
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
471
+ if (path !== undefined && file !== undefined)
472
+ files.push({ path, file });
473
+ }
474
+ let preset = "default";
475
+ if (chosen !== "" && !isPath(chosen)) {
476
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
477
+ } else {
478
+ const named = files.findLast(({ file }) => file.preset !== undefined);
479
+ if (named !== undefined)
480
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
481
+ }
482
+ for (const { path, file } of files) {
483
+ applyFile(theme, file, path, warn);
484
+ sources.push(path);
485
+ }
486
+ return { theme, sources, preset };
487
+ }
488
+ var current;
489
+ var currentKey = "";
490
+ function activeTheme() {
491
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
492
+ if (current === undefined || key !== currentKey) {
493
+ current = loadTheme();
494
+ currentKey = key;
495
+ }
496
+ return current;
497
+ }
498
+
499
+ // ../kit/src/style.ts
500
+ var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:" };
501
+ function takesControlCodes(stream, env = process6.env) {
502
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
503
+ }
504
+ function paint(stream, env = process6.env) {
285
505
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
286
506
  }
287
- function marked(mark, text, stream, detail, env = process2.env) {
507
+ function marked(mark, text, stream, detail, env = process6.env) {
288
508
  const colors = paint(stream, env);
289
- const { symbol, word, paint: tint } = MARKS[mark];
290
- const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
509
+ let head = MARK_WORDS[mark];
510
+ if (takesControlCodes(stream, env)) {
511
+ const { theme } = activeTheme();
512
+ head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
513
+ }
291
514
  return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
292
515
  }
293
- var STATUSES = {
294
- passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
295
- failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
296
- running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
297
- queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
298
- skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
516
+ var STATUS_WORDS = {
517
+ passed: ["passed", "success", "succeeded", "ok"],
518
+ failed: ["failed", "failure", "error", "errored"],
519
+ running: ["running", "in_progress", "started", "holding"],
520
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
521
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
299
522
  };
300
- var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
523
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
301
524
 
302
525
  // ../kit/src/format.ts
303
526
  function upTo(text, separator) {
@@ -305,32 +528,35 @@ function upTo(text, separator) {
305
528
  return end === -1 ? text : text.slice(0, end);
306
529
  }
307
530
  var ESCAPE = String.fromCharCode(27);
531
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
532
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
533
+ }
308
534
  function printJson(value) {
309
- console.log(JSON.stringify(value, undefined, 2));
535
+ console.log(jsonText(value));
310
536
  }
311
537
 
312
538
  // ../kit/src/help.ts
313
- import process3 from "process";
539
+ import process8 from "process";
314
540
  var OPTIONAL = /\[[^\]]+\]/g;
315
541
  var USAGE_PREFIX = /^usage:\s*/i;
316
542
  var FULL_STOP = /\.$/;
317
- function usageLine(usage, colors = paint(process3.stdout)) {
543
+ function usageLine(usage, colors = paint(process8.stdout)) {
318
544
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
319
545
  }
320
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
546
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
321
547
  return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
322
548
  `);
323
549
  }
324
- function exitRows(exits, colors = paint(process3.stdout)) {
550
+ function exitRows(exits, colors = paint(process8.stdout)) {
325
551
  if (exits.length === 0)
326
552
  return [];
327
553
  const width = Math.max(...exits.map(([code]) => String(code).length));
328
554
  return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
329
555
  }
330
- function replacesRows(replaces, colors = paint(process3.stdout)) {
331
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
556
+ function replacesRows(replaces, colors = paint(process8.stdout)) {
557
+ return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
332
558
  }
333
- function wantsHelpJson(env = process3.env) {
559
+ function wantsHelpJson(env = process8.env) {
334
560
  return env.KIT_HELP === "json";
335
561
  }
336
562
  function description(usage, { examples = [], replaces, exits } = {}, options) {
@@ -349,12 +575,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
349
575
  ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
350
576
  };
351
577
  }
352
- function exampleRows(examples, colors = paint(process3.stdout)) {
353
- if (examples.length === 0)
578
+ function exampleRows(examples, colors = paint(process8.stdout)) {
579
+ if (examples.length === 0 || outputMode() === "agent")
354
580
  return [];
355
581
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
356
582
  }
357
- function optionRows(options, colors = paint(process3.stdout)) {
583
+ function optionRows(options, colors = paint(process8.stdout)) {
358
584
  const rows = Object.entries(options).map(([name, option]) => {
359
585
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
360
586
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -445,7 +671,7 @@ var OUTPUT_OPTIONS = {
445
671
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
446
672
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
447
673
  };
448
- function applyOutput(color, plain, env = process4.env) {
674
+ function applyOutput(color, plain, env = process9.env) {
449
675
  const when = plain === true ? "never" : color ?? "auto";
450
676
  if (when === "auto")
451
677
  return;
@@ -620,15 +846,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
620
846
  var RESET_STYLE = `${ESC}[0m`;
621
847
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
622
848
  // ../kit/src/cli.ts
623
- import { readFileSync, realpathSync } from "fs";
624
- import { dirname as dirname2, join as join2 } from "path";
625
- import process6 from "process";
849
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
850
+ import { dirname as dirname3, join as join5 } from "path";
851
+ import process11 from "process";
626
852
 
627
853
  // ../kit/src/usage.ts
628
854
  import { appendFileSync, mkdirSync } from "fs";
629
- import { homedir } from "os";
630
- import { dirname, isAbsolute, join } from "path";
631
- import process5 from "process";
855
+ import { homedir as homedir3 } from "os";
856
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
857
+ import process10 from "process";
632
858
 
633
859
  // ../kit/src/logs.ts
634
860
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -642,14 +868,14 @@ var usageError;
642
868
  function noteUsageError(message) {
643
869
  usageError = message;
644
870
  }
645
- function stateHome(env = process5.env) {
871
+ function stateHome(env = process10.env) {
646
872
  const dir = env.XDG_STATE_HOME;
647
- return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
873
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
648
874
  }
649
- function usagePath(env = process5.env) {
650
- return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
875
+ function usagePath(env = process10.env) {
876
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
651
877
  }
652
- function usageRecorded(env = process5.env) {
878
+ function usageRecorded(env = process10.env) {
653
879
  const off = env.KAYNOOO_CLI_NO_USAGE;
654
880
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
655
881
  }
@@ -663,12 +889,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
663
889
  usageError = undefined;
664
890
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
665
891
  }
666
- function recordUsage(entry, env = process5.env) {
892
+ function recordUsage(entry, env = process10.env) {
667
893
  if (!usageRecorded(env))
668
894
  return;
669
895
  try {
670
896
  const path = usagePath(env);
671
- mkdirSync(dirname(path), { recursive: true, mode: 448 });
897
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
672
898
  appendFileSync(path, `${JSON.stringify(entry)}
673
899
  `, { mode: 384 });
674
900
  } catch {}
@@ -754,8 +980,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
754
980
  `);
755
981
  }
756
982
  function printError(prefix, message, hint, cause) {
757
- const colors = paint(process6.stderr);
758
- const styled = takesControlCodes(process6.stderr);
983
+ const colors = paint(process11.stderr);
984
+ const styled = takesControlCodes(process11.stderr);
759
985
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
760
986
  const under = (label, text, tint) => text === undefined ? "" : `
761
987
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -774,7 +1000,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
774
1000
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
775
1001
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
776
1002
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
777
- if (error instanceof UsageError)
1003
+ if (error instanceof Exit && error.code === 2)
778
1004
  noteUsageError(error.message);
779
1005
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
780
1006
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
@@ -798,11 +1024,11 @@ async function dispatch(level, typed, { version, redact }) {
798
1024
  }
799
1025
  }
800
1026
  if (name === undefined && level.path.length > 1) {
801
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process6.stderr));
1027
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stderr));
802
1028
  return 2;
803
1029
  }
804
1030
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
805
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process6.stdout));
1031
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process11.stdout));
806
1032
  return 0;
807
1033
  }
808
1034
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -919,17 +1145,17 @@ async function printCandidates(found) {
919
1145
  return 0;
920
1146
  }
921
1147
  function packageVersion(entry = Bun.main) {
922
- for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1148
+ for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
923
1149
  try {
924
- const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1150
+ const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
925
1151
  if (typeof version === "string")
926
1152
  return version;
927
1153
  } catch {}
928
- if (dirname2(dir) === dir)
1154
+ if (dirname3(dir) === dir)
929
1155
  return "0.0.0";
930
1156
  }
931
1157
  }
932
- async function runCli(cli, argv = process6.argv.slice(2)) {
1158
+ async function runCli(cli, argv = process11.argv.slice(2)) {
933
1159
  const version = cli.version ?? packageVersion();
934
1160
  if (argv[0] === COMPLETE)
935
1161
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
@@ -998,14 +1224,14 @@ var {Glob } = globalThis.Bun;
998
1224
  var SESSION_FILES = new Glob("*.json");
999
1225
  var ACCOUNT_DIRS = new Glob("*/sessions");
1000
1226
  // src/commands/audit.ts
1001
- import { homedir as homedir2 } from "os";
1002
- import { resolve as resolve2 } from "path";
1003
- import process9 from "process";
1227
+ import { homedir as homedir4 } from "os";
1228
+ import { resolve as resolve4 } from "path";
1229
+ import process14 from "process";
1004
1230
 
1005
1231
  // src/audit/compose.ts
1006
- import { join as join3 } from "path";
1232
+ import { join as join6 } from "path";
1007
1233
  var dockerCompose = async (root, files) => {
1008
- const result = await compose(["config", "--no-interpolate", "--format", "json"], { flags: ["--project-directory", root, ...files.flatMap((file) => ["-f", join3(root, file)])], env: { COMPOSE_FILE: "" } });
1234
+ const result = await compose(["config", "--no-interpolate", "--format", "json"], { flags: ["--project-directory", root, ...files.flatMap((file) => ["-f", join6(root, file)])], env: { COMPOSE_FILE: "" } });
1009
1235
  if (result.code !== 0)
1010
1236
  throw new Error(composeError(result));
1011
1237
  return JSON.parse(result.stdout);
@@ -1013,8 +1239,8 @@ var dockerCompose = async (root, files) => {
1013
1239
 
1014
1240
  // src/audit/render.ts
1015
1241
  import { basename } from "path";
1016
- import process8 from "process";
1017
- var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process8.stdout)}`;
1242
+ import process13 from "process";
1243
+ var line = (finding) => ` ${marked(finding.level === "error" ? "problem" : "warn", `[${finding.check}] ${finding.message}`, process13.stdout)}`;
1018
1244
  function errorsOf(result) {
1019
1245
  return result.findings.filter((finding) => finding.level === "error");
1020
1246
  }
@@ -1026,7 +1252,7 @@ function render(result, limit = Number.POSITIVE_INFINITY) {
1026
1252
  const errors = errorsOf(result);
1027
1253
  const warnings = result.findings.filter((finding) => finding.level === "warn");
1028
1254
  if (result.findings.length === 0)
1029
- return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process8.stdout);
1255
+ return marked("ok", `${basename(result.root)}: compose ${result.composeFiles.join(", ")} and release.config.ts agree.`, process13.stdout);
1030
1256
  return [
1031
1257
  ...section("Errors", errors, limit),
1032
1258
  ...section("Warnings", warnings, limit),
@@ -1036,12 +1262,12 @@ function render(result, limit = Number.POSITIVE_INFINITY) {
1036
1262
  }
1037
1263
 
1038
1264
  // src/audit/run.ts
1039
- import { existsSync as existsSync3 } from "fs";
1040
- import { join as join6 } from "path";
1265
+ import { existsSync as existsSync5 } from "fs";
1266
+ import { join as join9 } from "path";
1041
1267
 
1042
1268
  // src/audit/checks.ts
1043
- import { existsSync, readFileSync as readFileSync2 } from "fs";
1044
- import { isAbsolute as isAbsolute2, join as join4, relative, resolve } from "path";
1269
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
1270
+ import { isAbsolute as isAbsolute2, join as join7, relative, resolve as resolve3 } from "path";
1045
1271
  var ENV_REF = /(?<!\$)\$(?:\{([A-Z_]\w*)(\s*:?[-?+][^}]*)?\}|([A-Z_]\w*))/gi;
1046
1272
  var REQUIRED_OPERATOR = /^\s*:?\?/;
1047
1273
  var COMMENT_START = /(?:^|\s)#.*$/;
@@ -1057,18 +1283,18 @@ function before(text, separator) {
1057
1283
  }
1058
1284
  var stripDotSlash = (file) => file.replace(LEADING_DOT_SLASH, "");
1059
1285
  function composeLayout(root, config) {
1060
- const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync(join4(root, file)));
1286
+ const composeFiles = (config.deploySyncFiles ?? []).map(stripDotSlash).filter((file) => YAML_FILE.test(file) && existsSync3(join7(root, file)));
1061
1287
  const [base] = composeFiles.toSorted((a, b) => a.length - b.length);
1062
1288
  return { composeFiles, base, overlays: composeFiles.filter((file) => file !== base) };
1063
1289
  }
1064
1290
  function syncFindings(root, config) {
1065
- return (config.deploySyncFiles ?? []).filter((file) => !existsSync(join4(root, stripDotSlash(file)))).map((file) => ({ level: "error", check: "sync", message: `deploySyncFiles entry does not exist: ${file}` }));
1291
+ return (config.deploySyncFiles ?? []).filter((file) => !existsSync3(join7(root, stripDotSlash(file)))).map((file) => ({ level: "error", check: "sync", message: `deploySyncFiles entry does not exist: ${file}` }));
1066
1292
  }
1067
1293
  function buildFindings(root, releases, env, home) {
1068
1294
  const findings = [];
1069
1295
  const missing = (release, key) => {
1070
1296
  const path = release[key];
1071
- if (path !== undefined && path !== "" && !existsSync(join4(root, path)))
1297
+ if (path !== undefined && path !== "" && !existsSync3(join7(root, path)))
1072
1298
  findings.push({ level: "error", check: "build", message: `${release.slug}: ${key} does not exist: ${path}` });
1073
1299
  };
1074
1300
  for (const release of releases) {
@@ -1077,8 +1303,8 @@ function buildFindings(root, releases, env, home) {
1077
1303
  missing(release, "dockerfile");
1078
1304
  for (const secret of release.buildSecrets ?? []) {
1079
1305
  if (secret.src !== undefined && secret.src !== "") {
1080
- const path = secret.src.startsWith("~") ? join4(home, secret.src.slice(1)) : resolve(root, secret.src);
1081
- if (!existsSync(path))
1306
+ const path = secret.src.startsWith("~") ? join7(home, secret.src.slice(1)) : resolve3(root, secret.src);
1307
+ if (!existsSync3(path))
1082
1308
  findings.push({ level: "error", check: "build", message: `${release.slug}: buildSecret "${secret.id}" src does not exist: ${secret.src}` });
1083
1309
  }
1084
1310
  if (secret.env !== undefined && secret.env !== "" && (env[secret.env] ?? "") === "")
@@ -1095,7 +1321,7 @@ function withoutComment(line) {
1095
1321
  }
1096
1322
  function envRefs(root, composeFiles) {
1097
1323
  return composeFiles.flatMap((file) => {
1098
- const text = readFileSync2(join4(root, file), "utf8").split(`
1324
+ const text = readFileSync3(join7(root, file), "utf8").split(`
1099
1325
  `).map(withoutComment).join(`
1100
1326
  `);
1101
1327
  return [...text.matchAll(ENV_REF)].map((match) => ({ name: match[1] ?? match[3], defaulted: match[2] !== undefined && !REQUIRED_OPERATOR.test(match[2]), file }));
@@ -1205,22 +1431,25 @@ function routingFindings(config, gated, model, base, overlays) {
1205
1431
  }
1206
1432
  return findings;
1207
1433
  }
1208
- function relativeSource(root, source) {
1209
- if (source === undefined)
1434
+ var SOURCE_END = /:(?![-+?=])/;
1435
+ var DEFAULTED_VARIABLE = /\$\{[A-Z_]\w*:?-([^}$]*)\}/gi;
1436
+ function relativeSource(root, written) {
1437
+ const source = written?.replaceAll(DEFAULTED_VARIABLE, "$1");
1438
+ if (source === undefined || source.includes("$"))
1210
1439
  return;
1211
1440
  if (source.startsWith("."))
1212
1441
  return source;
1213
- const inRoot = relative(resolve(root), source);
1442
+ const inRoot = relative(resolve3(root), source);
1214
1443
  return isAbsolute2(source) && inRoot !== "" && !inRoot.startsWith("..") ? `./${inRoot}` : undefined;
1215
1444
  }
1216
1445
  function layoutFindings(root, base, model) {
1217
1446
  if (base === undefined)
1218
1447
  return [];
1219
- const header = readFileSync2(join4(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
1448
+ const header = readFileSync3(join7(root, base), "utf8").split(SERVICES_KEY)[0] ?? "";
1220
1449
  const findings = [];
1221
1450
  for (const [name, service] of services(model)) {
1222
1451
  for (const volume of service.volumes ?? []) {
1223
- const source = relativeSource(root, typeof volume === "string" ? before(volume, ":") : volume.source);
1452
+ const source = relativeSource(root, typeof volume === "string" ? volume.split(SOURCE_END)[0] : volume.source);
1224
1453
  if (source !== undefined && !header.includes(stripDotSlash(source)))
1225
1454
  findings.push({ level: "warn", check: "layout", message: `service "${name}" bind-mounts ${source}, absent from the header's expected server layout` });
1226
1455
  }
@@ -1228,14 +1457,14 @@ function layoutFindings(root, base, model) {
1228
1457
  return findings;
1229
1458
  }
1230
1459
  function gitignoreFindings(root) {
1231
- const path = join4(root, ".gitignore");
1232
- const text = existsSync(path) ? readFileSync2(path, "utf8") : "";
1460
+ const path = join7(root, ".gitignore");
1461
+ const text = existsSync3(path) ? readFileSync3(path, "utf8") : "";
1233
1462
  return [".release-logs", ".release-worktrees"].filter((entry) => !text.includes(entry)).map((entry) => ({ level: "warn", check: "gitignore", message: `${entry}/ is not in .gitignore` }));
1234
1463
  }
1235
1464
 
1236
1465
  // src/audit/nuxt.ts
1237
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
1238
- import { basename as basename2, join as join5 } from "path";
1466
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
1467
+ import { basename as basename2, join as join8 } from "path";
1239
1468
  var CAMEL_BOUNDARY = /([a-z0-9])([A-Z])/g;
1240
1469
  var KEY = /([A-Z_]\w*)\s*(?:\?\s*)?:/gi;
1241
1470
  var OPENS_BRACE = /^\s*\{/;
@@ -1278,21 +1507,21 @@ function schemaEnvNames(schema, iface, prefix) {
1278
1507
  }
1279
1508
  function nuxtFindings(root, releases, model) {
1280
1509
  const findings = [];
1281
- const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) => join5(root, dir)).filter((dir) => existsSync2(join5(dir, "nuxt.config.ts")));
1510
+ const dirs = [...new Set(releases.map((release) => release.buildContext).filter((context) => context !== undefined && context !== ""))].map((dir) => join8(root, dir)).filter((dir) => existsSync4(join8(dir, "nuxt.config.ts")));
1282
1511
  for (const dir of dirs) {
1283
- const schemaPath = [join5(dir, ".nuxt/types/schema.d.ts"), join5(dir, ".nuxt/types/runtime-config.d.ts")].find((path) => existsSync2(path));
1512
+ const schemaPath = [join8(dir, ".nuxt/types/schema.d.ts"), join8(dir, ".nuxt/types/runtime-config.d.ts")].find((path) => existsSync4(path));
1284
1513
  let allowed;
1285
1514
  let level = "error";
1286
1515
  let source;
1287
1516
  if (schemaPath !== undefined) {
1288
- const schema = readFileSync3(schemaPath, "utf8");
1517
+ const schema = readFileSync4(schemaPath, "utf8");
1289
1518
  allowed = new Set([
1290
1519
  ...schemaEnvNames(schema, "SharedRuntimeConfig", "NUXT_"),
1291
1520
  ...schemaEnvNames(schema, "SharedPublicRuntimeConfig", "NUXT_PUBLIC_")
1292
1521
  ]);
1293
1522
  source = `${basename2(dir)}/${schemaPath.slice(dir.length + 1)}`;
1294
1523
  } else {
1295
- const config = readFileSync3(join5(dir, "nuxt.config.ts"), "utf8");
1524
+ const config = readFileSync4(join8(dir, "nuxt.config.ts"), "utf8");
1296
1525
  const at = config.indexOf("runtimeConfig:");
1297
1526
  const block = at < 0 ? undefined : braceBody(config, at);
1298
1527
  if (block === undefined)
@@ -1323,7 +1552,7 @@ function installed(specifier, root) {
1323
1552
  }
1324
1553
  }
1325
1554
  async function loadConfig(root) {
1326
- const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(join6(root, CONFIG_FILE)).text())?.[1];
1555
+ const specifier = DEFINE_CONFIG_IMPORT.exec(await Bun.file(join9(root, CONFIG_FILE)).text())?.[1];
1327
1556
  if (specifier !== undefined && !installed(specifier, root)) {
1328
1557
  Bun.plugin({
1329
1558
  name: "release-stand-in",
@@ -1332,7 +1561,7 @@ async function loadConfig(root) {
1332
1561
  }
1333
1562
  });
1334
1563
  }
1335
- const config = (await import(join6(root, CONFIG_FILE))).default;
1564
+ const config = (await import(join9(root, CONFIG_FILE))).default;
1336
1565
  if (config === undefined)
1337
1566
  fail(`${CONFIG_FILE} has no default export`);
1338
1567
  return config;
@@ -1381,7 +1610,7 @@ async function audit(config, options) {
1381
1610
  ];
1382
1611
  return { root, composeFiles, findings };
1383
1612
  }
1384
- var hasConfig = (root) => existsSync3(join6(root, CONFIG_FILE));
1613
+ var hasConfig = (root) => existsSync5(join9(root, CONFIG_FILE));
1385
1614
 
1386
1615
  // src/commands/audit.ts
1387
1616
  var usage2 = `stack audit [dir]
@@ -1398,11 +1627,11 @@ var options = {
1398
1627
  };
1399
1628
  async function audit2(args, overrides = {}) {
1400
1629
  const parsed = parse(args, usage2, options);
1401
- const root = resolve2(parsed.positionals[0] ?? ".");
1630
+ const root = resolve4(parsed.positionals[0] ?? ".");
1402
1631
  if (!hasConfig(root)) {
1403
1632
  fail(`no ${CONFIG_FILE} in ${root}`);
1404
1633
  }
1405
- const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process9.env, home: homedir2(), ...overrides });
1634
+ const result = await audit(await loadConfig(root), { root, loadCompose: dockerCompose, env: process14.env, home: homedir4(), ...overrides });
1406
1635
  if (parsed.values.json === true)
1407
1636
  printJson(result);
1408
1637
  else
@@ -1466,7 +1695,7 @@ async function port(args) {
1466
1695
  }
1467
1696
 
1468
1697
  // src/cli.ts
1469
- process10.exitCode = await runCli({
1698
+ process15.exitCode = await runCli({
1470
1699
  name: "stack",
1471
1700
  about: "a stable port per service name, and a compose release audit",
1472
1701
  replaces: "picking a free host port by hand, and reading compose files against release.config.ts",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-stack",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.6.0",
5
5
  "description": "stack: a stable port per service name, and an audit of a compose release setup against its release.config.ts.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -28,6 +28,6 @@
28
28
  "stack": "$npm_execpath src/cli.ts"
29
29
  },
30
30
  "devDependencies": {
31
- "@kaynooo/cli-kit": "0.21.0"
31
+ "@kaynooo/cli-kit": "0.24.0"
32
32
  }
33
33
  }