@kaynooo/cli-wait 0.12.7 → 0.13.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/dist/cli.js CHANGED
@@ -1,2262 +1,24 @@
1
1
  #!/bin/sh
2
2
  // @bun 2>/dev/null; exec bun --no-env-file --config=/dev/null "$0" "$@"
3
- var __esm = (fn, res, err) => () => {
4
- if (fn)
5
- try {
6
- res = fn(fn = 0);
7
- } catch (e) {
8
- err = [e];
9
- }
10
- if (err)
11
- throw err[0];
12
- return res;
13
- };
14
-
15
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rkhsft4a.js
16
- function Ao(t, e, r = "...") {
17
- let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
18
- if (t.length <= e)
19
- return t;
20
- let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
21
- if (o && !Y.test(t[c.length] ?? " "))
22
- c = c.replace(Nt, "") || c;
23
- if (o)
24
- c = c.trimEnd();
25
- return s ? (c + n).slice(0, l) : c + n;
26
- }
27
- var N, Nt, Y, be, W;
28
- var init_chunk_rkhsft4a = __esm(() => {
29
- N = new Map;
30
- Nt = /\s+\S*$/;
31
- Y = /\s/;
32
- be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
33
- W = new Map;
34
- });
35
-
36
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/text.js
37
- var init_text = __esm(() => {
38
- init_chunk_rkhsft4a();
39
- });
40
-
41
- // ../kit/src/mode.ts
42
- import process2 from "process";
43
- function isSet(value) {
44
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
45
- }
46
- function outputMode(stream = process2.stdout, env = process2.env) {
47
- const chosen = env.KIT_MODE;
48
- if (chosen !== undefined && MODES.has(chosen))
49
- return chosen;
50
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
51
- return "agent";
52
- if (stream.isTTY === true)
53
- return "terminal";
54
- return isSet(env.CI) ? "ci" : "pipe";
55
- }
56
- var MODES, AGENT_VARIABLES;
57
- var init_mode = __esm(() => {
58
- MODES = new Set(["terminal", "ci", "agent", "pipe"]);
59
- AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
60
- });
61
-
62
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
63
- function b(r) {
64
- let e = r.startsWith("#") ? r.slice(1) : r;
65
- if (!G2.test(e))
66
- return [0, 0, 0];
67
- if (e.length === 3 || e.length === 4)
68
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
69
- if (e.length !== 6 && e.length !== 8)
70
- throw Error(`Invalid hex color length: ${e.length}`);
71
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
72
- }
73
- function C(r, e = globalThis.process?.env ?? {}) {
74
- if (e.FORCE_COLOR !== undefined)
75
- return h.has(e.FORCE_COLOR);
76
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
77
- return false;
78
- return r?.isTTY === true;
79
- }
80
- function f(r, e = []) {
81
- let l = "", n = "";
82
- for (let t = 0, i = e.length;t < i; t++)
83
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
84
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
85
- return new Proxy(c, { get(t, i) {
86
- let a = B[i];
87
- if (Array.isArray(a)) {
88
- let s = g.get(i);
89
- if (s === undefined)
90
- s = f(r, [...e, a]), g.set(i, s);
91
- return s;
92
- }
93
- if (typeof a === "function")
94
- return (...s) => {
95
- let y = `${i}:${s.join(",")}`, u = g.get(y);
96
- if (u === undefined) {
97
- if (g.size >= 64)
98
- g.clear();
99
- u = f(r, [...e, a(...s)]), g.set(y, u);
100
- }
101
- return u;
102
- };
103
- throw Error(`Unknown style: ${String(i)}`);
104
- } });
105
- }
106
- function Fe(r = {}) {
107
- return f(r);
108
- }
109
- var G2, B, h, o;
110
- var init_chunk_x450vn3m = __esm(() => {
111
- G2 = /^[a-f0-9]+$/i;
112
- B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
113
- let [l, n, c] = b(r);
114
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
115
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
116
- h = new Set(["", "1", "2", "3", "true"]);
117
- o = Fe();
118
- });
119
-
120
- // ../../node_modules/.bun/@kaynooo+utils@3.1.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/tools/colors.js
121
- var init_colors = __esm(() => {
122
- init_chunk_x450vn3m();
123
- });
124
-
125
- // ../kit/src/config.ts
126
- import { existsSync } from "fs";
127
- import { dirname, join, resolve } from "path";
128
- import process3 from "process";
129
- function findUp(names, from = process3.cwd(), stop = () => false) {
130
- const wanted = typeof names === "string" ? [names] : names;
131
- for (let dir = resolve(from);; dir = dirname(dir)) {
132
- const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
133
- if (found !== undefined)
134
- return found;
135
- if (stop(dir) || dirname(dir) === dir)
136
- return;
137
- }
138
- }
139
- var init_config = __esm(() => {
140
- init_args();
141
- });
142
-
143
- // ../kit/src/user-config.ts
144
- import { existsSync as existsSync2, readFileSync } from "fs";
145
- import { homedir } from "os";
146
- import { isAbsolute, join as join2 } from "path";
147
- import process4 from "process";
148
- function xdgFolder(value, fallback) {
149
- return value !== undefined && isAbsolute(value) ? value : fallback;
150
- }
151
- function configBase(where = {}) {
152
- const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
153
- return xdgFolder(xdg, join2(where.home ?? homedir(), ".config"));
154
- }
155
- function userConfigPath(bin, where = {}) {
156
- return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
157
- }
158
- function userConfigReadPath(bin, legacy = [], where = {}) {
159
- const current = userConfigPath(bin, where);
160
- if (existsSync2(current))
161
- return current;
162
- const base = configBase(where);
163
- return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
164
- }
165
- function readUserConfig(bin, where = {}, legacy = []) {
166
- const path = userConfigReadPath(bin, legacy, where);
167
- if (!existsSync2(path))
168
- return {};
169
- try {
170
- const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
171
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
172
- } catch {
173
- return {};
174
- }
175
- }
176
- function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
177
- const value = readUserConfig(bin, where, legacy)[key];
178
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
179
- }
180
- var init_user_config = () => {};
181
-
182
- // ../kit/src/theme.ts
183
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
184
- import { homedir as homedir2 } from "os";
185
- import { join as join3, resolve as resolve2 } from "path";
186
- import process5 from "process";
187
- function isColorSpec(spec) {
188
- if (typeof spec === "number")
189
- return Number.isInteger(spec) && spec >= 0 && spec <= 255;
190
- return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
191
- }
192
- function cubeLevel(channel) {
193
- return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
194
- }
195
- function nearest256(hex) {
196
- const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
197
- const levels = rgb.map(cubeLevel);
198
- const cube = levels.map((level) => CUBE[level]);
199
- const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
200
- const greyValue = 8 + grey * 10;
201
- const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
202
- return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
203
- }
204
- function hasTrueColor(env) {
205
- return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
206
- }
207
- function tinted(colors, spec, env = process5.env) {
208
- if (typeof spec === "number")
209
- return colors.ansi256(spec);
210
- return spec.trim().split(SPACES).reduce((chain, token) => {
211
- if (HEX.test(token))
212
- return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
213
- return chain[token] ?? chain;
214
- }, colors);
215
- }
216
- function isRecord(value) {
217
- return typeof value === "object" && value !== null && !Array.isArray(value);
218
- }
219
- function readThemeFile(path, warn) {
220
- try {
221
- const stat = statSync(path, { throwIfNoEntry: false });
222
- if (stat === undefined)
223
- return;
224
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
225
- warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
226
- return;
227
- }
228
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
229
- if (isRecord(parsed))
230
- return parsed;
231
- warn(`${path} is not a JSON object, theme ignored`);
232
- } catch (error) {
233
- warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
234
- }
235
- return;
236
- }
237
- function applyPreset(theme, name, warn, where) {
238
- if (name === undefined)
239
- return;
240
- if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
241
- warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
242
- return;
243
- }
244
- const preset = PRESETS[name];
245
- Object.assign(theme.colors, preset.colors);
246
- Object.assign(theme.glyphs, preset.glyphs);
247
- if (preset.accents !== undefined)
248
- theme.accents = [...preset.accents];
249
- if (Object.hasOwn(preset, "gradient"))
250
- theme.gradient = preset.gradient;
251
- return name;
252
- }
253
- function applyFile(theme, file, where, warn) {
254
- if (isRecord(file.colors)) {
255
- for (const [key, value] of Object.entries(file.colors)) {
256
- if (!Object.hasOwn(DEFAULT.colors, key))
257
- warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
258
- else if (!isColorSpec(value))
259
- warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
260
- else
261
- theme.colors[key] = value;
262
- }
263
- }
264
- if (isRecord(file.glyphs)) {
265
- for (const [key, value] of Object.entries(file.glyphs)) {
266
- if (!Object.hasOwn(DEFAULT.glyphs, key))
267
- warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
268
- else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
269
- warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
270
- else
271
- theme.glyphs[key] = value;
272
- }
273
- }
274
- if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
275
- theme.accents = [...file.accents];
276
- else if (file.accents !== undefined)
277
- warn(`${where}: accents must be a non-empty list of colours`);
278
- if (file.gradient === null)
279
- theme.gradient = undefined;
280
- else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
281
- theme.gradient = [file.gradient[0], file.gradient[1]];
282
- else if (file.gradient !== undefined)
283
- warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
284
- if (isRecord(file.bins)) {
285
- for (const [bin, value] of Object.entries(file.bins)) {
286
- if (isColorSpec(value))
287
- theme.bins[bin] = value;
288
- else
289
- warn(`${where}: bin ${bin} has no valid colour`);
290
- }
291
- }
292
- }
293
- function endsWalk(home) {
294
- return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
295
- }
296
- function warnOnce(message) {
297
- if (warned.has(message))
298
- return;
299
- warned.add(message);
300
- console.error(`warning: theme ${message}`);
301
- }
302
- function isPath(chosen) {
303
- return chosen.includes("/") || chosen.endsWith(".json");
304
- }
305
- function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
306
- const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
307
- const sources = [];
308
- const chosen = env.KIT_THEME ?? "";
309
- const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
310
- if (isPath(chosen))
311
- wanted.push(resolve2(from, chosen));
312
- const files = [];
313
- for (const path of wanted) {
314
- const file = path === undefined ? undefined : readThemeFile(path, warn);
315
- if (path !== undefined && file !== undefined)
316
- files.push({ path, file });
317
- }
318
- let preset = "default";
319
- if (chosen !== "" && !isPath(chosen)) {
320
- preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
321
- } else {
322
- const named = files.findLast(({ file }) => file.preset !== undefined);
323
- if (named !== undefined)
324
- preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
325
- }
326
- for (const { path, file } of files) {
327
- applyFile(theme, file, path, warn);
328
- sources.push(path);
329
- }
330
- return { theme, sources, preset };
331
- }
332
- function activeTheme() {
333
- const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
334
- if (current === undefined || key !== currentKey) {
335
- current = loadTheme();
336
- currentKey = key;
337
- }
338
- return current;
339
- }
340
- var ENDS, DEFAULT, BRIGHT, MONO, ASCII, PRESETS, STYLES, HEX, CONTROL, MAX_FILE_BYTES, SPACES, CUBE, warned, current, currentKey = "";
341
- var init_theme = __esm(() => {
342
- init_config();
343
- init_user_config();
344
- ENDS = new Map;
345
- DEFAULT = {
346
- colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", plan: "magenta", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
347
- glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", plan: "\u25C7", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D", open: "\u2022", leaf: "\xB7", guide: "\u2502" },
348
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
349
- bins: {},
350
- gradient: ["#c084fc", "#67e8f9"]
351
- };
352
- BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
353
- MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
354
- ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
355
- PRESETS = {
356
- default: {},
357
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
358
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
359
- ascii: { glyphs: ASCII }
360
- };
361
- 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"]);
362
- HEX = /^#[0-9a-f]{6}$/i;
363
- CONTROL = /\p{Cc}/u;
364
- MAX_FILE_BYTES = 64 * 1024;
365
- SPACES = /\s+/;
366
- CUBE = [0, 95, 135, 175, 215, 255];
367
- warned = new Set;
368
- });
369
-
370
- // ../kit/src/style.ts
371
- import process6 from "process";
372
- function takesControlCodes(stream, env = process6.env) {
373
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
374
- }
375
- function paint(stream, env = process6.env) {
376
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
377
- }
378
- function marked(mark, text, stream, detail, env = process6.env) {
379
- const colors = paint(stream, env);
380
- let head = MARK_WORDS[mark];
381
- if (takesControlCodes(stream, env)) {
382
- const { theme } = activeTheme();
383
- head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
384
- }
385
- return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
386
- }
387
- function problem(text, detail) {
388
- console.error(marked("problem", text, process6.stderr, detail));
389
- }
390
- function statusOf(word) {
391
- return STATUS_OF.get(word.toLowerCase());
392
- }
393
- function badge(word, stream, env = process6.env) {
394
- const status = statusOf(word);
395
- if (status === undefined || !takesControlCodes(stream, env))
396
- return word;
397
- const { theme } = activeTheme();
398
- return tinted(paint(stream, env), theme.colors[status], env)(`${theme.glyphs[status]} ${word}`);
399
- }
400
- var MARK_WORDS, STATUS_WORDS, STATUS_OF;
401
- var init_style = __esm(() => {
402
- init_colors();
403
- init_mode();
404
- init_theme();
405
- MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
406
- STATUS_WORDS = {
407
- passed: ["passed", "success", "succeeded", "ok"],
408
- failed: ["failed", "failure", "error", "errored"],
409
- running: ["running", "in_progress", "started", "holding"],
410
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
411
- skipped: ["skipped", "cancelled", "canceled", "manual"]
412
- };
413
- STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
414
- });
415
-
416
- // ../kit/src/format.ts
417
- import process7 from "process";
418
- function formatSeconds(total) {
419
- let rest = Math.max(0, Math.round(total));
420
- const amounts = UNITS.map(([unit, size]) => {
421
- const amount = Math.floor(rest / size);
422
- rest -= amount * size;
423
- return `${amount}${unit}`;
424
- });
425
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
426
- if (first === -1)
427
- return "0s";
428
- const next = amounts[first + 1];
429
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
430
- }
431
- function formatDuration(ms) {
432
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
433
- }
434
- function formatElapsed(ms) {
435
- return formatSeconds(Math.floor(Math.max(0, ms) / 1000));
436
- }
437
- function upTo(text, separator) {
438
- const end = text.indexOf(separator);
439
- return end === -1 ? text : text.slice(0, end);
440
- }
441
- function formatAge(date, now = Date.now()) {
442
- const at = typeof date === "number" ? date : Date.parse(date);
443
- if (Number.isNaN(at))
444
- return "-";
445
- const seconds = (now - at) / 1000;
446
- return seconds < 60 ? "just now" : `${upTo(formatSeconds(seconds), " ")} ago`;
447
- }
448
- function truncate(text, width) {
449
- return Ao(text, width, { suffix: "\u2026", includeSuffix: true });
450
- }
451
- function textWidth(text) {
452
- return Bun.stringWidth(text);
453
- }
454
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
455
- const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
456
- if (outputMode(stream, env) === "agent")
457
- return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
458
- `);
459
- const widths = [];
460
- for (const row of cells) {
461
- for (const [index, cell] of row.entries())
462
- widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
463
- }
464
- const shown = fit === undefined ? cells : narrow(cells, widths, fit);
465
- const colors = paint(stream);
466
- const lines = shown.map((row) => row.map((cell, index) => {
467
- const width = widths[index] ?? 0;
468
- const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
469
- if (align[index] === "right")
470
- return `${gap}${cell}`;
471
- return index === row.length - 1 ? cell : `${cell}${gap}`;
472
- }).join(" ").trimEnd());
473
- const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
474
- return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
475
- `);
476
- }
477
- function narrow(rows, widths, limit) {
478
- const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
479
- const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
480
- const floor = 8;
481
- while (used() > limit) {
482
- let widest = -1;
483
- for (const [index, width] of widths.entries()) {
484
- if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
485
- widest = index;
486
- }
487
- if (widest === -1)
488
- break;
489
- widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
490
- }
491
- return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
492
- }
493
- function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
494
- return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
495
- }
496
- function printJson(value) {
497
- console.log(jsonText(value));
498
- }
499
- var UNITS, LINE_BREAKS, ESCAPE;
500
- var init_format = __esm(() => {
501
- init_text();
502
- init_mode();
503
- init_style();
504
- UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
505
- LINE_BREAKS = /\s*\n\s*/g;
506
- ESCAPE = String.fromCharCode(27);
507
- });
508
-
509
- // ../kit/src/help.ts
510
- import process8 from "process";
511
- function usageLine(usage, colors = paint(process8.stdout), { summary: withSummary = true } = {}) {
512
- const lines = usage.replace(USAGE_PREFIX, "").split(`
513
- `);
514
- const blank = lines.indexOf("");
515
- const synopses = blank === -1 ? lines : lines.slice(0, blank);
516
- const details = blank === -1 ? [] : lines.slice(blank + 1);
517
- const colon = synopses[0].indexOf(": ");
518
- const inline = synopses[0].slice(colon + 2);
519
- const summary = colon === -1 ? details.shift() : `${inline.charAt(0).toUpperCase()}${inline.slice(1)}`;
520
- if (colon !== -1)
521
- synopses[0] = synopses[0].slice(0, colon);
522
- const head = `${colors.bold("Usage:")} ${synopses.map((line) => line.replaceAll(OPTIONAL, (part) => colors.dim(part))).join(`
523
- `)}`;
524
- const lead = summary === undefined || !withSummary ? [] : ["", colors.bold(prose(summary, colors))];
525
- const rest = details.length === 0 ? [] : ["", ...details.map((line) => prose(line, colors))];
526
- return [head, ...lead, ...rest].join(`
527
- `);
528
- }
529
- function prose(line, colors) {
530
- if (colors.cyan("x") === "x")
531
- return line;
532
- return line.replaceAll(PROSE_MARKS, (match, code, flag) => code === undefined ? colors.cyan(flag ?? match) : colors.bold(code));
533
- }
534
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [], bin } = {}) {
535
- const { summary } = description(usage);
536
- const head = bin === undefined ? [usageLine(usage, colors)] : [`${colors.bold(bin.name)} ${colors.dim(bin.version())}${summary === "" ? "" : ` ${summary}`}`, "", usageLine(usage, colors, { summary: false })];
537
- return [...head, "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
538
- `);
539
- }
540
- function exitRows(exits, colors = paint(process8.stdout)) {
541
- if (exits.length === 0)
542
- return [];
543
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
544
- }
545
- function wantsHelpJson(env = process8.env) {
546
- return env.KIT_HELP === "json";
547
- }
548
- function description(usage, { examples = [], replaces, exits } = {}, options) {
549
- const lines = usage.replace(USAGE_PREFIX, "").split(`
550
- `);
551
- const first = lines[0];
552
- const colon = first.indexOf(": ");
553
- const prose = lines[lines.indexOf("") + 1] ?? "";
554
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
555
- return {
556
- synopsis: colon === -1 ? first : first.slice(0, colon),
557
- summary: colon === -1 ? fallback : first.slice(colon + 2),
558
- ...replaces === undefined ? {} : { replaces },
559
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
560
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
561
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
562
- };
563
- }
564
- function exampleRows(examples, colors = paint(process8.stdout)) {
565
- if (examples.length === 0 || outputMode() === "agent")
566
- return [];
567
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
568
- }
569
- function optionRows(options, colors = paint(process8.stdout)) {
570
- const rows = Object.entries(options).map(([name, option]) => {
571
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
572
- const choices = option.choices?.join("|");
573
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
574
- const named = inline ? `<${choices}>` : "<value>";
575
- const placeholder = option.optional === undefined ? named : `[${named}]`;
576
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
577
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
578
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
579
- });
580
- const width = Math.max(0, ...rows.map((row) => row.width));
581
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
582
- }
583
- var OPTIONAL, USAGE_PREFIX, FULL_STOP, PROSE_MARKS, MAX_INLINE_CHOICES = 24;
584
- var init_help = __esm(() => {
585
- init_mode();
586
- init_style();
587
- OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
588
- USAGE_PREFIX = /^usage:\s*/i;
589
- FULL_STOP = /\.$/;
590
- PROSE_MARKS = /`([^`\n]+)`|(?<![\w-])(--[a-z][\w-]*|-[a-z](?![\w-]))/gi;
591
- });
592
-
593
- // ../kit/src/text.ts
594
- function distance(a, b) {
595
- const left = [...a];
596
- const right = [...b];
597
- let before = [];
598
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
599
- for (const [i, x] of left.entries()) {
600
- const current = [i + 1];
601
- for (const [j, y] of right.entries()) {
602
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
603
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
604
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
605
- current.push(cost);
606
- }
607
- before = previous;
608
- previous = current;
609
- }
610
- return previous[right.length] ?? 0;
611
- }
612
- function closest(name, names) {
613
- const started = names.find((known) => known.startsWith(name));
614
- if (started !== undefined)
615
- return started;
616
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
617
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
618
- }
619
- var init_text2 = () => {};
620
-
621
- // ../kit/src/input.ts
622
- function wholeNumber(value, name, fallback, min = 1) {
623
- if (value === undefined)
624
- return fallback;
625
- const number = Number(value);
626
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
627
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
628
- return number;
629
- }
630
- function durationMs(text, unit) {
631
- if (BARE_DURATION.test(text))
632
- return Number(text) * UNIT_MS[unit];
633
- if (!DURATION.test(text))
634
- return 0;
635
- let ms = 0;
636
- for (const [, amount, part] of text.matchAll(DURATION_PART))
637
- ms += Number(amount) * UNIT_MS[part];
638
- return ms;
639
- }
640
- function duration(value, name, fallback, unit = "s") {
641
- if (value === undefined)
642
- return fallback;
643
- const ms = durationMs(value.trim(), unit);
644
- if (ms < 1)
645
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
646
- return ms;
647
- }
648
- var WHOLE, BARE_DURATION, DURATION, DURATION_PART, UNIT_MS;
649
- var init_input = __esm(() => {
650
- init_args();
651
- WHOLE = /^\d+$/;
652
- BARE_DURATION = /^\d+(?:\.\d+)?$/;
653
- DURATION = /^(?:\d+(?:\.\d+)?(?:ms|min|[smhd]))+$/;
654
- DURATION_PART = /(\d+(?:\.\d+)?)(ms|min|[smhd])/g;
655
- UNIT_MS = { ms: 1, s: 1000, m: 60000, min: 60000, h: 3600000, d: 86400000 };
656
- });
657
-
658
- // ../kit/src/args.ts
659
- import process9 from "process";
660
- import { parseArgs } from "util";
661
- function jsonOption(holds) {
662
- return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
663
- }
664
- function fail(message, code = 2, hint) {
665
- throw new Exit(message, code, hint);
666
- }
667
- function badUsage(message) {
668
- throw new UsageError(message);
669
- }
670
-
671
- class Completing {
672
- options;
673
- positionals;
674
- candidates;
675
- constructor(options, positionals = [], candidates = {}) {
676
- this.options = options;
677
- this.positionals = positionals;
678
- this.candidates = candidates;
679
- }
680
- }
681
- function applyOutput(color, plain, env = process9.env) {
682
- const when = plain === true ? "never" : color ?? "auto";
683
- if (when === "auto")
684
- return;
685
- if (when !== "always" && when !== "never")
686
- badUsage(`--color takes auto, always or never, not ${when}`);
687
- if (when === "always") {
688
- env.FORCE_COLOR = "1";
689
- delete env.NO_COLOR;
690
- } else {
691
- env.NO_COLOR = "1";
692
- delete env.FORCE_COLOR;
693
- }
694
- }
695
- function parse(args, usage, options, settings = {}) {
696
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
697
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
698
- const listing = listed(all, settings.allowNegative === true);
699
- if (completion.active)
700
- throw new Completing(listing, settings.positionals, settings.candidates);
701
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
702
- let parsed;
703
- try {
704
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
705
- } catch (error) {
706
- const message = parseError(error);
707
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
708
- }
709
- const values = parsed.values;
710
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
711
- if (values.help === true) {
712
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, { ...settings, bin: heading.bin }));
713
- throw new HelpShown;
714
- }
715
- checkChoices(parsed.values, all);
716
- checkConflicts(parsed.values, all);
717
- if (settings.positionals !== undefined)
718
- checkPositionals(parsed.positionals, settings.positionals);
719
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
720
- }
721
- function splitRest(args, passes) {
722
- const separator = passes ? args.indexOf("--") : -1;
723
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
724
- }
725
- function splitTrailing(args, options, count) {
726
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
727
- let seen = 0;
728
- if (count === 0)
729
- return { own: args, rest: undefined };
730
- for (let at = 0;at < args.length; at++) {
731
- const word = args[at];
732
- if (word === "--")
733
- break;
734
- if (word.startsWith("-")) {
735
- if (takesValue(word))
736
- at++;
737
- continue;
738
- }
739
- seen++;
740
- if (seen === count)
741
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
742
- }
743
- return { own: args, rest: undefined };
744
- }
745
- function listed(options, allowNegative) {
746
- if (!allowNegative)
747
- return options;
748
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
749
- if (option.type !== "boolean" || option.negative === undefined)
750
- return [[name, option]];
751
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
752
- }));
753
- }
754
- function withAliases(args, options) {
755
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
756
- if (named.size === 0)
757
- return args;
758
- const separator = args.indexOf("--");
759
- const own = separator === -1 ? args : args.slice(0, separator);
760
- return [...own.map((arg) => {
761
- const at = arg.indexOf("=");
762
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
763
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
764
- }), ...separator === -1 ? [] : args.slice(separator)];
765
- }
766
- function withBare(args, options) {
767
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
768
- if (bare.size === 0)
769
- return args;
770
- const separator = args.indexOf("--");
771
- const own = separator === -1 ? args : args.slice(0, separator);
772
- return [...own.flatMap((arg, index) => {
773
- const optional = bare.get(arg);
774
- const next = own[index + 1];
775
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
776
- return optional === undefined || value ? [arg] : [arg, optional.bare];
777
- }), ...separator === -1 ? [] : args.slice(separator)];
778
- }
779
- function checkConflicts(values, options) {
780
- const given = (name) => values[name] !== undefined && values[name] !== false;
781
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
782
- const other = given(name) ? conflicts.find(given) : undefined;
783
- if (other !== undefined)
784
- badUsage(`--${name} cannot be used with --${other}`);
785
- }
786
- }
787
- function checkChoices(values, options) {
788
- for (const [name, option] of Object.entries(options)) {
789
- if (option.choices === undefined)
790
- continue;
791
- const given = values[name];
792
- for (const value of Array.isArray(given) ? given : [given]) {
793
- if (typeof value === "string")
794
- oneOf(value, name, option.choices);
795
- }
796
- }
797
- }
798
- function oneOf(value, name, choices) {
799
- if (!choices.includes(value))
800
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
801
- return value;
802
- }
803
- function checkPositionals(given, names) {
804
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
805
- const required = names.filter((name) => !name.startsWith("[")).length;
806
- if (given.length < required)
807
- badUsage(`missing ${names[given.length]}`);
808
- if (!variadic && given.length > names.length)
809
- badUsage(`unexpected argument ${given[names.length]}`);
810
- }
811
- function joinDashValues(args, options) {
812
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
813
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
814
- const joined = [];
815
- for (let i = 0;i < args.length; i++) {
816
- const arg = args[i] ?? "";
817
- if (arg === "--")
818
- return [...joined, ...args.slice(i)];
819
- const name = longOf.get(arg);
820
- const next = args[i + 1];
821
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
822
- joined.push(`--${name}=${next}`);
823
- i++;
824
- } else {
825
- joined.push(arg);
826
- }
827
- }
828
- return joined;
829
- }
830
- function parseError(error) {
831
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
832
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
833
- }
834
- function nearestOption(message, options, allowNegative) {
835
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
836
- if (typed === undefined)
837
- return;
838
- const word = typed.replace(DASHES, "");
839
- if (word.length < 2 && !typed.startsWith("--"))
840
- return;
841
- const known = Object.entries(options).flatMap(([name, option]) => [
842
- ...option.short === undefined ? [] : [`-${option.short}`],
843
- `--${name}`,
844
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
845
- ]);
846
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
847
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
848
- }
849
- var DASHES, EXIT, Exit, UsageError, HelpShown, completion, heading, OUTPUT_OPTIONS, UNKNOWN_OPTION;
850
- var init_args = __esm(() => {
851
- init_format();
852
- init_help();
853
- init_text2();
854
- init_help();
855
- init_input();
856
- DASHES = /^-+/;
857
- EXIT = Symbol.for("@kaynooo/cli-kit/Exit");
858
- Exit = class Exit extends Error {
859
- code;
860
- hint;
861
- [EXIT] = true;
862
- constructor(message, code, hint) {
863
- super(message);
864
- this.code = code;
865
- this.hint = hint;
866
- }
867
- static [Symbol.hasInstance](value) {
868
- if (this !== Exit)
869
- return Function.prototype[Symbol.hasInstance].call(this, value);
870
- return typeof value === "object" && value !== null && value[EXIT] === true;
871
- }
872
- };
873
- UsageError = class UsageError extends Exit {
874
- constructor(message, hint) {
875
- super(message, 2, hint);
876
- }
877
- };
878
- HelpShown = class HelpShown extends Exit {
879
- constructor() {
880
- super("help shown", 0);
881
- }
882
- };
883
- completion = { active: false };
884
- heading = { bin: undefined };
885
- OUTPUT_OPTIONS = {
886
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
887
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
888
- };
889
- UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
890
- });
891
-
892
- // ../kit/src/folders.ts
893
- var SKIPPED_FOLDERS;
894
- var init_folders = __esm(() => {
895
- init_user_config();
896
- SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
897
- });
898
-
899
- // src/cli.ts
900
- import { existsSync as existsSync6 } from "fs";
901
- import process21 from "process";
902
-
903
- // ../kit/src/index.ts
904
- init_args();
905
-
906
- // ../kit/src/argv.ts
907
- import { readFileSync as readFileSync3, realpathSync } from "fs";
908
- import { resolve as resolve3 } from "path";
909
- import process10 from "process";
910
- function commandLine() {
911
- try {
912
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
913
- } catch {
914
- return;
915
- }
916
- }
917
- function realPath(word) {
918
- try {
919
- return realpathSync(resolve3(word));
920
- } catch {
921
- return;
922
- }
923
- }
924
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
925
- const target = script === undefined ? undefined : realPath(script) ?? script;
926
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
927
- const after = at === -1 ? [] : cmdline.slice(at + 1);
928
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
929
- }
930
- // ../kit/src/chart.ts
931
- init_format();
932
- init_mode();
933
- init_style();
934
- init_theme();
935
- // ../kit/src/ci.ts
936
- init_args();
937
- init_format();
938
-
939
- // ../kit/src/progress.ts
940
- init_format();
941
- import process12 from "process";
942
-
943
- // ../kit/src/process.ts
944
- import { readFileSync as readFileSync4 } from "fs";
945
- import { constants } from "os";
946
- import process11 from "process";
947
- var KILL_GRACE_MS = 2000;
948
- var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
949
- var GROUP_SIGNALS = new Set(["SIGINT", "SIGHUP"]);
950
- function exitCodeOf(code, signal) {
951
- if (code !== null)
952
- return code;
953
- if (typeof signal === "number")
954
- return 128 + signal;
955
- return signal === null ? 129 : 128 + constants.signals[signal];
956
- }
957
- function groupsOf(pid) {
958
- try {
959
- const stat = readFileSync4(`/proc/${pid}/stat`, "utf8");
960
- const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
961
- return { group: Number(fields[2]), foreground: Number(fields[5]) };
962
- } catch {
963
- return;
964
- }
965
- }
966
- function heardTheTerminal(child) {
967
- if (child.pid === undefined)
968
- return false;
969
- const own = groupsOf("self");
970
- return own !== undefined && own.group === own.foreground && groupsOf(child.pid)?.group === own.group;
971
- }
972
- function holdSignals(cleanup) {
973
- let received;
974
- let child;
975
- const held = {
976
- get signal() {
977
- return received;
978
- },
979
- forward: (to) => {
980
- child = to;
981
- },
982
- release: () => {
983
- for (const signal of SIGNALS)
984
- process11.off(signal, onSignal);
985
- }
986
- };
987
- function onSignal(signal) {
988
- received = signal;
989
- if (child !== undefined) {
990
- if (!GROUP_SIGNALS.has(signal) || !heardTheTerminal(child))
991
- child.kill(signal);
992
- return;
993
- }
994
- if (cleanup === undefined)
995
- return;
996
- held.release();
997
- cleanup(signal);
998
- process11.kill(process11.pid, signal);
999
- }
1000
- for (const signal of SIGNALS)
1001
- process11.on(signal, onSignal);
1002
- return held;
1003
- }
1004
- async function runCommand(argv, { cwd, env, stdin = "ignore", input, timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
1005
- const chunks = [];
1006
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
1007
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin: input === undefined ? stdin : new TextEncoder().encode(input), stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
1008
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
1009
- const timers = [];
1010
- const killGroup = (killing) => {
1011
- if (state.done)
1012
- return;
1013
- try {
1014
- if (grouped)
1015
- process11.kill(-proc.pid, killing);
1016
- else
1017
- proc.kill(killing);
1018
- } catch {}
1019
- };
1020
- const stop = () => {
1021
- killGroup("SIGTERM");
1022
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
1023
- };
1024
- const onAbort = () => stop();
1025
- if (timeoutMs !== undefined) {
1026
- timers.push(setTimeout(() => {
1027
- state.timedOut = true;
1028
- stop();
1029
- }, timeoutMs));
1030
- }
1031
- if (signal?.aborted === true)
1032
- onAbort();
1033
- else
1034
- signal?.addEventListener("abort", onAbort, { once: true });
1035
- onStart?.({ kill: (killing) => killGroup(killing) });
1036
- const drain = async (stream, name) => {
1037
- for await (const data of stream) {
1038
- if (state.failure !== undefined)
1039
- continue;
1040
- try {
1041
- onChunk?.({ stream: name, data });
1042
- } catch (error) {
1043
- state.failure = error;
1044
- stop();
1045
- continue;
1046
- }
1047
- if (state.truncated)
1048
- continue;
1049
- let kept = data;
1050
- if (state.kept + data.length > maxBytes) {
1051
- let cut = maxBytes - state.kept;
1052
- while (cut > 0 && ((data[cut] ?? 0) & 192) === 128)
1053
- cut--;
1054
- kept = data.subarray(0, cut);
1055
- state.truncated = true;
1056
- }
1057
- state.kept += kept.length;
1058
- if (kept.length > 0)
1059
- chunks.push({ stream: name, data: kept });
1060
- }
1061
- };
1062
- try {
1063
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
1064
- await proc.exited;
1065
- } finally {
1066
- state.done = true;
1067
- for (const timer of timers)
1068
- clearTimeout(timer);
1069
- signal?.removeEventListener("abort", onAbort);
1070
- }
1071
- if (state.failure !== undefined)
1072
- throw state.failure;
1073
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
1074
- let output;
1075
- let text;
1076
- let stdout;
1077
- return {
1078
- code: exitCodeOf(proc.exitCode, proc.signalCode),
1079
- chunks,
1080
- timedOut: state.timedOut,
1081
- truncated: state.truncated,
1082
- get output() {
1083
- return output ??= joined();
1084
- },
1085
- get text() {
1086
- return text ??= (output ??= joined()).toString();
1087
- },
1088
- get stdout() {
1089
- return stdout ??= Buffer.concat(chunks.filter((chunk) => chunk.stream === "stdout").map((chunk) => chunk.data)).toString();
1090
- }
1091
- };
1092
- }
1093
-
1094
- // ../kit/src/progress.ts
1095
- init_style();
1096
- init_theme();
1097
- var FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
1098
- var FRAME_MS = 200;
1099
- var CLEAR_BELOW = "\r\x1B[J";
1100
- var ESC = String.fromCharCode(27);
1101
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
1102
- var RESET_STYLE = `${ESC}[0m`;
1103
- var CTRL_C = 3;
1104
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
1105
- var CONSOLE_METHODS = ["log", "info", "warn", "error", "debug", "dir", "dirxml", "table", "trace", "group", "groupCollapsed", "count", "timeEnd", "timeLog", "assert"];
1106
- function liveRegion(render, stream = process12.stderr, env = process12.env) {
1107
- if (!takesControlCodes(stream, env))
1108
- return { redraw: () => {
1109
- return;
1110
- }, print: (text) => void stream.write(`${text}
1111
- `), stop: () => {
1112
- return;
1113
- }, pause: () => () => {
1114
- return;
1115
- } };
1116
- const write = stream.write.bind(stream);
1117
- let frame = 0;
1118
- let drawn = false;
1119
- let paused = false;
1120
- let stopped = false;
1121
- const columns = () => {
1122
- const now = stream.getWindowSize?.()[0] ?? stream.columns;
1123
- return now === undefined || now === 0 ? 80 : now;
1124
- };
1125
- const clear = () => {
1126
- if (drawn)
1127
- write(CLEAR_BELOW);
1128
- drawn = false;
1129
- };
1130
- const draw = () => {
1131
- if (paused)
1132
- return;
1133
- const width = columns() - 1;
1134
- const height = stream.rows === undefined || stream.rows === 0 ? 24 : stream.rows;
1135
- const lines = render(FRAMES[frame++ % FRAMES.length]).slice(0, Math.max(1, height - 1)).map((line) => cutToWidth(line, width));
1136
- if (lines.length === 0) {
1137
- clear();
1138
- return;
1139
- }
1140
- write(`${CLEAR_BELOW}${lines.join(`
1141
- `)}${lines.length > 1 ? `\x1B[${lines.length - 1}A` : ""}\r`);
1142
- drawn = true;
1143
- };
1144
- let timer = setInterval(draw, FRAME_MS);
1145
- stream.on?.("resize", draw);
1146
- let restore = interceptOutput(clear);
1147
- let release = swallowInput();
1148
- const onExit = () => {
1149
- clear();
1150
- release();
1151
- };
1152
- const signals = holdSignals(stop);
1153
- function stop() {
1154
- stopped = true;
1155
- clearInterval(timer);
1156
- stream.off?.("resize", draw);
1157
- clear();
1158
- restore();
1159
- release();
1160
- process12.off("exit", onExit);
1161
- signals.release();
1162
- }
1163
- function pause() {
1164
- if (paused || stopped)
1165
- return () => {
1166
- return;
1167
- };
1168
- paused = true;
1169
- clearInterval(timer);
1170
- stream.off?.("resize", draw);
1171
- clear();
1172
- restore();
1173
- release();
1174
- return () => {
1175
- if (!paused || stopped)
1176
- return;
1177
- paused = false;
1178
- timer = setInterval(draw, FRAME_MS);
1179
- timer.unref();
1180
- stream.on?.("resize", draw);
1181
- restore = interceptOutput(clear);
1182
- release = swallowInput();
1183
- draw();
1184
- };
1185
- }
1186
- timer.unref();
1187
- process12.on("exit", onExit);
1188
- return {
1189
- redraw: draw,
1190
- print: (text) => {
1191
- clear();
1192
- write(`${text}
1193
- `);
1194
- draw();
1195
- },
1196
- stop,
1197
- pause
1198
- };
1199
- }
1200
- function cutToWidth(line, width) {
1201
- if (Bun.stringWidth(line) <= width)
1202
- return line;
1203
- let room = width;
1204
- let kept = "";
1205
- let index = 0;
1206
- let linked = false;
1207
- while (index < line.length) {
1208
- ESCAPE_CODE.lastIndex = index;
1209
- const escape = ESCAPE_CODE.exec(line);
1210
- if (escape !== null) {
1211
- kept += escape[0];
1212
- linked ||= escape[0].startsWith(`${ESC}]`);
1213
- index = ESCAPE_CODE.lastIndex;
1214
- continue;
1215
- }
1216
- const char = String.fromCodePoint(line.codePointAt(index));
1217
- const columns = Bun.stringWidth(char);
1218
- if (columns > room)
1219
- break;
1220
- kept += char;
1221
- room -= columns;
1222
- index += char.length;
1223
- }
1224
- return `${kept}${RESET_STYLE}${linked ? CLOSE_LINK : ""}`;
1225
- }
1226
- function swallowInput() {
1227
- const input = process12.stdin;
1228
- if (!input.isTTY)
1229
- return () => {
1230
- return;
1231
- };
1232
- const onData = (data) => {
1233
- if (data.includes(CTRL_C))
1234
- process12.kill(process12.pid, "SIGINT");
1235
- };
1236
- input.setRawMode(true);
1237
- input.on("data", onData);
1238
- input.resume();
1239
- let released = false;
1240
- return () => {
1241
- if (released)
1242
- return;
1243
- released = true;
1244
- input.off("data", onData);
1245
- input.pause();
1246
- input.setRawMode(false);
1247
- };
1248
- }
1249
- function interceptOutput(clear) {
1250
- const targets = [...CONSOLE_METHODS.map((name) => [console, name]), [process12.stdout, "write"], [process12.stderr, "write"]];
1251
- const wrapped = targets.map(([target, name]) => {
1252
- const original = Reflect.get(target, name);
1253
- const wrapper = (...args) => {
1254
- clear();
1255
- return original.apply(target, args);
1256
- };
1257
- Reflect.set(target, name, wrapper);
1258
- return { target, name, original, wrapper };
1259
- });
1260
- return () => {
1261
- for (const { target, name, original, wrapper } of wrapped) {
1262
- if (Reflect.get(target, name) === wrapper)
1263
- Reflect.set(target, name, original);
1264
- }
1265
- };
1266
- }
1267
-
1268
- // ../kit/src/ci.ts
1269
- init_style();
1270
-
1271
- // ../kit/src/tool.ts
1272
- init_format();
1273
- // ../kit/src/cli.ts
1274
- init_args();
1275
- import { readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1276
- import { dirname as dirname3, join as join6 } from "path";
1277
- import process17 from "process";
1278
-
1279
- // ../kit/src/askpass.ts
1280
- import process13 from "process";
1281
- var SOCKET_VARIABLE = "KAYNOOO_ASKPASS_SOCKET";
1282
- async function askpassClient(argv) {
1283
- const socketPath = process13.env[SOCKET_VARIABLE];
1284
- if (socketPath === undefined)
1285
- return;
1286
- const request = { prompt: argv[0] ?? "", ...process13.env.SSH_ASKPASS_PROMPT === "none" ? { notice: true } : {} };
1287
- const { promise, resolve } = Promise.withResolvers();
1288
- let received = "";
1289
- try {
1290
- await Bun.connect({
1291
- unix: socketPath,
1292
- socket: {
1293
- open: (socket) => void socket.write(`${JSON.stringify(request)}
1294
- `),
1295
- data: (_, chunk) => {
1296
- received += chunk.toString();
1297
- },
1298
- close: () => resolve(received),
1299
- error: () => resolve("")
1300
- }
1301
- });
1302
- } catch {
1303
- return 1;
1304
- }
1305
- const reply = await promise;
1306
- if (reply === "")
1307
- return 1;
1308
- const { answer } = JSON.parse(reply);
1309
- if (request.notice === true)
1310
- return 0;
1311
- if (answer === undefined)
1312
- return 1;
1313
- process13.stdout.write(`${answer}
1314
- `);
1315
- return 0;
1316
- }
1317
-
1318
- // ../kit/src/completions.ts
1319
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
1320
- var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
1321
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
1322
- set -l current (commandline -ct)
1323
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
1324
- if test "$line" = __files__
1325
- __fish_complete_path $current
1326
- else
1327
- echo $line
1328
- end
1329
- end
1330
- end`;
1331
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
1332
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
1333
- local -a lines
1334
- COMPREPLY=()
1335
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
1336
- for line in "\${lines[@]}"; do
1337
- if [[ $line == __files__ ]]; then
1338
- COMPREPLY+=($(compgen -f -- "$cur"))
1339
- else
1340
- words+="\${line%%$'\\t'*}"$'\\n'
1341
- fi
1342
- done
1343
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
1344
- }`;
1345
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
1346
- local line
1347
- local -a described plain
1348
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
1349
- if [[ $line == __files__ ]]; then
1350
- _files
1351
- elif [[ $line == *$'\\t'* ]]; then
1352
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
1353
- else
1354
- plain+=("$line")
1355
- fi
1356
- done
1357
- (( \${#described} )) && _describe -V value described
1358
- (( \${#plain} )) && compadd -- "\${plain[@]}"
1359
- return 0
1360
- }`;
1361
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
1362
- if (shell === "fish")
1363
- return `${header}
1364
- ${FISH_FUNCTION}
1365
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
1366
- `).join("")}`;
1367
- if (shell === "bash")
1368
- return `${header}
1369
- ${BASH_FUNCTION}
1370
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1371
- `;
1372
- return `${header}
1373
- ${ZSH_FUNCTION}
1374
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1375
- `;
1376
- }
1377
-
1378
- // ../kit/src/notify.ts
1379
- init_format();
1380
- init_mode();
1381
- import process14 from "process";
1382
- var NOTIFY_AFTER_MS = 1e4;
1383
- var CANCELLED = 130;
1384
- function base64(text) {
1385
- return Buffer.from(text).toString("base64");
1386
- }
1387
- function notification(title, body, env = process14.env) {
1388
- const id = `kit${process14.pid}`;
1389
- const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
1390
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1391
- }
1392
- function notifyEnd(command, code, ms, { stream = process14.stderr, env = process14.env } = {}) {
1393
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1394
- return;
1395
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1396
- }
1397
-
1398
- // ../kit/src/cli.ts
1399
- init_style();
1400
- init_text2();
1401
-
1402
- // ../kit/src/usage.ts
1403
- import { appendFileSync, mkdirSync } from "fs";
1404
- import { homedir as homedir4 } from "os";
1405
- import { dirname as dirname2, join as join5 } from "path";
1406
- import process16 from "process";
1407
-
1408
- // ../kit/src/logs.ts
1409
- init_user_config();
1410
- import { lstatSync, openSync } from "fs";
1411
- import { mkdir, mkdtemp, readdir, rm, stat } from "fs/promises";
1412
- import { homedir as homedir3, tmpdir } from "os";
1413
- import { join as join4 } from "path";
1414
- import process15 from "process";
1415
- var DAY_MS = 24 * 60 * 60 * 1000;
1416
- var CLI_FOLDER = "kaynooo-cli";
1417
- function isPrivateDirectory(path) {
1418
- try {
1419
- const info = lstatSync(path, { throwIfNoEntry: false });
1420
- return info !== undefined && info.isDirectory() && info.uid === (process15.getuid?.() ?? info.uid) && (info.mode & 63) === 0;
1421
- } catch {
1422
- return false;
1423
- }
1424
- }
1425
- async function privateLogDirectory(name, env = process15.env) {
1426
- const path = join4(xdgFolder(env.XDG_RUNTIME_DIR, join4(homedir3(), ".cache")), CLI_FOLDER, name);
1427
- try {
1428
- await mkdir(path, { recursive: true, mode: 448 });
1429
- if (isPrivateDirectory(path))
1430
- return path;
1431
- } catch {}
1432
- return mkdtemp(join4(tmpdir(), `${name.replaceAll("/", "-")}-`));
1433
- }
1434
-
1435
- // ../kit/src/usage.ts
1436
- init_user_config();
1437
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1438
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1439
- var LONGEST_NAME = 40;
1440
- var usageError;
1441
- function noteUsageError(message) {
1442
- usageError = message;
1443
- }
1444
- function stateHome(env = process16.env) {
1445
- return xdgFolder(env.XDG_STATE_HOME, join5(homedir4(), ".local", "state"));
1446
- }
1447
- function usagePath(env = process16.env) {
1448
- return join5(stateHome(env), CLI_FOLDER, "usage.jsonl");
1449
- }
1450
- function usageRecorded(env = process16.env) {
1451
- const off = env.KAYNOOO_CLI_NO_USAGE;
1452
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1453
- }
1454
- function flagNames(argv) {
1455
- const end = argv.indexOf("--");
1456
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1457
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1458
- }
1459
- function usageEntry(bin, command, argv, code, { ms, now = new Date } = {}) {
1460
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1461
- usageError = undefined;
1462
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown }, ...ms === undefined ? {} : { ms: Math.round(ms) } };
1463
- }
1464
- function recordUsage(entry, env = process16.env) {
1465
- if (!usageRecorded(env))
1466
- return;
1467
- try {
1468
- const path = usagePath(env);
1469
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1470
- appendFileSync(path, `${JSON.stringify(entry)}
1471
- `, { mode: 384 });
1472
- } catch {}
1473
- }
1474
-
1475
- // ../kit/src/cli.ts
1476
- var LEVEL_OPTIONS = {
1477
- ...OUTPUT_OPTIONS,
1478
- help: { type: "boolean", short: "h", description: "show this help" }
1479
- };
1480
- var TOP_OPTIONS = {
1481
- ...LEVEL_OPTIONS,
1482
- version: { type: "boolean", short: "v", description: "print the version" },
1483
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1484
- };
1485
- function printError(prefix, message, hint, cause) {
1486
- const colors = paint(process17.stderr);
1487
- const styled = takesControlCodes(process17.stderr);
1488
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1489
- const under = (label, text, tint) => text === undefined ? "" : `
1490
- ${styled ? tint(label) : `${label}:`} ${text}`;
1491
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1492
- }
1493
- function printJsonError(message, hint, cause) {
1494
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1495
- }
1496
- function wantsJson(argv) {
1497
- const end = argv.indexOf("--");
1498
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1499
- }
1500
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1501
- if (error instanceof HelpShown)
1502
- return 0;
1503
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1504
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1505
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1506
- if (error instanceof Exit && error.code === 2)
1507
- noteUsageError(error.message);
1508
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1509
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1510
- return error instanceof Exit ? error.code : 1;
1511
- }
1512
- var COMPLETE = "__complete";
1513
- var FILES = "__files__";
1514
- async function completingOf(run) {
1515
- completion.active = true;
1516
- try {
1517
- await run([]);
1518
- } catch (error) {
1519
- if (error instanceof Completing)
1520
- return error;
1521
- } finally {
1522
- completion.active = false;
1523
- }
1524
- return new Completing({});
1525
- }
1526
- function candidateLine(candidate) {
1527
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1528
- }
1529
- function positionalBeingTyped(before, { options, positionals }) {
1530
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1531
- const typed = [];
1532
- let at = 0;
1533
- while (at < before.length) {
1534
- const word = before[at];
1535
- if (word === "--") {
1536
- typed.push(...before.slice(at + 1));
1537
- break;
1538
- }
1539
- if (!word.startsWith("-"))
1540
- typed.push(word);
1541
- else if (takesValue(word))
1542
- at++;
1543
- at++;
1544
- }
1545
- const last = positionals.at(-1);
1546
- if (typed.length < positionals.length)
1547
- return { name: positionals[typed.length], typed };
1548
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1549
- }
1550
- async function leafCandidates(run, words) {
1551
- const completing = await completingOf(run);
1552
- if ((words.at(-1) ?? "").startsWith("-"))
1553
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1554
- const flag = words.at(-2);
1555
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1556
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1557
- if (option?.type === "string") {
1558
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1559
- return values === undefined ? [FILES] : values.map(candidateLine);
1560
- }
1561
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1562
- return values === undefined ? [FILES] : values.map(candidateLine);
1563
- }
1564
- var COMPLETIONS = "--completions";
1565
- function flagValue([flag = "", ...rest]) {
1566
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1567
- }
1568
- function printCompletionScript(name, args) {
1569
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1570
- if (shell === undefined || args.length !== 1) {
1571
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1572
- return 2;
1573
- }
1574
- console.log(completionScript(shell, [name]).trimEnd());
1575
- return 0;
1576
- }
1577
- async function printCandidates(found) {
1578
- for (const line of await found)
1579
- console.log(line);
1580
- return 0;
1581
- }
1582
- function packageVersion(entry = Bun.main) {
1583
- let resolved = entry;
1584
- try {
1585
- resolved = realpathSync2(entry);
1586
- } catch {}
1587
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1588
- try {
1589
- const { version } = JSON.parse(readFileSync5(join6(dir, "package.json"), "utf8"));
1590
- if (typeof version === "string")
1591
- return version;
1592
- } catch {}
1593
- if (dirname3(dir) === dir)
1594
- return "0.0.0";
1595
- }
1596
- }
1597
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1598
- const answered = await askpassClient(argv);
1599
- if (answered !== undefined)
1600
- return answered;
1601
- if (argv[0] === COMPLETE)
1602
- return printCandidates(leafCandidates(run, argv.slice(1)));
1603
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1604
- return printCompletionScript(name, flagValue(argv));
1605
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1606
- console.log(version ?? packageVersion());
1607
- return 0;
1608
- }
1609
- let code;
1610
- const started = performance.now();
1611
- heading.bin = { name, version: () => version ?? packageVersion() };
1612
- try {
1613
- code = await run(argv);
1614
- } catch (error) {
1615
- code = reportThrown(name, error, redact, wantsJson(argv));
1616
- } finally {
1617
- heading.bin = undefined;
1618
- }
1619
- notifyEnd(name, code, performance.now() - started);
1620
- if (usage !== false) {
1621
- try {
1622
- recordUsage(usageEntry(name, undefined, argv, code, { ms: performance.now() - started }));
1623
- } catch {}
1624
- }
1625
- return code;
1626
- }
1627
-
1628
- // ../kit/src/index.ts
1629
- init_config();
1630
-
1631
- // ../kit/src/excerpt.ts
1632
- init_text2();
1633
-
1634
- // ../kit/src/index.ts
1635
- init_folders();
1636
- init_format();
1637
-
1638
- // ../kit/src/git.ts
1639
- init_args();
1640
- // ../kit/src/limit.ts
1641
- init_args();
1642
-
1643
- // ../kit/src/index.ts
1644
- init_mode();
1645
-
1646
- // ../kit/src/report.ts
1647
- init_style();
1648
- init_text2();
1649
- // ../kit/src/secrets.ts
1650
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1651
- var NOT_PASSWORDS = new Set(["compass", "encompass", "bypass", "overpass", "underpass", "surpass", "trespass"]);
1652
- // ../kit/src/sessions.ts
1653
- import { homedir as homedir5 } from "os";
1654
- import { join as join7 } from "path";
1655
- import process18 from "process";
1656
- var {Glob } = globalThis.Bun;
1657
- var SESSION_FILES = new Glob("*.json");
1658
- var ACCOUNT_DIRS = new Glob("*/sessions");
1659
- async function sessionDirs() {
1660
- const home = homedir5();
1661
- const dirs = new Set([join7(home, ".claude", "sessions")]);
1662
- if (process18.env.CLAUDE_CONFIG_DIR !== undefined)
1663
- dirs.add(join7(process18.env.CLAUDE_CONFIG_DIR, "sessions"));
1664
- try {
1665
- for await (const dir of ACCOUNT_DIRS.scan({ cwd: join7(home, ".claude-accounts"), onlyFiles: false, absolute: true }))
1666
- dirs.add(dir);
1667
- } catch {}
1668
- return [...dirs];
1669
- }
1670
- async function procStat(pid) {
1671
- try {
1672
- const stat = await Bun.file(`/proc/${pid}/stat`).text();
1673
- return stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1674
- } catch {
1675
- return;
1676
- }
1677
- }
1678
- async function isAlive(pid, procStart) {
1679
- const stat = await procStat(pid);
1680
- if (stat === undefined)
1681
- return false;
1682
- return procStart === undefined || stat[19] === procStart;
1683
- }
1684
- async function liveSessions() {
1685
- const sessions = new Map;
1686
- for (const dir of await sessionDirs()) {
1687
- let files;
1688
- try {
1689
- files = await Array.fromAsync(SESSION_FILES.scan({ cwd: dir, absolute: true }));
1690
- } catch {
1691
- continue;
1692
- }
1693
- for (const file of files) {
1694
- let entry;
1695
- try {
1696
- entry = await Bun.file(file).json();
1697
- } catch {
1698
- continue;
1699
- }
1700
- if (entry.name === undefined || entry.pid === undefined || sessions.has(entry.pid) || !await isAlive(entry.pid, entry.procStart))
1701
- continue;
1702
- sessions.set(entry.pid, { name: entry.name, pid: entry.pid, status: entry.status ?? "unknown", cwd: entry.cwd ?? "" });
1703
- }
1704
- }
1705
- return [...sessions.values()];
1706
- }
1707
- async function currentSession(sessions) {
1708
- const byPid = new Map(sessions.map((session) => [session.pid, session]));
1709
- let pid = process18.ppid;
1710
- for (let depth = 0;depth < 32 && pid > 1; depth++) {
1711
- const session = byPid.get(pid);
1712
- if (session !== undefined)
1713
- return session;
1714
- const parent = Number((await procStat(pid))?.[1]);
1715
- if (!Number.isInteger(parent))
1716
- return;
1717
- pid = parent;
1718
- }
1719
- return;
1720
- }
1721
-
1722
- // ../kit/src/index.ts
1723
- init_style();
1724
- init_text2();
1725
- init_theme();
1726
- init_user_config();
1727
-
1728
- // ../kit/src/watch.ts
1729
- init_args();
1730
- init_input();
1731
- init_style();
1732
- // ../kit/src/workspace-root.ts
1733
- init_user_config();
1734
- // src/conditions.ts
1735
- import { existsSync as existsSync4, statSync as statSync2 } from "fs";
1736
- var TAIL = configuredNumber("wait", "tail", 20);
1737
- var AROUND = configuredNumber("wait", "around", 5);
1738
- var CARRIAGE_RETURN = /\r$/;
1739
- var SLICE_BYTES = 1024 * 1024;
1740
- var MAX_LINE = 1e4;
1741
- var PORT_TIMEOUT_MS = configuredNumber("wait", "portTimeoutMs", 3000);
1742
-
1743
- class FileWatch {
1744
- path;
1745
- until;
1746
- failOn;
1747
- offset = 0;
1748
- decoder = new TextDecoder;
1749
- partial = "";
1750
- identity;
1751
- number = 0;
1752
- recent = [];
1753
- failure;
1754
- matched = false;
1755
- constructor(path, until, failOn) {
1756
- this.path = path;
1757
- this.until = until;
1758
- this.failOn = failOn;
1759
- }
1760
- get done() {
1761
- return this.until === undefined || this.matched;
1762
- }
1763
- get failing() {
1764
- return this.failure !== undefined;
1765
- }
1766
- get failsFirst() {
1767
- return this.failure?.isFirst === true;
1768
- }
1769
- get exists() {
1770
- return existsSync4(this.path);
1771
- }
1772
- async poll() {
1773
- const events = [];
1774
- for (let lines = await this.nextLines();lines !== undefined; lines = await this.nextLines()) {
1775
- for (const line of lines) {
1776
- if (this.failure !== undefined) {
1777
- if (this.failure.after.length < AROUND)
1778
- this.failure.after.push(line);
1779
- continue;
1780
- }
1781
- if (this.failOn?.test(line.text) === true) {
1782
- this.failure = { before: this.recent.slice(-AROUND), line, after: [], waited: false, isFirst: !this.matched };
1783
- continue;
1784
- }
1785
- this.recent.push(line);
1786
- if (this.recent.length > TAIL)
1787
- this.recent.shift();
1788
- if (!this.matched && this.until?.test(line.text) === true) {
1789
- this.matched = true;
1790
- events.push({ kind: "until", line });
1791
- }
1792
- }
1793
- }
1794
- if (this.failure !== undefined && !this.failure.waited && this.failure.after.length < AROUND)
1795
- this.failure.waited = true;
1796
- else if (this.failure !== undefined)
1797
- events.push({ kind: "fail", line: this.failure.line, excerpt: [...this.failure.before, this.failure.line, ...this.failure.after] });
1798
- return events;
1799
- }
1800
- excerpt() {
1801
- return this.recent;
1802
- }
1803
- async nextLines() {
1804
- if (!existsSync4(this.path))
1805
- return;
1806
- const stats = statSync2(this.path);
1807
- if (stats.isDirectory())
1808
- badUsage(`--file ${this.path} is a folder, not a log file`);
1809
- const { size, dev, ino } = stats;
1810
- const replaced = this.identity !== undefined && (this.identity.dev !== dev || this.identity.ino !== ino);
1811
- this.identity = { dev, ino };
1812
- if (size < this.offset || replaced) {
1813
- this.offset = 0;
1814
- this.decoder = new TextDecoder;
1815
- this.partial = "";
1816
- this.number = 0;
1817
- this.recent = [];
1818
- }
1819
- if (size === this.offset)
1820
- return;
1821
- const end = Math.min(size, this.offset + SLICE_BYTES);
1822
- const chunk = this.decoder.decode(await this.slice(end), { stream: true });
1823
- this.offset = end;
1824
- const pieces = (this.partial + chunk).split(`
1825
- `);
1826
- this.partial = (pieces.pop() ?? "").slice(0, MAX_LINE);
1827
- return pieces.map((text) => ({ number: ++this.number, text: Bun.stripANSI(text.slice(0, MAX_LINE).replace(CARRIAGE_RETURN, "")) }));
1828
- }
1829
- async slice(end) {
1830
- try {
1831
- return await Bun.file(this.path).slice(this.offset, end).bytes();
1832
- } catch (error) {
1833
- return badUsage(`--file ${this.path} cannot be read (${error.code ?? String(error)})`);
1834
- }
1835
- }
1836
- }
1837
- async function portProblem(host, port, timeoutMs = PORT_TIMEOUT_MS) {
1838
- const attempt = Bun.connect({ hostname: host, port, socket: { data: (socket) => void socket.end() } });
1839
- let timer;
1840
- try {
1841
- const socket = await Promise.race([attempt, new Promise((resolve) => {
1842
- timer = setTimeout(resolve, timeoutMs, "timeout");
1843
- })]);
1844
- if (socket === "timeout") {
1845
- closeWhenConnected(attempt);
1846
- return "ETIMEDOUT";
1847
- }
1848
- socket.end();
1849
- return;
1850
- } catch (error) {
1851
- return error instanceof Error ? error.code ?? error.message : String(error);
1852
- } finally {
1853
- clearTimeout(timer);
1854
- }
1855
- }
1856
- async function closeWhenConnected(attempt) {
1857
- try {
1858
- (await attempt).end();
1859
- } catch {}
1860
- }
1861
- var STATUS_CLASS = /^([1-5])xx$/i;
1862
- var STATUS_RANGE = /^(\d{3})(?:-(\d{3}))?$/;
1863
- var BODY_BYTES = 1024 * 1024;
1864
- function parseStatus(spec) {
1865
- const tests = [];
1866
- for (const part of spec.split(",").map((item) => item.trim())) {
1867
- const klass = STATUS_CLASS.exec(part);
1868
- const range = STATUS_RANGE.exec(part);
1869
- if (klass !== null) {
1870
- const hundred = Number(klass[1]);
1871
- tests.push((status) => Math.floor(status / 100) === hundred);
1872
- } else if (range !== null) {
1873
- const low = Number(range[1]);
1874
- const high = Number(range[2] ?? range[1]);
1875
- tests.push((status) => status >= low && status <= high);
1876
- } else {
1877
- return;
1878
- }
1879
- }
1880
- return (status) => tests.some((test) => test(status));
1881
- }
1882
- async function readBody(response) {
1883
- const reader = response.body?.getReader();
1884
- if (reader === undefined)
1885
- return "";
1886
- const decoder = new TextDecoder;
1887
- let text = "";
1888
- let bytes = 0;
1889
- while (bytes < BODY_BYTES) {
1890
- const { done, value } = await reader.read();
1891
- if (done)
1892
- break;
1893
- bytes += value?.length ?? 0;
1894
- text += decoder.decode(value, { stream: true });
1895
- }
1896
- await reader.cancel();
1897
- return text;
1898
- }
1899
- async function urlCheck(url, timeout, expect = {}) {
1900
- try {
1901
- const wantsRedirect = expect.status !== undefined && Array.from({ length: 100 }, (_, index) => 300 + index).some(expect.status.test);
1902
- const response = await fetch(url, { signal: AbortSignal.timeout(timeout), redirect: wantsRedirect ? "manual" : "follow" });
1903
- const ok = expect.status === undefined ? response.ok : expect.status.test(response.status);
1904
- if (!ok) {
1905
- await response.body?.cancel();
1906
- return { problem: expect.status === undefined ? `answered ${response.status}` : `answered ${response.status}, expected ${expect.status.spec}` };
1907
- }
1908
- if (expect.body === undefined) {
1909
- await response.body?.cancel();
1910
- return { status: response.status };
1911
- }
1912
- return expect.body.test(await readBody(response)) ? { status: response.status } : { problem: `answered ${response.status} but the body does not match ${expect.body}` };
1913
- } catch (error) {
1914
- return { problem: error instanceof Error ? error.message : String(error), isTimeout: error instanceof Error && error.name === "TimeoutError" };
1915
- }
1916
- }
1917
-
1918
- // src/task.ts
1919
- import { existsSync as existsSync5, lstatSync as lstatSync2, readFileSync as readFileSync6, statSync as statSync3 } from "fs";
1920
- import { join as join8 } from "path";
1921
- import process20 from "process";
1922
- var EXITED = /(?:^|\n)\[exited with code (-?\d+)\]\n*$/;
1923
- var FAILURE = /\(fail\)|\berror:/i;
1924
- var TASK_ID = /^[\w-]+$/;
1925
- var TAIL_BYTES = 256;
1926
- var LONGEST_FAILURES = 30;
1927
- var CARRIAGE_RETURN2 = /\r$/;
1928
- function tasksRoot(env) {
1929
- return join8(env.CLAUDE_CODE_TMPDIR ?? env.TMPDIR ?? "/tmp", `claude-${process20.getuid?.() ?? 0}`);
1930
- }
1931
- function taskFile(task, env = process20.env) {
1932
- if (task.includes("/") || task.endsWith(".output"))
1933
- return task;
1934
- if (!TASK_ID.test(task))
1935
- return;
1936
- const root = tasksRoot(env);
1937
- const found = existsSync5(root) ? [...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({ cwd: root, onlyFiles: false })] : [];
1938
- return found.length === 0 ? undefined : join8(root, found[0] ?? "");
1939
- }
1940
- function isTranscript(path) {
1941
- return existsSync5(path) && lstatSync2(path).isSymbolicLink() && path.endsWith(".output");
1942
- }
1943
- async function exitCode(path) {
1944
- if (!existsSync5(path))
1945
- return;
1946
- const size = statSync3(path).size;
1947
- const found = EXITED.exec(await Bun.file(path).slice(Math.max(0, size - TAIL_BYTES), size).text());
1948
- return found === null ? undefined : Number(found[1]);
1949
- }
1950
- async function taskEnd(path, lines) {
1951
- if (!existsSync5(path))
1952
- return { failures: [], tail: [] };
1953
- const text = (await Bun.file(path).text()).replace(EXITED, "");
1954
- const all = text.split(`
1955
- `).map((line, i) => ({ number: i + 1, text: Bun.stripANSI(line.replace(CARRIAGE_RETURN2, "")) }));
1956
- while (all.at(-1)?.text.trim() === "")
1957
- all.pop();
1958
- const tail = all.slice(-lines);
1959
- const first = tail[0]?.number ?? Infinity;
1960
- return { failures: all.filter((line) => line.number < first && FAILURE.test(line.text)).slice(-LONGEST_FAILURES), tail };
1961
- }
1962
- function pidAlive(pid) {
1963
- try {
1964
- process20.kill(pid, 0);
1965
- } catch (error) {
1966
- return error.code === "EPERM";
1967
- }
1968
- return !isZombie(pid);
1969
- }
1970
- function isZombie(pid) {
1971
- try {
1972
- const stat = readFileSync6(`/proc/${pid}/stat`, "utf8");
1973
- return stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) === "Z";
1974
- } catch {
1975
- return false;
1976
- }
1977
- }
1978
-
1979
- // src/cli.ts
1980
- var USAGE = `waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx, a process exits or a command exits 0
3
+ import{configuredNumber,paint,problem,formatDuration,formatElapsed,truncate,printJson,wholeNumber,duration,jsonOption,fail,badUsage,parse,runCommand,liveRegion,runMain}from"./chunk-mqe2vjsz.js";import{existsSync as existsSync3}from"fs";import process2 from"process";import{existsSync,statSync}from"fs";var TAIL=configuredNumber("wait","tail",20),AROUND=configuredNumber("wait","around",5),CARRIAGE_RETURN=/\r$/,SLICE_BYTES=1048576,MAX_LINE=1e4,PORT_TIMEOUT_MS=configuredNumber("wait","portTimeoutMs",3000);class FileWatch{path;until;failOn;offset=0;decoder=new TextDecoder;partial="";identity;number=0;recent=[];failure;matched=!1;constructor(path,until,failOn,fromEnd=!1){this.path=path;this.until=until;this.failOn=failOn;if(fromEnd&&existsSync(path)){let stats=statSync(path);if(stats.isDirectory())badUsage(`--file ${path} is a folder, not a log file`);this.offset=stats.size,this.identity={dev:stats.dev,ino:stats.ino}}}get done(){return this.until===void 0||this.matched}get failing(){return this.failure!==void 0}get failsFirst(){return this.failure?.isFirst===!0}get exists(){return existsSync(this.path)}async poll(){let events=[];for(let lines=await this.nextLines();lines!==void 0;lines=await this.nextLines())for(let line of lines){if(this.failure!==void 0){if(this.failure.after.length<AROUND)this.failure.after.push(line);continue}if(this.failOn?.test(line.text)===!0){this.failure={before:this.recent.slice(-AROUND),line,after:[],waited:!1,isFirst:!this.matched};continue}if(this.recent.push(line),this.recent.length>TAIL)this.recent.shift();if(!this.matched&&this.until?.test(line.text)===!0)this.matched=!0,events.push({kind:"until",line})}if(this.failure!==void 0&&!this.failure.waited&&this.failure.after.length<AROUND)this.failure.waited=!0;else if(this.failure!==void 0)events.push({kind:"fail",line:this.failure.line,excerpt:[...this.failure.before,this.failure.line,...this.failure.after]});return events}excerpt(){return this.recent}async nextLines(){if(!existsSync(this.path))return;let stats=statSync(this.path);if(stats.isDirectory())badUsage(`--file ${this.path} is a folder, not a log file`);let{size,dev,ino}=stats,replaced=this.identity!==void 0&&(this.identity.dev!==dev||this.identity.ino!==ino);if(this.identity={dev,ino},size<this.offset||replaced)this.offset=0,this.decoder=new TextDecoder,this.partial="",this.number=0,this.recent=[];if(size===this.offset)return;let end=Math.min(size,this.offset+SLICE_BYTES),chunk=this.decoder.decode(await this.slice(end),{stream:!0});this.offset=end;let pieces=(this.partial+chunk).split(`
4
+ `);return this.partial=(pieces.pop()??"").slice(0,MAX_LINE),pieces.map((text)=>({number:++this.number,text:Bun.stripANSI(text.slice(0,MAX_LINE).replace(CARRIAGE_RETURN,""))}))}async slice(end){try{return await Bun.file(this.path).slice(this.offset,end).bytes()}catch(error){return badUsage(`--file ${this.path} cannot be read (${error.code??String(error)})`)}}}async function portProblem(host,port,timeoutMs=PORT_TIMEOUT_MS){let attempt=Bun.connect({hostname:host,port,socket:{data:(socket)=>void socket.end()}}),timer;try{let socket=await Promise.race([attempt,new Promise((resolve)=>{timer=setTimeout(resolve,timeoutMs,"timeout")})]);if(socket==="timeout")return closeWhenConnected(attempt),"ETIMEDOUT";socket.end();return}catch(error){return error instanceof Error?error.code??error.message:String(error)}finally{clearTimeout(timer)}}async function closeWhenConnected(attempt){try{(await attempt).end()}catch{}}var STATUS_CLASS=/^([1-5])xx$/i,STATUS_RANGE=/^(\d{3})(?:-(\d{3}))?$/,BODY_BYTES=1048576;function parseStatus(spec){let tests=[];for(let part of spec.split(",").map((item)=>item.trim())){let klass=STATUS_CLASS.exec(part),range=STATUS_RANGE.exec(part);if(klass!==null){let hundred=Number(klass[1]);tests.push((status)=>Math.floor(status/100)===hundred)}else if(range!==null){let low=Number(range[1]),high=Number(range[2]??range[1]);tests.push((status)=>status>=low&&status<=high)}else return}return(status)=>tests.some((test)=>test(status))}async function healthyProblem(service){if(Bun.which("docker")===null)return"docker is not installed";let compose=await runCommand(["docker","compose","ps","--format","json",service]);if(compose.code===0&&compose.stdout.trim()!==""){let rows=compose.stdout.trim().split(`
5
+ `).flatMap((line)=>{try{let parsed=JSON.parse(line);return Array.isArray(parsed)?parsed:[parsed]}catch{return[]}});if(rows.length>0){let states=rows.map((row)=>String(row.Health??row.State??row.Status??"unknown").toLowerCase());return states.every((state)=>state==="healthy"||state.includes("(healthy)"))?void 0:states.join(", ")}}let inspected=await runCommand(["docker","inspect","--format","{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",service]);if(inspected.code!==0)return"container not found";let status=inspected.stdout.trim().toLowerCase();return status==="healthy"?void 0:status||"unknown"}async function readBody(response){let reader=response.body?.getReader();if(reader===void 0)return"";let decoder=new TextDecoder,text="",bytes=0;while(bytes<BODY_BYTES){let{done,value}=await reader.read();if(done)break;bytes+=value?.length??0,text+=decoder.decode(value,{stream:!0})}return await reader.cancel(),text}async function urlCheck(url,timeout,expect={}){try{let wantsRedirect=expect.status!==void 0&&Array.from({length:100},(_,index)=>300+index).some(expect.status.test),init={signal:AbortSignal.timeout(timeout),redirect:wantsRedirect?"manual":"follow",...expect.headers===void 0?{}:{headers:expect.headers},...expect.insecure===!0?{tls:{rejectUnauthorized:!1}}:{}},response=await fetch(url,init);if(!(expect.status===void 0?response.ok:expect.status.test(response.status)))return await response.body?.cancel(),{problem:expect.status===void 0?`answered ${response.status}`:`answered ${response.status}, expected ${expect.status.spec}`};if(expect.body===void 0)return await response.body?.cancel(),{status:response.status};return expect.body.test(await readBody(response))?{status:response.status}:{problem:`answered ${response.status} but the body does not match ${expect.body}`}}catch(error){return{problem:error instanceof Error?error.message:String(error),isTimeout:error instanceof Error&&error.name==="TimeoutError"}}}import{existsSync as existsSync2,lstatSync,readFileSync,statSync as statSync2}from"fs";import{join}from"path";import process from"process";var EXITED=/(?:^|\n)\[exited with code (-?\d+)\]\n*$/,FAILURE=/\(fail\)|\berror:/i,TASK_ID=/^[\w-]+$/,TAIL_BYTES=256,LONGEST_FAILURES=30,CARRIAGE_RETURN2=/\r$/;function tasksRoot(env){return join(env.CLAUDE_CODE_TMPDIR??env.TMPDIR??"/tmp",`claude-${process.getuid?.()??0}`)}function taskFile(task,env=process.env){if(task.includes("/")||task.endsWith(".output"))return task;if(!TASK_ID.test(task))return;let root=tasksRoot(env),found=existsSync2(root)?[...new Bun.Glob(`*/*/tasks/${task}.output`).scanSync({cwd:root,onlyFiles:!1})]:[];return found.length===0?void 0:join(root,found[0]??"")}function isTranscript(path){return existsSync2(path)&&lstatSync(path).isSymbolicLink()&&path.endsWith(".output")}async function exitCode(path){if(!existsSync2(path))return;let size=statSync2(path).size,found=EXITED.exec(await Bun.file(path).slice(Math.max(0,size-TAIL_BYTES),size).text());return found===null?void 0:Number(found[1])}async function taskEnd(path,lines){if(!existsSync2(path))return{failures:[],tail:[]};let all=(await Bun.file(path).text()).replace(EXITED,"").split(`
6
+ `).map((line,i)=>({number:i+1,text:Bun.stripANSI(line.replace(CARRIAGE_RETURN2,""))}));while(all.at(-1)?.text.trim()==="")all.pop();let tail=all.slice(-lines),first=tail[0]?.number??1/0;return{failures:all.filter((line)=>line.number<first&&FAILURE.test(line.text)).slice(-LONGEST_FAILURES),tail}}function pidAlive(pid){try{process.kill(pid,0)}catch(error){return error.code==="EPERM"}return!isZombie(pid)}function isZombie(pid){try{let stat=readFileSync(`/proc/${pid}/stat`,"utf8");return stat.slice(stat.lastIndexOf(")")+2,stat.lastIndexOf(")")+3)==="Z"}catch{return!1}}var USAGE=`waitfor [options]: waits until a file shows a line, a port listens, a URL answers 2xx, a Docker service is healthy, a process exits or a command exits 0
1981
7
  waitfor task <task id | file>: waits for a Claude Code background task to end (waitfor task --help)
1982
8
 
1983
- Every condition given must be met, or with --any the first of them to be; --port and --url may be repeated. A --fail line in --file ends the wait at once, and a timeout or a --fail line comes with an excerpt of what was seen last.`;
1984
- var TASK_USAGE = `waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
9
+ All conditions are polled in parallel every tick. Every condition given must be met, or with --any the first of them; --port, --url and --healthy may be repeated. A --fail line in --file or a --while-pid process exiting ends the wait immediately with exit 1.`,TASK_USAGE=`waitfor task [options] <task id | file>: waits for a Claude Code background task to end, then prints its exit code, its last lines and the (fail) and error: lines above them
1985
10
 
1986
11
  The task is the id a background Bash call returned, or the path of its .output file.
1987
- --json prints {task, path, code, ms, failures, tail}, each line as {number, text}.`;
1988
- var EXITS = [[0, "every condition was met"], [1, "a --fail line showed up"], [2, "it timed out or a usage error"]];
1989
- var TASK_EXITS = [[0, "the task exited 0"], [1, "it exited with another code"], [2, "it timed out or a usage error"]];
1990
- var TIMEOUT = { type: "string", short: "t", description: "how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds" };
1991
- var TASK_OPTIONS = {
1992
- lines: { type: "string", short: "n", description: "how many of its last lines to print (20)" },
1993
- timeout: TIMEOUT,
1994
- json: jsonOption(),
1995
- quiet: { type: "boolean", short: "q", description: "no live progress line" }
1996
- };
1997
- var OPTIONS = {
1998
- file: { type: "string", short: "f", description: "a log file to read, from its start, waiting for it to exist" },
1999
- until: { type: "string", short: "u", description: "a regular expression a line of --file must match" },
2000
- fail: { type: "string", short: "e", description: "a regular expression whose first matching line of --file is a failure" },
2001
- port: { type: "string", short: "p", multiple: true, description: "a TCP port that must accept connections, repeatable" },
2002
- host: { type: "string", short: "H", description: "the host of --port (127.0.0.1 and ::1)" },
2003
- url: { type: "string", multiple: true, description: "a URL that must answer 2xx (or --status), repeatable" },
2004
- status: { type: "string", description: "the status a --url must answer instead of 2xx: 301, 200-299, 2xx or a comma list, for every --url" },
2005
- body: { type: "string", description: "a regular expression the first MiB of a --url body must match, for every --url" },
2006
- pid: { type: "string", description: "a process id that must exit" },
2007
- cmd: { type: "string", short: "c", description: "a shell command that must exit 0, re-run every --interval" },
2008
- interval: { type: "string", description: "how long between two runs of --cmd (1s)" },
2009
- any: { type: "boolean", description: "met by the first condition that is, not all of them (needs two)" },
2010
- timeout: TIMEOUT,
2011
- json: jsonOption("{met, ms, line, conditions: [{name, ms}]}, line being the last --until line or the --fail one as {number, text}; the progress lines go to stderr"),
2012
- quiet: { type: "boolean", short: "q", description: "no live progress line: only what was met and the failure" }
2013
- };
2014
- var POLL = 250;
2015
- var URL_TIMEOUT = 5000;
2016
- var WIDTH = 400;
2017
- var CMD_RUN_LIMIT = 30000;
2018
- var LAST_LINE = /[^\n]+(?=\n*$)/;
2019
- function regex(source, name) {
2020
- if (source === undefined)
2021
- return;
2022
- try {
2023
- return new RegExp(source);
2024
- } catch (error) {
2025
- fail(`--${name} is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
2026
- }
2027
- }
2028
- function numbered(lines, marked) {
2029
- const width = String(lines.at(-1)?.number ?? 0).length;
2030
- return lines.map((line) => `${line === marked ? ">" : " "} ${String(line.number).padStart(width)} ${truncate(line.text, WIDTH)}`).join(`
2031
- `);
2032
- }
2033
- async function cmdProblem(command, timeoutMs) {
2034
- try {
2035
- const ran = await runCommand(["sh", "-c", command], { timeoutMs });
2036
- if (ran.code === 0 && !ran.timedOut)
2037
- return;
2038
- const last = LAST_LINE.exec(ran.text)?.[0];
2039
- return `${ran.timedOut ? "timed out" : `exited ${ran.code}`}${last === undefined ? "" : ` (${truncate(last, WIDTH)})`}`;
2040
- } catch (error) {
2041
- return `could not run: ${error instanceof Error ? error.message : String(error)}`;
2042
- }
2043
- }
2044
- async function waitTask(args) {
2045
- const { values, positionals: [task] } = parse(args, TASK_USAGE, TASK_OPTIONS, { positionals: ["<task>"], exits: TASK_EXITS });
2046
- const path = taskFile(task);
2047
- if (path === undefined)
2048
- fail(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);
2049
- if (!existsSync6(path))
2050
- fail(`no output file ${path}: ${task} is no background task of this machine`);
2051
- if (isTranscript(path))
2052
- fail(`${task} is a subagent, whose end its notification reports: waitfor task waits on a background Bash task`);
2053
- const lines = wholeNumber(values.lines, "lines", 20);
2054
- const timeout = duration(values.timeout, "timeout", 5 * 60000);
2055
- const started = Date.now();
2056
- const { dim } = paint(process21.stderr);
2057
- const region = values.quiet === true ? undefined : liveRegion((spinner) => [`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now() - started))}`]);
2058
- let code;
2059
- try {
2060
- for (;; ) {
2061
- code = await exitCode(path);
2062
- if (code !== undefined || Date.now() - started >= timeout)
2063
- break;
2064
- await Bun.sleep(POLL);
2065
- }
2066
- } finally {
2067
- region?.stop();
2068
- }
2069
- const { failures, tail } = await taskEnd(path, lines);
2070
- const last = tail.length === 0 ? "" : `
12
+ --json prints {task, path, code, ms, failures, tail}, each line as {number, text}.`,TIMEOUT_EXIT=124,EXITS=[[0,"every condition was met"],[1,"a --fail line showed up or --while-pid exited"],[124,"it timed out"],[2,"a usage error"]],TASK_EXITS=[[0,"the task exited 0"],[1,"it exited with another code"],[124,"it timed out"],[2,"a usage error"]],TIMEOUT={type:"string",short:"t",description:"how long before giving up (5m): 30s, 5m, 1h, a bare number in seconds"},TASK_OPTIONS={lines:{type:"string",short:"n",description:"how many of its last lines to print (20)"},timeout:TIMEOUT,json:jsonOption(),quiet:{type:"boolean",short:"q",description:"no live progress line"}},OPTIONS={file:{type:"string",short:"f",description:"a log file to read, waiting for it to exist"},"from-end":{type:"boolean",description:"with --file, start reading from the current end of the file (ignore existing lines)"},until:{type:"string",short:"u",description:"a regular expression a line of --file must match"},fail:{type:"string",short:"e",description:"a regular expression whose first matching line of --file is a failure"},port:{type:"string",short:"p",multiple:!0,description:"a TCP port that must accept connections, repeatable"},host:{type:"string",description:"the host of --port (127.0.0.1 and ::1)"},url:{type:"string",multiple:!0,description:"a URL that must answer 2xx (or --status), repeatable"},header:{type:"string",short:"H",multiple:!0,description:'"Name: value" header sent with every --url request, repeatable'},insecure:{type:"boolean",short:"k",description:"with --url, ignore untrusted TLS certificates"},status:{type:"string",description:"the status a --url must answer instead of 2xx: 301, 200-299, 2xx or a comma list, for every --url"},body:{type:"string",description:"a regular expression the first MiB of a --url body must match, for every --url"},healthy:{type:"string",multiple:!0,description:"a Docker Compose service or container that must report healthy, repeatable"},pid:{type:"string",description:"a process id that must exit"},"while-pid":{type:"string",description:"abort immediately with exit 1 if this process exits before conditions are met"},cmd:{type:"string",short:"c",description:"a shell command that must exit 0, re-run every --interval"},interval:{type:"string",description:"how long between two runs of --cmd (1s)"},any:{type:"boolean",description:"met by the first condition that is, not all of them (needs two)"},timeout:TIMEOUT,json:jsonOption("{met, ms, line, conditions: [{name, ms}]}, line being the last --until line or the --fail one as {number, text}; the progress lines go to stderr"),quiet:{type:"boolean",short:"q",description:"no live progress line: only what was met and the failure"}},POLL=250,URL_TIMEOUT=5000,WIDTH=400,CMD_RUN_LIMIT=30000,LAST_LINE=/[^\n]+(?=\n*$)/,HEADER_LINE=/^[\w!#$%&'*+.^`|~-]+:/;function regex(source,name){if(source===void 0)return;try{return new RegExp(source)}catch(error){fail(`--${name} is no valid regular expression: ${error instanceof Error?error.message:String(error)}`)}}function numbered(lines,marked){let width=String(lines.at(-1)?.number??0).length;return lines.map((line)=>`${line===marked?">":" "} ${String(line.number).padStart(width)} ${truncate(line.text,WIDTH)}`).join(`
13
+ `)}async function cmdProblem(command,timeoutMs){try{let ran=await runCommand(["sh","-c",command],{timeoutMs});if(ran.code===0&&!ran.timedOut)return;let last=LAST_LINE.exec(ran.text)?.[0];return`${ran.timedOut?"timed out":`exited ${ran.code}`}${last===void 0?"":` (${truncate(last,WIDTH)})`}`}catch(error){return`could not run: ${error instanceof Error?error.message:String(error)}`}}async function waitTask(args){let{values,positionals:[task]}=parse(args,TASK_USAGE,TASK_OPTIONS,{positionals:["<task>"],exits:TASK_EXITS}),path=taskFile(task);if(path===void 0)fail(`no background task ${task}: give the id a background Bash call returned, or the path of its .output file`);if(!existsSync3(path))fail(`no output file ${path}: ${task} is no background task of this machine`);if(isTranscript(path))fail(`${task} is a subagent, whose end its notification reports: waitfor task waits on a background Bash task`);let lines=wholeNumber(values.lines,"lines",20),timeout=duration(values.timeout,"timeout",300000),started=Date.now(),{dim}=paint(process2.stderr),region=values.quiet===!0?void 0:liveRegion((spinner)=>[`${spinner} task ${task}: still running ${dim(formatElapsed(Date.now()-started))}`]),code;try{for(;;){if(code=await exitCode(path),code!==void 0||Date.now()-started>=timeout)break;await Bun.sleep(POLL)}}finally{region?.stop()}let{failures,tail}=await taskEnd(path,lines),last=tail.length===0?"":`
2071
14
  last lines of ${path}:
2072
- ${numbered(tail)}`;
2073
- if (code === undefined)
2074
- fail(`gave up after ${formatDuration(timeout)}: task ${task} is still running${last}`);
2075
- if (values.json === true) {
2076
- printJson({ task, path, code, ms: Date.now() - started, failures, tail });
2077
- return code === 0 ? 0 : 1;
2078
- }
2079
- const failed = failures.length === 0 ? "" : `
15
+ ${numbered(tail)}`;if(code===void 0)fail(`gave up after ${formatDuration(timeout)}: task ${task} is still running${last}`,TIMEOUT_EXIT);if(values.json===!0)return printJson({task,path,code,ms:Date.now()-started,failures,tail}),code===0?0:1;let failed=failures.length===0?"":`
2080
16
  (fail) and error: lines above them:
2081
- ${numbered(failures)}`;
2082
- console.log(`task ${task} exited with code ${code}, waited ${formatDuration(Date.now() - started)}${failed}${last}`);
2083
- return code === 0 ? 0 : 1;
2084
- }
2085
- async function main(args) {
2086
- if (args[0] === "task")
2087
- return waitTask(args.slice(1));
2088
- const parsed = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "sleep loops, tail -f and until ! pgrep -f", examples: [['waitfor --file dev.log --until "ready in" --fail error', "a dev server up, or its first error"], ["waitfor --port 5432 -t 2m", "Postgres accepting connections"]] });
2089
- const { values, positionals } = parsed;
2090
- if (positionals.length > 0)
2091
- fail(`unexpected argument ${positionals[0]}
17
+ ${numbered(failures)}`;return console.log(`task ${task} exited with code ${code}, waited ${formatDuration(Date.now()-started)}${failed}${last}`),code===0?0:1}async function main(args){if(args[0]==="task")return waitTask(args.slice(1));let parsed=parse(args,USAGE,OPTIONS,{exits:EXITS,replaces:"sleep loops, tail -f and until ! pgrep -f",examples:[['waitfor --file dev.log --from-end --until "ready in" --fail error',"a dev server up from new log lines, or its first error"],["waitfor --port 5432 --while-pid 1234 -t 2m","Postgres accepting connections while its launcher is alive"]]}),{values,positionals}=parsed;if(positionals.length>0)fail(`unexpected argument ${positionals[0]}
2092
18
 
2093
- ${USAGE}`);
2094
- const portTexts = values.port ?? [];
2095
- const urlTexts = values.url ?? [];
2096
- if (values.until === undefined && portTexts.length === 0 && urlTexts.length === 0 && values.pid === undefined && values.cmd === undefined)
2097
- fail(`give --until with --file, --port, --url, --pid or --cmd
19
+ ${USAGE}`);let portTexts=values.port??[],urlTexts=values.url??[],healthyTexts=values.healthy??[];if(values.until===void 0&&portTexts.length===0&&urlTexts.length===0&&healthyTexts.length===0&&values.pid===void 0&&values.cmd===void 0)fail(`give --until with --file, --port, --url, --healthy, --pid or --cmd
2098
20
 
2099
- ${USAGE}`);
2100
- if ((values.until !== undefined || values.fail !== undefined) !== (values.file !== undefined))
2101
- fail("--until and --fail read the --file lines, and --file needs one of them");
2102
- if (values.host !== undefined && portTexts.length === 0)
2103
- fail("--host goes with --port");
2104
- if ((values.status !== undefined || values.body !== undefined) && urlTexts.length === 0)
2105
- fail("--status and --body go with --url");
2106
- const conditions = [values.until, ...portTexts, ...urlTexts, values.pid, values.cmd].filter((condition) => condition !== undefined).length;
2107
- if (values.any === true && conditions < 2)
2108
- fail("--any needs two or more of --until, --port, --url, --pid and --cmd");
2109
- if (values.interval !== undefined && values.cmd === undefined)
2110
- fail("--interval goes with --cmd");
2111
- const ports = portTexts.map((text) => {
2112
- const port = wholeNumber(text, "port", 0);
2113
- if (port > 65535)
2114
- fail(`--port takes a port up to 65535, not ${port}`);
2115
- return { name: String(port), port, left: "not checked yet" };
2116
- });
2117
- for (const url of urlTexts) {
2118
- if (!URL.canParse(url))
2119
- fail(`--url ${url} is no URL`);
2120
- }
2121
- const statusTest = values.status === undefined ? undefined : parseStatus(values.status);
2122
- if (values.status !== undefined && statusTest === undefined)
2123
- fail(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);
2124
- const expect = {};
2125
- if (values.status !== undefined && statusTest !== undefined)
2126
- expect.status = { test: statusTest, spec: values.status };
2127
- const body = regex(values.body, "body");
2128
- if (body !== undefined)
2129
- expect.body = body;
2130
- const urls = urlTexts.map((url) => ({ name: url, left: "not checked yet" }));
2131
- const metAt = [];
2132
- const pid = values.pid === undefined ? undefined : wholeNumber(values.pid, "pid", 0);
2133
- const hosts = values.host === undefined ? ["127.0.0.1", "::1"] : [values.host];
2134
- const interval = duration(values.interval, "interval", 1000);
2135
- const isAny = values.any === true;
2136
- const timeout = duration(values.timeout, "timeout", 5 * 60000);
2137
- const watch = values.file === undefined ? undefined : new FileWatch(values.file, regex(values.until, "until"), regex(values.fail, "fail"));
2138
- const started = Date.now();
2139
- const json = values.json === true;
2140
- const say = json ? console.error : console.log;
2141
- let matched;
2142
- let isPidLeft = pid !== undefined;
2143
- let cmdLeft = values.cmd === undefined ? undefined : "not run yet";
2144
- let cmdRanAt = 0;
2145
- const { dim } = paint(process21.stderr);
2146
- const region = values.quiet === true ? undefined : liveRegion((spinner) => {
2147
- const waited = dim(formatElapsed(Date.now() - started));
2148
- const left = [
2149
- watch === undefined || watch.done ? undefined : `${watch.path}: ${watch.exists ? "no --until line yet" : "does not exist yet"}`,
2150
- ...ports.filter((probe) => probe.left !== undefined).map((probe) => `${hosts[0]}:${probe.port}: ${probe.left}`),
2151
- ...urls.filter((probe) => probe.left !== undefined).map((probe) => `${probe.name}: ${probe.left}`),
2152
- isPidLeft ? `pid ${pid}: still running` : undefined,
2153
- cmdLeft === undefined ? undefined : `\`${values.cmd}\`: ${cmdLeft}`
2154
- ];
2155
- return left.filter((line) => line !== undefined).map((line) => `${spinner} ${line} ${waited}`);
2156
- });
2157
- try {
2158
- for (;; ) {
2159
- if (watch !== undefined) {
2160
- for (const event of await watch.poll()) {
2161
- if (event.kind === "until") {
2162
- say(`${watch.path}:${event.line.number}: ${truncate(event.line.text, WIDTH)}`);
2163
- matched = { number: event.line.number, text: event.line.text };
2164
- metAt.push({ name: `${watch.path} --until`, ms: Date.now() - started });
2165
- continue;
2166
- }
2167
- problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now() - started)}
2168
- ${numbered(event.excerpt, event.line)}`);
2169
- if (json)
2170
- printJson({ met: false, ms: Date.now() - started, line: { number: event.line.number, text: event.line.text } });
2171
- return 1;
2172
- }
2173
- }
2174
- for (const probe of ports) {
2175
- if (probe.left === undefined)
2176
- continue;
2177
- for (const candidate of hosts) {
2178
- const problem = await portProblem(candidate, probe.port ?? 0);
2179
- if (candidate === hosts[0])
2180
- probe.left = problem;
2181
- if (problem === undefined) {
2182
- const name = `${candidate.includes(":") ? `[${candidate}]` : candidate}:${probe.port}`;
2183
- probe.left = undefined;
2184
- probe.name = name;
2185
- metAt.push({ name, ms: Date.now() - started });
2186
- say(`${name} listening after ${formatDuration(Date.now() - started)}`);
2187
- break;
2188
- }
2189
- }
2190
- }
2191
- for (const probe of urls) {
2192
- if (probe.left === undefined)
2193
- continue;
2194
- const budget = Math.max(1, Math.min(URL_TIMEOUT, started + timeout - Date.now()));
2195
- const check = await urlCheck(probe.name, budget, expect);
2196
- const isCutShort = "problem" in check && check.isTimeout === true && budget < URL_TIMEOUT && probe.left !== "not checked yet";
2197
- if (!isCutShort)
2198
- probe.left = "problem" in check ? check.problem : undefined;
2199
- if ("status" in check) {
2200
- metAt.push({ name: probe.name, ms: Date.now() - started });
2201
- say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now() - started)}`);
2202
- }
2203
- }
2204
- if (pid !== undefined && isPidLeft) {
2205
- isPidLeft = pidAlive(pid);
2206
- if (!isPidLeft) {
2207
- metAt.push({ name: `pid ${pid}`, ms: Date.now() - started });
2208
- say(`pid ${pid} exited after ${formatDuration(Date.now() - started)}`);
2209
- }
2210
- }
2211
- if (values.cmd !== undefined && cmdLeft !== undefined && Date.now() - cmdRanAt >= interval) {
2212
- const budget = Math.max(1, Math.min(CMD_RUN_LIMIT, started + timeout - Date.now()));
2213
- const problem = await cmdProblem(values.cmd, budget);
2214
- if (!(problem?.startsWith("timed out") === true && budget < CMD_RUN_LIMIT && cmdLeft !== "not run yet"))
2215
- cmdLeft = problem;
2216
- cmdRanAt = Date.now();
2217
- if (cmdLeft === undefined) {
2218
- metAt.push({ name: `\`${values.cmd}\``, ms: Date.now() - started });
2219
- say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now() - started)}`);
2220
- }
2221
- }
2222
- const isMet = [
2223
- values.until !== undefined && (watch?.done ?? false),
2224
- ports.some((probe) => probe.left === undefined),
2225
- urls.some((probe) => probe.left === undefined),
2226
- pid !== undefined && !isPidLeft,
2227
- values.cmd !== undefined && cmdLeft === undefined
2228
- ];
2229
- const isAllMet = (watch?.done ?? true) && ports.every((probe) => probe.left === undefined) && urls.every((probe) => probe.left === undefined) && !isPidLeft && cmdLeft === undefined;
2230
- if ((isAny ? isMet.includes(true) : isAllMet) && !(watch?.failsFirst ?? false)) {
2231
- if (json)
2232
- printJson({ met: true, ms: Date.now() - started, line: matched ?? null, conditions: metAt });
2233
- return 0;
2234
- }
2235
- if (Date.now() - started >= timeout && !(watch?.failing ?? false))
2236
- break;
2237
- await Bun.sleep(POLL);
2238
- }
2239
- } finally {
2240
- region?.stop();
2241
- }
2242
- const missing = [];
2243
- if (watch !== undefined && !watch.done)
2244
- missing.push(watch.exists ? `no line of ${watch.path} matched --until` : `${watch.path} does not exist`);
2245
- for (const probe of ports) {
2246
- if (probe.left !== undefined)
2247
- missing.push(`${hosts[0]}:${probe.port} is not listening (${probe.left})`);
2248
- }
2249
- for (const probe of urls) {
2250
- if (probe.left !== undefined)
2251
- missing.push(`${probe.name} ${probe.left}`);
2252
- }
2253
- if (isPidLeft)
2254
- missing.push(`pid ${pid} is still running`);
2255
- if (cmdLeft !== undefined)
2256
- missing.push(`\`${values.cmd}\` ${cmdLeft}`);
2257
- const lines = watch?.excerpt() ?? [];
2258
- fail(`gave up after ${formatDuration(timeout)}${isAny ? ", none met" : ""}: ${missing.join(", ")}${lines.length === 0 ? "" : `
21
+ ${USAGE}`);if((values.until!==void 0||values.fail!==void 0)!==(values.file!==void 0))fail("--until and --fail read the --file lines, and --file needs one of them");if(values["from-end"]===!0&&values.file===void 0)fail("--from-end goes with --file");if(values.host!==void 0&&portTexts.length===0)fail("--host goes with --port");if((values.status!==void 0||values.body!==void 0||(values.header?.length??0)>0||values.insecure===!0)&&urlTexts.length===0)fail("--status, --body, --header and --insecure go with --url");let conditions=[values.until,...portTexts,...urlTexts,...healthyTexts,values.pid,values.cmd].filter((condition)=>condition!==void 0).length;if(values.any===!0&&conditions<2)fail("--any needs two or more of --until, --port, --url, --healthy, --pid and --cmd");if(values.interval!==void 0&&values.cmd===void 0)fail("--interval goes with --cmd");let ports=portTexts.map((text)=>{let port=wholeNumber(text,"port",0);if(port>65535)fail(`--port takes a port up to 65535, not ${port}`);return{name:String(port),port,left:"not checked yet"}});for(let url of urlTexts)if(!URL.canParse(url))fail(`--url ${url} is no URL`);let headers={};for(let entry of values.header??[]){if(!HEADER_LINE.test(entry))fail(`-H takes "Name: value", not ${entry}`);let at=entry.indexOf(":");headers[entry.slice(0,at).trim()]=entry.slice(at+1).trim()}let statusTest=values.status===void 0?void 0:parseStatus(values.status);if(values.status!==void 0&&statusTest===void 0)fail(`--status takes a code, a range or a class such as 301, 200-299 or 2xx, not ${values.status}`);let expect={...values.status!==void 0&&statusTest!==void 0?{status:{test:statusTest,spec:values.status}}:{},...Object.keys(headers).length===0?{}:{headers},...values.insecure===!0?{insecure:!0}:{}},body=regex(values.body,"body");if(body!==void 0)expect.body=body;let urls=urlTexts.map((url)=>({name:url,left:"not checked yet"})),services=healthyTexts.map((service)=>({name:service,left:"not checked yet"})),metAt=[],pid=values.pid===void 0?void 0:wholeNumber(values.pid,"pid",0),whilePid=values["while-pid"]===void 0?void 0:wholeNumber(values["while-pid"],"while-pid",0),hosts=values.host===void 0?["127.0.0.1","::1"]:[values.host],interval=duration(values.interval,"interval",1000),isAny=values.any===!0,timeout=duration(values.timeout,"timeout",300000),watch=values.file===void 0?void 0:new FileWatch(values.file,regex(values.until,"until"),regex(values.fail,"fail"),values["from-end"]===!0),started=Date.now(),json=values.json===!0,say=json?console.error:console.log,matched,isPidLeft=pid!==void 0,cmdLeft=values.cmd===void 0?void 0:"not run yet",cmdRanAt=0,{dim}=paint(process2.stderr),region=values.quiet===!0?void 0:liveRegion((spinner)=>{let waited=dim(formatElapsed(Date.now()-started));return[watch===void 0||watch.done?void 0:`${watch.path}: ${watch.exists?"no --until line yet":"does not exist yet"}`,...ports.filter((probe)=>probe.left!==void 0).map((probe)=>`${hosts[0]}:${probe.port}: ${probe.left}`),...urls.filter((probe)=>probe.left!==void 0).map((probe)=>`${probe.name}: ${probe.left}`),...services.filter((probe)=>probe.left!==void 0).map((probe)=>`service ${probe.name}: ${probe.left}`),isPidLeft?`pid ${pid}: still running`:void 0,cmdLeft===void 0?void 0:`\`${values.cmd}\`: ${cmdLeft}`].filter((line)=>line!==void 0).map((line)=>`${spinner} ${line} ${waited}`)});try{for(;;){if(whilePid!==void 0&&!pidAlive(whilePid)){if(problem(`waitfor: --while-pid ${whilePid} exited after ${formatDuration(Date.now()-started)} before conditions were met`),json)printJson({met:!1,ms:Date.now()-started,reason:`pid ${whilePid} exited`,line:null,conditions:metAt});return 1}let[fileEvents]=await Promise.all([watch===void 0?Promise.resolve([]):watch.poll(),Promise.all(ports.filter((probe)=>probe.left!==void 0).map(async(probe)=>{for(let candidate of hosts){let prob=await portProblem(candidate,probe.port??0);if(candidate===hosts[0])probe.left=prob;if(prob===void 0){let name=`${candidate.includes(":")?`[${candidate}]`:candidate}:${probe.port}`;probe.left=void 0,probe.name=name,metAt.push({name,ms:Date.now()-started}),say(`${name} listening after ${formatDuration(Date.now()-started)}`);return}}})),Promise.all(urls.filter((probe)=>probe.left!==void 0).map(async(probe)=>{let budget=Math.max(1,Math.min(URL_TIMEOUT,started+timeout-Date.now())),check=await urlCheck(probe.name,budget,expect);if(!(("problem"in check)&&check.isTimeout===!0&&budget<URL_TIMEOUT&&probe.left!=="not checked yet"))probe.left="problem"in check?check.problem:void 0;if("status"in check)metAt.push({name:probe.name,ms:Date.now()-started}),say(`${probe.name} answered ${check.status} after ${formatDuration(Date.now()-started)}`)})),Promise.all(services.filter((probe)=>probe.left!==void 0).map(async(probe)=>{let prob=await healthyProblem(probe.name);if(probe.left=prob,prob===void 0)metAt.push({name:`healthy:${probe.name}`,ms:Date.now()-started}),say(`${probe.name} healthy after ${formatDuration(Date.now()-started)}`)})),(async()=>{if(values.cmd!==void 0&&cmdLeft!==void 0&&Date.now()-cmdRanAt>=interval){let budget=Math.max(1,Math.min(CMD_RUN_LIMIT,started+timeout-Date.now())),prob=await cmdProblem(values.cmd,budget);if(!(prob?.startsWith("timed out")===!0&&budget<CMD_RUN_LIMIT&&cmdLeft!=="not run yet"))cmdLeft=prob;if(cmdRanAt=Date.now(),cmdLeft===void 0)metAt.push({name:`\`${values.cmd}\``,ms:Date.now()-started}),say(`\`${values.cmd}\` exited 0 after ${formatDuration(Date.now()-started)}`)}})()]);for(let event of fileEvents){if(event.kind==="until"){say(`${watch.path}:${event.line.number}: ${truncate(event.line.text,WIDTH)}`),matched={number:event.line.number,text:event.line.text},metAt.push({name:`${watch.path} --until`,ms:Date.now()-started});continue}if(problem(`waitfor: ${watch.path}:${event.line.number} matched --fail after ${formatDuration(Date.now()-started)}
22
+ ${numbered(event.excerpt,event.line)}`),json)printJson({met:!1,ms:Date.now()-started,line:{number:event.line.number,text:event.line.text}});return 1}if(pid!==void 0&&isPidLeft){if(isPidLeft=pidAlive(pid),!isPidLeft)metAt.push({name:`pid ${pid}`,ms:Date.now()-started}),say(`pid ${pid} exited after ${formatDuration(Date.now()-started)}`)}let isMet=[values.until!==void 0&&(watch?.done??!1),ports.some((probe)=>probe.left===void 0),urls.some((probe)=>probe.left===void 0),services.some((probe)=>probe.left===void 0),pid!==void 0&&!isPidLeft,values.cmd!==void 0&&cmdLeft===void 0],isAllMet=(watch?.done??!0)&&ports.every((probe)=>probe.left===void 0)&&urls.every((probe)=>probe.left===void 0)&&services.every((probe)=>probe.left===void 0)&&!isPidLeft&&cmdLeft===void 0;if((isAny?isMet.includes(!0):isAllMet)&&!(watch?.failsFirst??!1)){if(json)printJson({met:!0,ms:Date.now()-started,line:matched??null,conditions:metAt});return 0}if(Date.now()-started>=timeout&&!(watch?.failing??!1))break;await Bun.sleep(POLL)}}finally{region?.stop()}let missing=[];if(watch!==void 0&&!watch.done)missing.push(watch.exists?`no line of ${watch.path} matched --until`:`${watch.path} does not exist`);for(let probe of ports)if(probe.left!==void 0)missing.push(`${hosts[0]}:${probe.port} is not listening (${probe.left})`);for(let probe of urls)if(probe.left!==void 0)missing.push(`${probe.name} ${probe.left}`);for(let probe of services)if(probe.left!==void 0)missing.push(`service ${probe.name} is not healthy (${probe.left})`);if(isPidLeft)missing.push(`pid ${pid} is still running`);if(cmdLeft!==void 0)missing.push(`\`${values.cmd}\` ${cmdLeft}`);let lines=watch?.excerpt()??[];fail(`gave up after ${formatDuration(timeout)}${isAny?", none met":""}: ${missing.join(", ")}${lines.length===0?"":`
2259
23
  last lines of ${watch?.path}:
2260
- ${numbered(lines)}`}`);
2261
- }
2262
- process21.exitCode = await runMain({ name: "waitfor", run: main });
24
+ ${numbered(lines)}`}`,TIMEOUT_EXIT)}process2.exitCode=await runMain({name:"waitfor",run:main});