@kaynooo/cli-wait 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.
- package/README.md +8 -2
- package/dist/cli.js +515 -178
- package/dist/slot-cli.js +448 -168
- package/package.json +2 -2
package/dist/slot-cli.js
CHANGED
|
@@ -2,19 +2,18 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/slot-cli.ts
|
|
5
|
-
import
|
|
6
|
-
|
|
5
|
+
import process15 from "process";
|
|
7
6
|
// ../kit/src/args.ts
|
|
8
|
-
import
|
|
7
|
+
import process5 from "process";
|
|
9
8
|
import { parseArgs } from "util";
|
|
10
9
|
|
|
11
10
|
// ../kit/src/format.ts
|
|
12
|
-
import
|
|
11
|
+
import process3 from "process";
|
|
13
12
|
|
|
14
13
|
// ../kit/src/style.ts
|
|
15
|
-
import
|
|
14
|
+
import process2 from "process";
|
|
16
15
|
|
|
17
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
16
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
18
17
|
function x(s) {
|
|
19
18
|
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
20
19
|
if (!/^[a-f0-9]+$/.test(r))
|
|
@@ -234,7 +233,7 @@ class e {
|
|
|
234
233
|
}
|
|
235
234
|
}
|
|
236
235
|
|
|
237
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
236
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
238
237
|
var r = 39;
|
|
239
238
|
var o = 49;
|
|
240
239
|
var f2 = "\x1B[";
|
|
@@ -276,10 +275,10 @@ function le(i = {}) {
|
|
|
276
275
|
var t = le();
|
|
277
276
|
|
|
278
277
|
// ../kit/src/style.ts
|
|
279
|
-
function takesControlCodes(stream, env =
|
|
278
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
280
279
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
281
280
|
}
|
|
282
|
-
function paint(stream, env =
|
|
281
|
+
function paint(stream, env = process2.env) {
|
|
283
282
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
284
283
|
}
|
|
285
284
|
var STATUSES = {
|
|
@@ -339,7 +338,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
|
|
|
339
338
|
widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
|
|
340
339
|
}
|
|
341
340
|
const shown = fit === undefined ? cells : narrow(cells, widths, fit);
|
|
342
|
-
const colors = paint(
|
|
341
|
+
const colors = paint(process3.stdout);
|
|
343
342
|
const lines = shown.map((row) => row.map((cell, index) => {
|
|
344
343
|
const width = widths[index] ?? 0;
|
|
345
344
|
const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
|
|
@@ -370,6 +369,63 @@ function printJson(value) {
|
|
|
370
369
|
console.log(JSON.stringify(value, undefined, 2));
|
|
371
370
|
}
|
|
372
371
|
|
|
372
|
+
// ../kit/src/help.ts
|
|
373
|
+
import process4 from "process";
|
|
374
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
375
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
376
|
+
var FULL_STOP = /\.$/;
|
|
377
|
+
function usageLine(usage, colors = paint(process4.stdout)) {
|
|
378
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
379
|
+
}
|
|
380
|
+
function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
381
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
382
|
+
`);
|
|
383
|
+
}
|
|
384
|
+
function exitRows(exits, colors = paint(process4.stdout)) {
|
|
385
|
+
if (exits.length === 0)
|
|
386
|
+
return [];
|
|
387
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
388
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
389
|
+
}
|
|
390
|
+
function replacesRows(replaces, colors = paint(process4.stdout)) {
|
|
391
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
392
|
+
}
|
|
393
|
+
function wantsHelpJson(env = process4.env) {
|
|
394
|
+
return env.KIT_HELP === "json";
|
|
395
|
+
}
|
|
396
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
397
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
398
|
+
`);
|
|
399
|
+
const first = lines[0];
|
|
400
|
+
const colon = first.indexOf(": ");
|
|
401
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
402
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
403
|
+
return {
|
|
404
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
405
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
406
|
+
...replaces === undefined ? {} : { replaces },
|
|
407
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
408
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
409
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
function exampleRows(examples, colors = paint(process4.stdout)) {
|
|
413
|
+
if (examples.length === 0)
|
|
414
|
+
return [];
|
|
415
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
416
|
+
}
|
|
417
|
+
function optionRows(options, colors = paint(process4.stdout)) {
|
|
418
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
419
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
420
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
421
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
422
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
423
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
424
|
+
});
|
|
425
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
426
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
427
|
+
}
|
|
428
|
+
|
|
373
429
|
// ../kit/src/text.ts
|
|
374
430
|
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
375
431
|
function distance(a, b) {
|
|
@@ -389,8 +445,30 @@ function closest(name, names) {
|
|
|
389
445
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
390
446
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
391
447
|
}
|
|
448
|
+
// ../kit/src/input.ts
|
|
449
|
+
var WHOLE = /^\d+$/;
|
|
450
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
451
|
+
if (value === undefined)
|
|
452
|
+
return fallback;
|
|
453
|
+
const number = Number(value);
|
|
454
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
455
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
456
|
+
return number;
|
|
457
|
+
}
|
|
458
|
+
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
459
|
+
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
460
|
+
function duration(value, name, fallback, unit = "s") {
|
|
461
|
+
if (value === undefined)
|
|
462
|
+
return fallback;
|
|
463
|
+
const match = DURATION.exec(value.trim());
|
|
464
|
+
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
465
|
+
if (ms < 1)
|
|
466
|
+
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
467
|
+
return ms;
|
|
468
|
+
}
|
|
392
469
|
|
|
393
470
|
// ../kit/src/args.ts
|
|
471
|
+
var DASHES = /^-+/;
|
|
394
472
|
function jsonOption(holds) {
|
|
395
473
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
396
474
|
}
|
|
@@ -425,61 +503,20 @@ class HelpShown extends Exit {
|
|
|
425
503
|
|
|
426
504
|
class Completing {
|
|
427
505
|
options;
|
|
428
|
-
|
|
506
|
+
positionals;
|
|
507
|
+
candidates;
|
|
508
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
429
509
|
this.options = options;
|
|
510
|
+
this.positionals = positionals;
|
|
511
|
+
this.candidates = candidates;
|
|
430
512
|
}
|
|
431
513
|
}
|
|
432
514
|
var completion = { active: false };
|
|
433
|
-
var OPTIONAL = /\[[^\]]+\]/g;
|
|
434
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
435
|
-
var FULL_STOP = /\.$/;
|
|
436
|
-
var DASHES = /^-+/;
|
|
437
|
-
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
438
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
439
|
-
}
|
|
440
|
-
function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
|
|
441
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
442
|
-
`);
|
|
443
|
-
}
|
|
444
|
-
function replacesRows(replaces, colors = paint(process3.stdout)) {
|
|
445
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
446
|
-
}
|
|
447
|
-
function wantsHelpJson(env = process3.env) {
|
|
448
|
-
return env.KIT_HELP === "json";
|
|
449
|
-
}
|
|
450
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
451
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
452
|
-
`);
|
|
453
|
-
const first = lines[0];
|
|
454
|
-
const colon = first.indexOf(": ");
|
|
455
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
456
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
457
|
-
return {
|
|
458
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
459
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
460
|
-
...replaces === undefined ? {} : { replaces },
|
|
461
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
465
|
-
if (examples.length === 0)
|
|
466
|
-
return [];
|
|
467
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
468
|
-
}
|
|
469
|
-
function optionRows(options, colors = paint(process3.stdout)) {
|
|
470
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
471
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
472
|
-
const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
|
|
473
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
|
|
474
|
-
});
|
|
475
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
476
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
477
|
-
}
|
|
478
515
|
var OUTPUT_OPTIONS = {
|
|
479
516
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
480
517
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
481
518
|
};
|
|
482
|
-
function applyOutput(color, plain, env =
|
|
519
|
+
function applyOutput(color, plain, env = process5.env) {
|
|
483
520
|
const when = plain === true ? "never" : color ?? "auto";
|
|
484
521
|
if (when === "auto")
|
|
485
522
|
return;
|
|
@@ -496,14 +533,13 @@ function applyOutput(color, plain, env = process3.env) {
|
|
|
496
533
|
function parse(args, usage, options, settings = {}) {
|
|
497
534
|
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
498
535
|
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
536
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
499
537
|
if (completion.active)
|
|
500
|
-
throw new Completing(
|
|
501
|
-
const
|
|
502
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
503
|
-
const rest = separator === -1 ? undefined : args.slice(separator + 1);
|
|
538
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
539
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
504
540
|
let parsed;
|
|
505
541
|
try {
|
|
506
|
-
parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
542
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
507
543
|
} catch (error) {
|
|
508
544
|
const message = parseError(error);
|
|
509
545
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -511,12 +547,96 @@ function parse(args, usage, options, settings = {}) {
|
|
|
511
547
|
const values = parsed.values;
|
|
512
548
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
513
549
|
if (values.help === true) {
|
|
514
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage,
|
|
550
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
515
551
|
throw new HelpShown;
|
|
516
552
|
}
|
|
553
|
+
checkChoices(parsed.values, all);
|
|
554
|
+
checkConflicts(parsed.values, all);
|
|
517
555
|
if (settings.positionals !== undefined)
|
|
518
556
|
checkPositionals(parsed.positionals, settings.positionals);
|
|
519
|
-
return { ...parsed, positionals: parsed.positionals, rest };
|
|
557
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
558
|
+
}
|
|
559
|
+
function splitRest(args, passes) {
|
|
560
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
561
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
562
|
+
}
|
|
563
|
+
function splitTrailing(args, options, count) {
|
|
564
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
565
|
+
let seen = 0;
|
|
566
|
+
if (count === 0)
|
|
567
|
+
return { own: args, rest: undefined };
|
|
568
|
+
for (let at = 0;at < args.length; at++) {
|
|
569
|
+
const word = args[at];
|
|
570
|
+
if (word === "--")
|
|
571
|
+
break;
|
|
572
|
+
if (word.startsWith("-")) {
|
|
573
|
+
if (takesValue(word))
|
|
574
|
+
at++;
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
seen++;
|
|
578
|
+
if (seen === count)
|
|
579
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
580
|
+
}
|
|
581
|
+
return { own: args, rest: undefined };
|
|
582
|
+
}
|
|
583
|
+
function listed(options, allowNegative) {
|
|
584
|
+
if (!allowNegative)
|
|
585
|
+
return options;
|
|
586
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
587
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
588
|
+
return [[name, option]];
|
|
589
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
590
|
+
}));
|
|
591
|
+
}
|
|
592
|
+
function withAliases(args, options) {
|
|
593
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
594
|
+
if (named.size === 0)
|
|
595
|
+
return args;
|
|
596
|
+
const separator = args.indexOf("--");
|
|
597
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
598
|
+
return [...own.map((arg) => {
|
|
599
|
+
const at = arg.indexOf("=");
|
|
600
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
601
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
602
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
603
|
+
}
|
|
604
|
+
function withBare(args, options) {
|
|
605
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
606
|
+
if (bare.size === 0)
|
|
607
|
+
return args;
|
|
608
|
+
const separator = args.indexOf("--");
|
|
609
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
610
|
+
return [...own.flatMap((arg, index) => {
|
|
611
|
+
const optional = bare.get(arg);
|
|
612
|
+
const next = own[index + 1];
|
|
613
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
614
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
615
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
616
|
+
}
|
|
617
|
+
function checkConflicts(values, options) {
|
|
618
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
619
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
620
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
621
|
+
if (other !== undefined)
|
|
622
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
function checkChoices(values, options) {
|
|
626
|
+
for (const [name, option] of Object.entries(options)) {
|
|
627
|
+
if (option.choices === undefined)
|
|
628
|
+
continue;
|
|
629
|
+
const given = values[name];
|
|
630
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
631
|
+
if (typeof value === "string")
|
|
632
|
+
oneOf(value, name, option.choices);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function oneOf(value, name, choices) {
|
|
637
|
+
if (!choices.includes(value))
|
|
638
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
639
|
+
return value;
|
|
520
640
|
}
|
|
521
641
|
function checkPositionals(given, names) {
|
|
522
642
|
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
@@ -565,32 +685,13 @@ function nearestOption(message, options, allowNegative) {
|
|
|
565
685
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
566
686
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
567
687
|
}
|
|
568
|
-
var WHOLE = /^\d+$/;
|
|
569
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
570
|
-
if (value === undefined)
|
|
571
|
-
return fallback;
|
|
572
|
-
const number = Number(value);
|
|
573
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
574
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
575
|
-
return number;
|
|
576
|
-
}
|
|
577
|
-
var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
|
|
578
|
-
var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
579
|
-
function duration(value, name, fallback, unit = "s") {
|
|
580
|
-
if (value === undefined)
|
|
581
|
-
return fallback;
|
|
582
|
-
const match = DURATION.exec(value.trim());
|
|
583
|
-
const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
|
|
584
|
-
if (ms < 1)
|
|
585
|
-
badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
|
|
586
|
-
return ms;
|
|
587
|
-
}
|
|
588
688
|
// ../kit/src/progress.ts
|
|
589
|
-
import
|
|
689
|
+
import process7 from "process";
|
|
590
690
|
|
|
591
691
|
// ../kit/src/process.ts
|
|
592
692
|
import { constants } from "os";
|
|
593
|
-
import
|
|
693
|
+
import process6 from "process";
|
|
694
|
+
var KILL_GRACE_MS = 2000;
|
|
594
695
|
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
595
696
|
function exitCodeOf(code, signal) {
|
|
596
697
|
if (code !== null)
|
|
@@ -611,7 +712,7 @@ function holdSignals(cleanup) {
|
|
|
611
712
|
},
|
|
612
713
|
release: () => {
|
|
613
714
|
for (const signal of SIGNALS)
|
|
614
|
-
|
|
715
|
+
process6.off(signal, onSignal);
|
|
615
716
|
}
|
|
616
717
|
};
|
|
617
718
|
function onSignal(signal) {
|
|
@@ -624,12 +725,90 @@ function holdSignals(cleanup) {
|
|
|
624
725
|
return;
|
|
625
726
|
held.release();
|
|
626
727
|
cleanup(signal);
|
|
627
|
-
|
|
728
|
+
process6.kill(process6.pid, signal);
|
|
628
729
|
}
|
|
629
730
|
for (const signal of SIGNALS)
|
|
630
|
-
|
|
731
|
+
process6.on(signal, onSignal);
|
|
631
732
|
return held;
|
|
632
733
|
}
|
|
734
|
+
async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
|
|
735
|
+
const chunks = [];
|
|
736
|
+
const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
|
|
737
|
+
const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
|
|
738
|
+
const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
|
|
739
|
+
const timers = [];
|
|
740
|
+
const killGroup = (killing) => {
|
|
741
|
+
if (state.done)
|
|
742
|
+
return;
|
|
743
|
+
try {
|
|
744
|
+
if (grouped)
|
|
745
|
+
process6.kill(-proc.pid, killing);
|
|
746
|
+
else
|
|
747
|
+
proc.kill(killing);
|
|
748
|
+
} catch {}
|
|
749
|
+
};
|
|
750
|
+
const stop = () => {
|
|
751
|
+
killGroup("SIGTERM");
|
|
752
|
+
timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
|
|
753
|
+
};
|
|
754
|
+
const onAbort = () => stop();
|
|
755
|
+
if (timeoutMs !== undefined) {
|
|
756
|
+
timers.push(setTimeout(() => {
|
|
757
|
+
state.timedOut = true;
|
|
758
|
+
stop();
|
|
759
|
+
}, timeoutMs));
|
|
760
|
+
}
|
|
761
|
+
if (signal?.aborted === true)
|
|
762
|
+
onAbort();
|
|
763
|
+
else
|
|
764
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
765
|
+
onStart?.({ kill: (killing) => killGroup(killing) });
|
|
766
|
+
const drain = async (stream, name) => {
|
|
767
|
+
for await (const data of stream) {
|
|
768
|
+
if (state.failure !== undefined)
|
|
769
|
+
continue;
|
|
770
|
+
try {
|
|
771
|
+
onChunk?.({ stream: name, data });
|
|
772
|
+
} catch (error) {
|
|
773
|
+
state.failure = error;
|
|
774
|
+
stop();
|
|
775
|
+
continue;
|
|
776
|
+
}
|
|
777
|
+
if (state.kept + data.length > maxBytes) {
|
|
778
|
+
state.truncated = true;
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
state.kept += data.length;
|
|
782
|
+
chunks.push({ stream: name, data });
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
try {
|
|
786
|
+
await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
|
|
787
|
+
await proc.exited;
|
|
788
|
+
} finally {
|
|
789
|
+
state.done = true;
|
|
790
|
+
for (const timer of timers)
|
|
791
|
+
clearTimeout(timer);
|
|
792
|
+
signal?.removeEventListener("abort", onAbort);
|
|
793
|
+
}
|
|
794
|
+
if (state.failure !== undefined)
|
|
795
|
+
throw state.failure;
|
|
796
|
+
const joined = () => Buffer.concat(chunks.map(({ data }) => data));
|
|
797
|
+
let output;
|
|
798
|
+
let text;
|
|
799
|
+
return {
|
|
800
|
+
code: exitCodeOf(proc.exitCode, proc.signalCode),
|
|
801
|
+
chunks,
|
|
802
|
+
timedOut: state.timedOut,
|
|
803
|
+
truncated: state.truncated,
|
|
804
|
+
get output() {
|
|
805
|
+
return output ??= joined();
|
|
806
|
+
},
|
|
807
|
+
get text() {
|
|
808
|
+
return text ??= (output ??= joined()).toString();
|
|
809
|
+
}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
633
812
|
|
|
634
813
|
// ../kit/src/progress.ts
|
|
635
814
|
var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
|
|
@@ -642,7 +821,7 @@ var RESET_STYLE = `${ESC}[0m`;
|
|
|
642
821
|
var CTRL_C = 3;
|
|
643
822
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
644
823
|
var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
|
|
645
|
-
function liveRegion(render, stream =
|
|
824
|
+
function liveRegion(render, stream = process7.stderr, env = process7.env) {
|
|
646
825
|
if (!takesControlCodes(stream, env))
|
|
647
826
|
return { redraw: () => {
|
|
648
827
|
return;
|
|
@@ -683,11 +862,11 @@ function liveRegion(render, stream = process5.stderr, env = process5.env) {
|
|
|
683
862
|
clear();
|
|
684
863
|
restore();
|
|
685
864
|
release();
|
|
686
|
-
|
|
865
|
+
process7.off("exit", onExit);
|
|
687
866
|
signals.release();
|
|
688
867
|
}
|
|
689
868
|
timer.unref();
|
|
690
|
-
|
|
869
|
+
process7.on("exit", onExit);
|
|
691
870
|
return {
|
|
692
871
|
redraw: draw,
|
|
693
872
|
print: (text) => {
|
|
@@ -726,14 +905,14 @@ function cutToWidth(line, width) {
|
|
|
726
905
|
return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
|
|
727
906
|
}
|
|
728
907
|
function swallowInput() {
|
|
729
|
-
const input =
|
|
908
|
+
const input = process7.stdin;
|
|
730
909
|
if (!input.isTTY)
|
|
731
910
|
return () => {
|
|
732
911
|
return;
|
|
733
912
|
};
|
|
734
913
|
const onData = (data) => {
|
|
735
914
|
if (data.includes(CTRL_C))
|
|
736
|
-
|
|
915
|
+
process7.kill(process7.pid, "SIGINT");
|
|
737
916
|
};
|
|
738
917
|
input.setRawMode(true);
|
|
739
918
|
input.on("data", onData);
|
|
@@ -749,7 +928,7 @@ function swallowInput() {
|
|
|
749
928
|
};
|
|
750
929
|
}
|
|
751
930
|
function interceptOutput(clear) {
|
|
752
|
-
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [
|
|
931
|
+
const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process7.stdout, "write"], [process7.stderr, "write"]];
|
|
753
932
|
const wrapped = targets.map(([target, name]) => {
|
|
754
933
|
const original = Reflect.get(target, name);
|
|
755
934
|
const wrapper = (...args) => {
|
|
@@ -767,15 +946,93 @@ function interceptOutput(clear) {
|
|
|
767
946
|
};
|
|
768
947
|
}
|
|
769
948
|
// ../kit/src/cli.ts
|
|
770
|
-
import
|
|
949
|
+
import { readFileSync, realpathSync } from "fs";
|
|
950
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
951
|
+
import process10 from "process";
|
|
952
|
+
|
|
953
|
+
// ../kit/src/usage.ts
|
|
954
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
955
|
+
import { homedir as homedir2 } from "os";
|
|
956
|
+
import { dirname, isAbsolute, join as join2 } from "path";
|
|
957
|
+
import process9 from "process";
|
|
958
|
+
|
|
959
|
+
// ../kit/src/logs.ts
|
|
960
|
+
import { lstatSync, openSync } from "fs";
|
|
961
|
+
import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
|
|
962
|
+
import { homedir, tmpdir } from "os";
|
|
963
|
+
import { join } from "path";
|
|
964
|
+
import process8 from "process";
|
|
965
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
966
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
967
|
+
function isPrivateDirectory(path) {
|
|
968
|
+
try {
|
|
969
|
+
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
970
|
+
return info !== undefined && info.isDirectory() && info.uid === (process8.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
971
|
+
} catch {
|
|
972
|
+
return false;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
async function privateLogDirectory(name, env = process8.env) {
|
|
976
|
+
const runtime = env.XDG_RUNTIME_DIR;
|
|
977
|
+
const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
|
|
978
|
+
const path = join(base, name);
|
|
979
|
+
try {
|
|
980
|
+
await mkdir(path, { recursive: true, mode: 448 });
|
|
981
|
+
if (isPrivateDirectory(path))
|
|
982
|
+
return path;
|
|
983
|
+
} catch {}
|
|
984
|
+
return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// ../kit/src/usage.ts
|
|
988
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
989
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
990
|
+
var LONGEST_NAME = 40;
|
|
991
|
+
var usageError;
|
|
992
|
+
function noteUsageError(message) {
|
|
993
|
+
usageError = message;
|
|
994
|
+
}
|
|
995
|
+
function stateHome(env = process9.env) {
|
|
996
|
+
const dir = env.XDG_STATE_HOME;
|
|
997
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join2(homedir2(), ".local", "state");
|
|
998
|
+
}
|
|
999
|
+
function usagePath(env = process9.env) {
|
|
1000
|
+
return join2(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
1001
|
+
}
|
|
1002
|
+
function usageRecorded(env = process9.env) {
|
|
1003
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
1004
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
1005
|
+
}
|
|
1006
|
+
function flagNames(argv) {
|
|
1007
|
+
const end = argv.indexOf("--");
|
|
1008
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
1009
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
1010
|
+
}
|
|
1011
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
1012
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
1013
|
+
usageError = undefined;
|
|
1014
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
1015
|
+
}
|
|
1016
|
+
function recordUsage(entry, env = process9.env) {
|
|
1017
|
+
if (!usageRecorded(env))
|
|
1018
|
+
return;
|
|
1019
|
+
try {
|
|
1020
|
+
const path = usagePath(env);
|
|
1021
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
1022
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
1023
|
+
`, { mode: 384 });
|
|
1024
|
+
} catch {}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// ../kit/src/cli.ts
|
|
771
1028
|
var LEVEL_OPTIONS = {
|
|
772
1029
|
...OUTPUT_OPTIONS,
|
|
773
1030
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
774
1031
|
};
|
|
775
1032
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
776
1033
|
function printError(prefix, message, hint, cause) {
|
|
777
|
-
const colors = paint(
|
|
778
|
-
const styled = takesControlCodes(
|
|
1034
|
+
const colors = paint(process10.stderr);
|
|
1035
|
+
const styled = takesControlCodes(process10.stderr);
|
|
779
1036
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
780
1037
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
781
1038
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -794,90 +1051,116 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
794
1051
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
795
1052
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
796
1053
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
1054
|
+
if (error instanceof UsageError)
|
|
1055
|
+
noteUsageError(error.message);
|
|
797
1056
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
798
1057
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
799
1058
|
return error instanceof Exit ? error.code : 1;
|
|
800
1059
|
}
|
|
801
1060
|
var COMPLETE = "__complete";
|
|
802
1061
|
var FILES = "__files__";
|
|
803
|
-
async function
|
|
1062
|
+
async function completingOf(run) {
|
|
804
1063
|
completion.active = true;
|
|
805
1064
|
try {
|
|
806
1065
|
await run([]);
|
|
807
1066
|
} catch (error) {
|
|
808
1067
|
if (error instanceof Completing)
|
|
809
|
-
return error
|
|
1068
|
+
return error;
|
|
810
1069
|
} finally {
|
|
811
1070
|
completion.active = false;
|
|
812
1071
|
}
|
|
813
|
-
return {};
|
|
1072
|
+
return new Completing({});
|
|
1073
|
+
}
|
|
1074
|
+
function candidateLine(candidate) {
|
|
1075
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
1076
|
+
}
|
|
1077
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
1078
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
1079
|
+
let index = 0;
|
|
1080
|
+
let at = 0;
|
|
1081
|
+
while (at < before.length) {
|
|
1082
|
+
const word = before[at];
|
|
1083
|
+
if (word === "--") {
|
|
1084
|
+
index += before.length - at - 1;
|
|
1085
|
+
break;
|
|
1086
|
+
}
|
|
1087
|
+
if (!word.startsWith("-"))
|
|
1088
|
+
index++;
|
|
1089
|
+
else if (takesValue(word))
|
|
1090
|
+
at++;
|
|
1091
|
+
at++;
|
|
1092
|
+
}
|
|
1093
|
+
const last = positionals.at(-1);
|
|
1094
|
+
if (index < positionals.length)
|
|
1095
|
+
return positionals[index];
|
|
1096
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
814
1097
|
}
|
|
815
1098
|
async function leafCandidates(run, words) {
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
1099
|
+
const completing = await completingOf(run);
|
|
1100
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
1101
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
1102
|
+
const flag = words.at(-2);
|
|
1103
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
1104
|
+
if (option?.type === "string") {
|
|
1105
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
1106
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
1107
|
+
}
|
|
1108
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
1109
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
1110
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
819
1111
|
}
|
|
820
1112
|
async function printCandidates(found) {
|
|
821
1113
|
for (const line of await found)
|
|
822
1114
|
console.log(line);
|
|
823
1115
|
return 0;
|
|
824
1116
|
}
|
|
825
|
-
|
|
1117
|
+
function packageVersion(entry = Bun.main) {
|
|
1118
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
1119
|
+
try {
|
|
1120
|
+
const { version } = JSON.parse(readFileSync(join3(dir, "package.json"), "utf8"));
|
|
1121
|
+
if (typeof version === "string")
|
|
1122
|
+
return version;
|
|
1123
|
+
} catch {}
|
|
1124
|
+
if (dirname2(dir) === dir)
|
|
1125
|
+
return "0.0.0";
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
|
|
826
1129
|
if (argv[0] === COMPLETE)
|
|
827
1130
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
828
1131
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
829
|
-
console.log(version);
|
|
1132
|
+
console.log(version ?? packageVersion());
|
|
830
1133
|
return 0;
|
|
831
1134
|
}
|
|
1135
|
+
let code;
|
|
832
1136
|
try {
|
|
833
|
-
|
|
1137
|
+
code = await run(argv);
|
|
834
1138
|
} catch (error) {
|
|
835
|
-
|
|
1139
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
836
1140
|
}
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
import { homedir, tmpdir } from "os";
|
|
842
|
-
import { join } from "path";
|
|
843
|
-
import process7 from "process";
|
|
844
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
845
|
-
var CLI_FOLDER = "kaynooo-cli";
|
|
846
|
-
function isPrivateDirectory(path) {
|
|
847
|
-
try {
|
|
848
|
-
const info = lstatSync(path, { throwIfNoEntry: false });
|
|
849
|
-
return info !== undefined && info.isDirectory() && info.uid === (process7.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
|
|
850
|
-
} catch {
|
|
851
|
-
return false;
|
|
1141
|
+
if (usage !== false) {
|
|
1142
|
+
try {
|
|
1143
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
1144
|
+
} catch {}
|
|
852
1145
|
}
|
|
853
|
-
|
|
854
|
-
async function privateLogDirectory(name, env = process7.env) {
|
|
855
|
-
const runtime = env.XDG_RUNTIME_DIR;
|
|
856
|
-
const base = runtime === undefined || runtime === "" ? join(homedir(), ".cache", CLI_FOLDER) : join(runtime, CLI_FOLDER);
|
|
857
|
-
const path = join(base, name);
|
|
858
|
-
try {
|
|
859
|
-
await mkdir(path, { recursive: true, mode: 448 });
|
|
860
|
-
if (isPrivateDirectory(path))
|
|
861
|
-
return path;
|
|
862
|
-
} catch {}
|
|
863
|
-
return mkdtemp(join(tmpdir(), `${name.replaceAll("/", "-")}-`));
|
|
1146
|
+
return code;
|
|
864
1147
|
}
|
|
865
1148
|
// ../kit/src/secrets.ts
|
|
866
1149
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
867
1150
|
// ../kit/src/sessions.ts
|
|
868
|
-
import { homedir as
|
|
869
|
-
import { join as
|
|
870
|
-
import
|
|
1151
|
+
import { homedir as homedir3 } from "os";
|
|
1152
|
+
import { join as join4 } from "path";
|
|
1153
|
+
import process11 from "process";
|
|
871
1154
|
var {Glob } = globalThis.Bun;
|
|
872
1155
|
var SESSION_FILES = new Glob("*.json");
|
|
873
1156
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
874
1157
|
async function sessionDirs() {
|
|
875
|
-
const home =
|
|
876
|
-
const dirs = new Set([
|
|
877
|
-
if (
|
|
878
|
-
dirs.add(
|
|
1158
|
+
const home = homedir3();
|
|
1159
|
+
const dirs = new Set([join4(home, ".claude", "sessions")]);
|
|
1160
|
+
if (process11.env.CLAUDE_CONFIG_DIR !== undefined)
|
|
1161
|
+
dirs.add(join4(process11.env.CLAUDE_CONFIG_DIR, "sessions"));
|
|
879
1162
|
try {
|
|
880
|
-
for await (const dir of ACCOUNT_DIRS.scan({ cwd:
|
|
1163
|
+
for await (const dir of ACCOUNT_DIRS.scan({ cwd: join4(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
|
|
881
1164
|
dirs.add(dir);
|
|
882
1165
|
} catch {}
|
|
883
1166
|
return [...dirs];
|
|
@@ -921,7 +1204,7 @@ async function liveSessions() {
|
|
|
921
1204
|
}
|
|
922
1205
|
async function currentSession(sessions) {
|
|
923
1206
|
const byPid = new Map(sessions.map((session) => [session.pid, session]));
|
|
924
|
-
let pid =
|
|
1207
|
+
let pid = process11.ppid;
|
|
925
1208
|
for (let depth = 0;depth < 32 && pid > 1; depth++) {
|
|
926
1209
|
const session = byPid.get(pid);
|
|
927
1210
|
if (session !== undefined)
|
|
@@ -933,24 +1216,21 @@ async function currentSession(sessions) {
|
|
|
933
1216
|
}
|
|
934
1217
|
return;
|
|
935
1218
|
}
|
|
936
|
-
// package.json
|
|
937
|
-
var version = "0.5.0";
|
|
938
|
-
|
|
939
1219
|
// src/slot.ts
|
|
940
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync,
|
|
1220
|
+
import { existsSync, mkdirSync as mkdirSync2, readdirSync, readFileSync as readFileSync2, rmSync } from "fs";
|
|
941
1221
|
import { availableParallelism } from "os";
|
|
942
|
-
import { join as
|
|
943
|
-
import
|
|
1222
|
+
import { join as join5 } from "path";
|
|
1223
|
+
import process14 from "process";
|
|
944
1224
|
|
|
945
1225
|
// src/flock.ts
|
|
946
1226
|
import { closeSync, constants as constants2, ftruncateSync, openSync as openSync2, writeSync } from "fs";
|
|
947
|
-
import
|
|
1227
|
+
import process13 from "process";
|
|
948
1228
|
import { dlopen, FFIType } from "bun:ffi";
|
|
949
1229
|
var LOCK_EX = 2;
|
|
950
1230
|
var LOCK_NB = 4;
|
|
951
1231
|
var flock;
|
|
952
1232
|
function native() {
|
|
953
|
-
flock ??= dlopen(
|
|
1233
|
+
flock ??= dlopen(process13.platform === "darwin" ? "libSystem.B.dylib" : "libc.so.6", { flock: { args: [FFIType.i32, FFIType.i32], returns: FFIType.i32 } }).symbols.flock;
|
|
954
1234
|
return flock;
|
|
955
1235
|
}
|
|
956
1236
|
function tryLock(path) {
|
|
@@ -973,8 +1253,8 @@ slot ls [--json]: lists who holds a slot or a lock and who waits for one (slot l
|
|
|
973
1253
|
The slots and locks are shared by every session, worktree and shell of this user, so heavy jobs (phpunit, playwright, vue-tsc, eslint) queue instead of overloading the machine.
|
|
974
1254
|
A slot or lock is freed the moment its holder ends, SIGKILL included, since the kernel drops it with the process.
|
|
975
1255
|
A slotted command that runs slot again does not wait for a second slot, so wrapping both a script and the commands inside it cannot deadlock.
|
|
976
|
-
A first word \`ls\` always means the listing, so run the ls command as \`slot -n 4 -- ls\` or by its path
|
|
977
|
-
|
|
1256
|
+
A first word \`ls\` always means the listing, so run the ls command as \`slot -n 4 -- ls\` or by its path.`;
|
|
1257
|
+
var RUN_EXITS = [[0, "the command did"], ["its own", "the code of a command that failed"], [2, "it timed out waiting for the slot or a usage error"], [127, "the command cannot be started"]];
|
|
978
1258
|
var LS_USAGE = `slot ls [options]: lists the slots and locks held, with the session, the command and how long ago it started, then who waits for one
|
|
979
1259
|
|
|
980
1260
|
--json prints {slots, busy, entries}, each entry as {state, resource, pid, session, command, cwd, since}.`;
|
|
@@ -994,21 +1274,21 @@ function defaultSlots() {
|
|
|
994
1274
|
return Math.max(1, Math.floor(availableParallelism() / 2));
|
|
995
1275
|
}
|
|
996
1276
|
async function stateDir() {
|
|
997
|
-
const dir =
|
|
1277
|
+
const dir = process14.env.SLOT_DIR ?? await privateLogDirectory("slot");
|
|
998
1278
|
for (const sub of ["slots", "locks", "waiters"])
|
|
999
|
-
|
|
1279
|
+
mkdirSync2(join5(dir, sub), { recursive: true, mode: 448 });
|
|
1000
1280
|
return dir;
|
|
1001
1281
|
}
|
|
1002
1282
|
function readHolder(path) {
|
|
1003
1283
|
try {
|
|
1004
|
-
const holder = JSON.parse(
|
|
1284
|
+
const holder = JSON.parse(readFileSync2(path, "utf8"));
|
|
1005
1285
|
return typeof holder.pid === "number" && typeof holder.command === "string" ? { pid: holder.pid, command: holder.command, cwd: holder.cwd ?? "", since: holder.since ?? 0, ...holder.session === undefined ? {} : { session: holder.session }, ...holder.resource === undefined ? {} : { resource: holder.resource } } : undefined;
|
|
1006
1286
|
} catch {
|
|
1007
1287
|
return;
|
|
1008
1288
|
}
|
|
1009
1289
|
}
|
|
1010
1290
|
function pathOf(dir, kind, name) {
|
|
1011
|
-
return
|
|
1291
|
+
return join5(dir, kind === "slot" ? "slots" : "locks", name);
|
|
1012
1292
|
}
|
|
1013
1293
|
function candidates(dir, { kind, name, count }) {
|
|
1014
1294
|
if (kind === "lock")
|
|
@@ -1036,7 +1316,7 @@ function waitingLine(dir, wanted) {
|
|
|
1036
1316
|
}
|
|
1037
1317
|
async function holderOf(command) {
|
|
1038
1318
|
const session = await currentSession(await liveSessions());
|
|
1039
|
-
return { pid:
|
|
1319
|
+
return { pid: process14.pid, command: command.join(" "), cwd: process14.cwd(), since: Date.now(), ...session === undefined ? {} : { session: session.name } };
|
|
1040
1320
|
}
|
|
1041
1321
|
var waiterCount = 0;
|
|
1042
1322
|
async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
@@ -1062,7 +1342,7 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
|
1062
1342
|
held.release();
|
|
1063
1343
|
const resource = busy.kind === "lock" ? `lock ${busy.name}` : "slot";
|
|
1064
1344
|
if (waiter === undefined) {
|
|
1065
|
-
const path =
|
|
1345
|
+
const path = join5(dir, "waiters", `${process14.pid}-${waiterCount++}`);
|
|
1066
1346
|
const held = tryLock(path);
|
|
1067
1347
|
if (held !== undefined) {
|
|
1068
1348
|
writeHeld(held, JSON.stringify({ ...holder, resource }));
|
|
@@ -1079,14 +1359,14 @@ async function acquire(dir, resources, holder, deadline, timeoutMs) {
|
|
|
1079
1359
|
}
|
|
1080
1360
|
} finally {
|
|
1081
1361
|
if (waiter !== undefined) {
|
|
1082
|
-
|
|
1362
|
+
rmSync(waiter.path, { force: true });
|
|
1083
1363
|
waiter.held.release();
|
|
1084
1364
|
}
|
|
1085
1365
|
}
|
|
1086
1366
|
}
|
|
1087
1367
|
async function runSlotted(args) {
|
|
1088
1368
|
const bare = args[0] !== undefined && !args[0].startsWith("-");
|
|
1089
|
-
const parsed = parse(bare ? [] : args, RUN_USAGE, RUN_OPTIONS, { rest: true, replaces: "flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database", examples: [["slot -- bunx vue-tsc", "wait for a free slot, then type-check"], ["slot --lock booki-test-db -- vendor/bin/phpunit", "one phpunit at a time on the shared test database"], "slot ls"] });
|
|
1369
|
+
const parsed = parse(bare ? [] : args, RUN_USAGE, RUN_OPTIONS, { rest: true, exits: RUN_EXITS, replaces: "flock wrappers, hand-written heavy.sh queues and parallel runs fighting over one test database", examples: [["slot -- bunx vue-tsc", "wait for a free slot, then type-check"], ["slot --lock booki-test-db -- vendor/bin/phpunit", "one phpunit at a time on the shared test database"], "slot ls"] });
|
|
1090
1370
|
const { values } = parsed;
|
|
1091
1371
|
const rest = bare ? args : parsed.rest;
|
|
1092
1372
|
if (rest === undefined || rest.length === 0)
|
|
@@ -1103,7 +1383,7 @@ ${RUN_USAGE}`);
|
|
|
1103
1383
|
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1104
1384
|
const timeoutMs = duration(values.timeout, "timeout", Number.POSITIVE_INFINITY);
|
|
1105
1385
|
const deadline = Date.now() + timeoutMs;
|
|
1106
|
-
const holding = new Set((
|
|
1386
|
+
const holding = new Set((process14.env[HOLDING] ?? "").split(",").filter((token) => token !== ""));
|
|
1107
1387
|
const wanted = [...locks.filter((name) => !holding.has(`lock:${name}`)).map((name) => ({ kind: "lock", name, count })), ...values["no-slot"] === true || holding.has("slot") ? [] : [{ kind: "slot", name: "", count }]];
|
|
1108
1388
|
const signals = holdSignals(() => {
|
|
1109
1389
|
return;
|
|
@@ -1118,7 +1398,7 @@ ${RUN_USAGE}`);
|
|
|
1118
1398
|
const tokens = new Set([...holding, ...locks.map((name) => `lock:${name}`), ...wanted.some((resource) => resource.kind === "slot") ? ["slot"] : []]);
|
|
1119
1399
|
let child;
|
|
1120
1400
|
try {
|
|
1121
|
-
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...
|
|
1401
|
+
child = Bun.spawn(rest, { stdio: ["inherit", "inherit", "inherit"], env: { ...process14.env, [HOLDING]: [...tokens].join(",") } });
|
|
1122
1402
|
} catch (error) {
|
|
1123
1403
|
fail(`cannot run ${rest[0]}: ${error instanceof Error ? error.message : String(error)}`, 127);
|
|
1124
1404
|
}
|
|
@@ -1132,14 +1412,14 @@ ${RUN_USAGE}`);
|
|
|
1132
1412
|
}
|
|
1133
1413
|
}
|
|
1134
1414
|
function scan(dir, state, kind) {
|
|
1135
|
-
const folder =
|
|
1415
|
+
const folder = join5(dir, kind);
|
|
1136
1416
|
const entries = [];
|
|
1137
1417
|
for (const name of existsSync(folder) ? readdirSync(folder) : []) {
|
|
1138
|
-
const path =
|
|
1418
|
+
const path = join5(folder, name);
|
|
1139
1419
|
const probe = tryLock(path);
|
|
1140
1420
|
if (probe !== undefined) {
|
|
1141
1421
|
if (kind === "waiters")
|
|
1142
|
-
|
|
1422
|
+
rmSync(path, { force: true });
|
|
1143
1423
|
probe.release();
|
|
1144
1424
|
continue;
|
|
1145
1425
|
}
|
|
@@ -1150,7 +1430,7 @@ function scan(dir, state, kind) {
|
|
|
1150
1430
|
return entries;
|
|
1151
1431
|
}
|
|
1152
1432
|
async function listSlots(args) {
|
|
1153
|
-
const { values } = parse(args, LS_USAGE, LS_OPTIONS, { examples: ["slot ls", "slot ls --json"] });
|
|
1433
|
+
const { values } = parse(args, LS_USAGE, LS_OPTIONS, { exits: [[0, "it listed them"], [2, "a usage error"]], examples: ["slot ls", "slot ls --json"] });
|
|
1154
1434
|
const count = wholeNumber(values.slots, "slots", defaultSlots());
|
|
1155
1435
|
const dir = await stateDir();
|
|
1156
1436
|
const holding = [...scan(dir, "holding", "slots"), ...scan(dir, "holding", "locks")].sort((a, b) => a.since - b.since);
|
|
@@ -1168,4 +1448,4 @@ async function listSlots(args) {
|
|
|
1168
1448
|
}
|
|
1169
1449
|
|
|
1170
1450
|
// src/slot-cli.ts
|
|
1171
|
-
|
|
1451
|
+
process15.exitCode = await runMain({ name: "slot", run: async (args) => args[0] === "ls" ? listSlots(args.slice(1)) : runSlotted(args) });
|