@kaynooo/cli-code 0.15.1 → 0.17.2

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.
@@ -1,1661 +0,0 @@
1
- #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
- // @bun
3
-
4
- // src/hotspots-cli.ts
5
- import process17 from "process";
6
- // ../kit/src/args.ts
7
- import process9 from "process";
8
- import { parseArgs } from "util";
9
-
10
- // ../kit/src/format.ts
11
- import process7 from "process";
12
-
13
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
- var ct = /[aeiou]y$/;
15
- var N = new Map;
16
- var Ot = /(?:leaf|loaf|thief|wolf|half|calf|elf|sheaf|scarf|dwarf|hoof|wharf)$/;
17
- var Gt = /(?:knife|life|wife)$/;
18
- function K(t, e, { plural: r, zero: n = "singular" } = {}) {
19
- if (e === 1 || e === 0 && n === "singular")
20
- return t;
21
- if (r !== undefined)
22
- return r;
23
- if (t.endsWith("y") && !ct.test(t))
24
- return `${t.slice(0, -1)}ies`;
25
- if (t.endsWith("s") || t.endsWith("x") || t.endsWith("z") || t.endsWith("ch") || t.endsWith("sh"))
26
- return `${t}es`;
27
- if (Ot.test(t))
28
- return `${t.slice(0, -1)}ves`;
29
- return Gt.test(t) ? `${t.slice(0, -2)}ves` : `${t}s`;
30
- }
31
- function go(t, e, { zero: r = "plural", ...n } = {}) {
32
- return `${t} ${K(e, t, { ...n, zero: r })}`;
33
- }
34
- var Nt = /\s+\S*$/;
35
- var Y = /\s/;
36
- function ko(t, e, r = "...") {
37
- let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
38
- if (t.length <= e)
39
- return t;
40
- let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
41
- if (o && !Y.test(t[c.length] ?? " "))
42
- c = c.replace(Nt, "") || c;
43
- if (o)
44
- c = c.trimEnd();
45
- return s ? (c + n).slice(0, l) : c + n;
46
- }
47
- var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
48
- var z = new Map;
49
-
50
- // ../kit/src/mode.ts
51
- import process2 from "process";
52
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
53
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
54
- function isSet(value) {
55
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
56
- }
57
- function outputMode(stream = process2.stdout, env = process2.env) {
58
- const chosen = env.KIT_MODE;
59
- if (chosen !== undefined && MODES.has(chosen))
60
- return chosen;
61
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
62
- return "agent";
63
- if (stream.isTTY === true)
64
- return "terminal";
65
- return isSet(env.CI) ? "ci" : "pipe";
66
- }
67
-
68
- // ../kit/src/style.ts
69
- import { resolve as resolve3 } from "path";
70
- import process6 from "process";
71
- import { pathToFileURL } from "url";
72
-
73
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
74
- var G2 = /^[a-f0-9]+$/i;
75
- function b(r) {
76
- let e = r.startsWith("#") ? r.slice(1) : r;
77
- if (!G2.test(e))
78
- return [0, 0, 0];
79
- if (e.length === 3 || e.length === 4)
80
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
81
- if (e.length !== 6 && e.length !== 8)
82
- throw Error(`Invalid hex color length: ${e.length}`);
83
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
84
- }
85
- var B2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
86
- let [l, n, c] = b(r);
87
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
88
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
89
- var h = new Set(["", "1", "2", "3", "true"]);
90
- function C(r, e = globalThis.process?.env ?? {}) {
91
- if (e.FORCE_COLOR !== undefined)
92
- return h.has(e.FORCE_COLOR);
93
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
94
- return false;
95
- return r?.isTTY === true;
96
- }
97
- function f(r, e = []) {
98
- let l = "", n = "";
99
- for (let t = 0, i = e.length;t < i; t++)
100
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
101
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
102
- return new Proxy(c, { get(t, i) {
103
- let a = B2[i];
104
- if (Array.isArray(a)) {
105
- let s = g.get(i);
106
- if (s === undefined)
107
- s = f(r, [...e, a]), g.set(i, s);
108
- return s;
109
- }
110
- if (typeof a === "function")
111
- return (...s) => {
112
- let y = `${i}:${s.join(",")}`, u = g.get(y);
113
- if (u === undefined) {
114
- if (g.size >= 64)
115
- g.clear();
116
- u = f(r, [...e, a(...s)]), g.set(y, u);
117
- }
118
- return u;
119
- };
120
- throw Error(`Unknown style: ${String(i)}`);
121
- } });
122
- }
123
- function Fe(r = {}) {
124
- return f(r);
125
- }
126
- var o = Fe();
127
-
128
- // ../kit/src/theme.ts
129
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
130
- import { homedir as homedir2 } from "os";
131
- import { join as join3, resolve as resolve2 } from "path";
132
- import process5 from "process";
133
-
134
- // ../kit/src/config.ts
135
- import { existsSync } from "fs";
136
- import { dirname, join, resolve } from "path";
137
- import process3 from "process";
138
- function findUp(names, from = process3.cwd(), stop = () => false) {
139
- const wanted = typeof names === "string" ? [names] : names;
140
- for (let dir = resolve(from);; dir = dirname(dir)) {
141
- const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
142
- if (found !== undefined)
143
- return found;
144
- if (stop(dir) || dirname(dir) === dir)
145
- return;
146
- }
147
- }
148
-
149
- // ../kit/src/user-config.ts
150
- import { existsSync as existsSync2, readFileSync } from "fs";
151
- import { homedir } from "os";
152
- import { join as join2 } from "path";
153
- import process4 from "process";
154
- function configBase(where = {}) {
155
- const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
156
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
157
- }
158
- function userConfigPath(bin, where = {}) {
159
- return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
160
- }
161
- function userConfigReadPath(bin, legacy = [], where = {}) {
162
- const current = userConfigPath(bin, where);
163
- if (existsSync2(current))
164
- return current;
165
- const base = configBase(where);
166
- return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
167
- }
168
- function readUserConfig(bin, where = {}, legacy = []) {
169
- const path = userConfigReadPath(bin, legacy, where);
170
- if (!existsSync2(path))
171
- return {};
172
- try {
173
- const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
174
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
175
- } catch {
176
- return {};
177
- }
178
- }
179
- function configuredNumber(bin, key, fallback, where = {}, legacy = []) {
180
- const value = readUserConfig(bin, where, legacy)[key];
181
- return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
182
- }
183
-
184
- // ../kit/src/theme.ts
185
- var ENDS = new Map;
186
- var DEFAULT = {
187
- 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" },
188
- 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" },
189
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
190
- bins: {},
191
- gradient: ["#c084fc", "#67e8f9"]
192
- };
193
- var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", plan: "magentaBright", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
194
- var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", plan: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
195
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
196
- var PRESETS = {
197
- default: {},
198
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
199
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
200
- ascii: { glyphs: ASCII }
201
- };
202
- var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
203
- var HEX = /^#[0-9a-f]{6}$/i;
204
- var CONTROL = /\p{Cc}/u;
205
- var MAX_FILE_BYTES = 64 * 1024;
206
- var SPACES = /\s+/;
207
- function isColorSpec(spec) {
208
- if (typeof spec === "number")
209
- return Number.isInteger(spec) && spec >= 0 && spec <= 255;
210
- return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
211
- }
212
- var CUBE = [0, 95, 135, 175, 215, 255];
213
- function cubeLevel(channel) {
214
- return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
215
- }
216
- function nearest256(hex) {
217
- const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
218
- const levels = rgb.map(cubeLevel);
219
- const cube = levels.map((level) => CUBE[level]);
220
- const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
221
- const greyValue = 8 + grey * 10;
222
- const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
223
- return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
224
- }
225
- function hasTrueColor(env) {
226
- return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
227
- }
228
- function tinted(colors, spec, env = process5.env) {
229
- if (typeof spec === "number")
230
- return colors.ansi256(spec);
231
- return spec.trim().split(SPACES).reduce((chain, token) => {
232
- if (HEX.test(token))
233
- return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
234
- return chain[token] ?? chain;
235
- }, colors);
236
- }
237
- function isRecord(value) {
238
- return typeof value === "object" && value !== null && !Array.isArray(value);
239
- }
240
- function readThemeFile(path, warn) {
241
- try {
242
- const stat = statSync(path, { throwIfNoEntry: false });
243
- if (stat === undefined)
244
- return;
245
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
246
- warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
247
- return;
248
- }
249
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
250
- if (isRecord(parsed))
251
- return parsed;
252
- warn(`${path} is not a JSON object, theme ignored`);
253
- } catch (error) {
254
- warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
255
- }
256
- return;
257
- }
258
- function applyPreset(theme, name, warn, where) {
259
- if (name === undefined)
260
- return;
261
- if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
262
- warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
263
- return;
264
- }
265
- const preset = PRESETS[name];
266
- Object.assign(theme.colors, preset.colors);
267
- Object.assign(theme.glyphs, preset.glyphs);
268
- if (preset.accents !== undefined)
269
- theme.accents = [...preset.accents];
270
- if (Object.hasOwn(preset, "gradient"))
271
- theme.gradient = preset.gradient;
272
- return name;
273
- }
274
- function applyFile(theme, file, where, warn) {
275
- if (isRecord(file.colors)) {
276
- for (const [key, value] of Object.entries(file.colors)) {
277
- if (!Object.hasOwn(DEFAULT.colors, key))
278
- warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
279
- else if (!isColorSpec(value))
280
- warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
281
- else
282
- theme.colors[key] = value;
283
- }
284
- }
285
- if (isRecord(file.glyphs)) {
286
- for (const [key, value] of Object.entries(file.glyphs)) {
287
- if (!Object.hasOwn(DEFAULT.glyphs, key))
288
- warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
289
- else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
290
- warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
291
- else
292
- theme.glyphs[key] = value;
293
- }
294
- }
295
- if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
296
- theme.accents = [...file.accents];
297
- else if (file.accents !== undefined)
298
- warn(`${where}: accents must be a non-empty list of colours`);
299
- if (file.gradient === null)
300
- theme.gradient = undefined;
301
- else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
302
- theme.gradient = [file.gradient[0], file.gradient[1]];
303
- else if (file.gradient !== undefined)
304
- warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
305
- if (isRecord(file.bins)) {
306
- for (const [bin, value] of Object.entries(file.bins)) {
307
- if (isColorSpec(value))
308
- theme.bins[bin] = value;
309
- else
310
- warn(`${where}: bin ${bin} has no valid colour`);
311
- }
312
- }
313
- }
314
- function endsWalk(home) {
315
- return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
316
- }
317
- var warned = new Set;
318
- function warnOnce(message) {
319
- if (warned.has(message))
320
- return;
321
- warned.add(message);
322
- console.error(`warning: theme ${message}`);
323
- }
324
- function isPath(chosen) {
325
- return chosen.includes("/") || chosen.endsWith(".json");
326
- }
327
- function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
328
- const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
329
- const sources = [];
330
- const chosen = env.KIT_THEME ?? "";
331
- const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
332
- if (isPath(chosen))
333
- wanted.push(resolve2(from, chosen));
334
- const files = [];
335
- for (const path of wanted) {
336
- const file = path === undefined ? undefined : readThemeFile(path, warn);
337
- if (path !== undefined && file !== undefined)
338
- files.push({ path, file });
339
- }
340
- let preset = "default";
341
- if (chosen !== "" && !isPath(chosen)) {
342
- preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
343
- } else {
344
- const named = files.findLast(({ file }) => file.preset !== undefined);
345
- if (named !== undefined)
346
- preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
347
- }
348
- for (const { path, file } of files) {
349
- applyFile(theme, file, path, warn);
350
- sources.push(path);
351
- }
352
- return { theme, sources, preset };
353
- }
354
- var current;
355
- var currentKey = "";
356
- function activeTheme() {
357
- const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
358
- if (current === undefined || key !== currentKey) {
359
- current = loadTheme();
360
- currentKey = key;
361
- }
362
- return current;
363
- }
364
-
365
- // ../kit/src/style.ts
366
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
367
- function takesControlCodes(stream, env = process6.env) {
368
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
369
- }
370
- function paint(stream, env = process6.env) {
371
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
372
- }
373
- function marked(mark, text, stream, detail, env = process6.env) {
374
- const colors = paint(stream, env);
375
- let head = MARK_WORDS[mark];
376
- if (takesControlCodes(stream, env)) {
377
- const { theme } = activeTheme();
378
- head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
379
- }
380
- return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
381
- }
382
- function warn(text, detail) {
383
- console.error(marked("warn", text, process6.stderr, detail));
384
- }
385
- function role(name, stream, env = process6.env) {
386
- const colors = paint(stream, env);
387
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
388
- }
389
- var STATUS_WORDS = {
390
- passed: ["passed", "success", "succeeded", "ok"],
391
- failed: ["failed", "failure", "error", "errored"],
392
- running: ["running", "in_progress", "started", "holding"],
393
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
394
- skipped: ["skipped", "cancelled", "canceled", "manual"]
395
- };
396
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
397
- function header(bin, context, stream, env = process6.env) {
398
- if (!takesControlCodes(stream, env))
399
- return "";
400
- const colors = paint(stream, env);
401
- const hash = [...bin].reduce((sum, char) => sum + char.charCodeAt(0), 0);
402
- const { theme } = activeTheme();
403
- const spec = theme.bins[bin] ?? theme.accents[hash % theme.accents.length];
404
- const accent = tinted(typeof spec === "string" && spec.split(" ").includes("bold") ? colors : colors.bold, spec, env);
405
- return `${accent(bin)}${context === undefined ? "" : colors.dim(` \u203A ${context}`)}`;
406
- }
407
- function link(text, url, stream, env = process6.env) {
408
- if (takesControlCodes(stream, env))
409
- return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
410
- return text === url ? text : `${text} (${url})`;
411
- }
412
- function printHeader(bin, context, stream = process6.stdout, env = process6.env) {
413
- const line = header(bin, context, stream, env);
414
- if (line !== "")
415
- console.log(line);
416
- }
417
- function hyperlink(text, url, stream, env = process6.env) {
418
- return takesControlCodes(stream, env) ? paint(stream, env).underline(link(text, url, stream, env)) : text;
419
- }
420
- function fileLink(text, path, stream, from = process6.cwd(), env = process6.env) {
421
- return hyperlink(text, pathToFileURL(resolve3(from, path)).href, stream, env);
422
- }
423
-
424
- // ../kit/src/format.ts
425
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
426
- function formatSeconds(total) {
427
- let rest = Math.max(0, Math.round(total));
428
- const amounts = UNITS.map(([unit, size]) => {
429
- const amount = Math.floor(rest / size);
430
- rest -= amount * size;
431
- return `${amount}${unit}`;
432
- });
433
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
434
- if (first === -1)
435
- return "0s";
436
- const next = amounts[first + 1];
437
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
438
- }
439
- function formatDuration(ms) {
440
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
441
- }
442
- function upTo(text, separator) {
443
- const end = text.indexOf(separator);
444
- return end === -1 ? text : text.slice(0, end);
445
- }
446
- function truncate(text, width) {
447
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
448
- }
449
- var LINE_BREAKS = /\s*\n\s*/g;
450
- var ESCAPE = String.fromCharCode(27);
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
-
500
- // ../kit/src/help.ts
501
- import process8 from "process";
502
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
503
- var USAGE_PREFIX = /^usage:\s*/i;
504
- var FULL_STOP = /\.$/;
505
- function usageLine(usage, colors = paint(process8.stdout)) {
506
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
507
- }
508
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
509
- return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
510
- `);
511
- }
512
- function exitRows(exits, colors = paint(process8.stdout)) {
513
- if (exits.length === 0)
514
- return [];
515
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
516
- }
517
- function wantsHelpJson(env = process8.env) {
518
- return env.KIT_HELP === "json";
519
- }
520
- function description(usage, { examples = [], replaces, exits } = {}, options) {
521
- const lines = usage.replace(USAGE_PREFIX, "").split(`
522
- `);
523
- const first = lines[0];
524
- const colon = first.indexOf(": ");
525
- const prose = lines[lines.indexOf("") + 1] ?? "";
526
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
527
- return {
528
- synopsis: colon === -1 ? first : first.slice(0, colon),
529
- summary: colon === -1 ? fallback : first.slice(colon + 2),
530
- ...replaces === undefined ? {} : { replaces },
531
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
532
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
533
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
534
- };
535
- }
536
- function exampleRows(examples, colors = paint(process8.stdout)) {
537
- if (examples.length === 0 || outputMode() === "agent")
538
- return [];
539
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
540
- }
541
- var MAX_INLINE_CHOICES = 24;
542
- function optionRows(options, colors = paint(process8.stdout)) {
543
- const rows = Object.entries(options).map(([name, option]) => {
544
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
545
- const choices = option.choices?.join("|");
546
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
547
- const named = inline ? `<${choices}>` : "<value>";
548
- const placeholder = option.optional === undefined ? named : `[${named}]`;
549
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
550
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
551
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
552
- });
553
- const width = Math.max(0, ...rows.map((row) => row.width));
554
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
555
- }
556
-
557
- // ../kit/src/text.ts
558
- function distance(a, b) {
559
- const left = [...a];
560
- const right = [...b];
561
- let before = [];
562
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
563
- for (const [i, x] of left.entries()) {
564
- const current = [i + 1];
565
- for (const [j, y] of right.entries()) {
566
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
567
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
568
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
569
- current.push(cost);
570
- }
571
- before = previous;
572
- previous = current;
573
- }
574
- return previous[right.length] ?? 0;
575
- }
576
- function closest(name, names) {
577
- const started = names.find((known) => known.startsWith(name));
578
- if (started !== undefined)
579
- return started;
580
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
581
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
582
- }
583
- // ../kit/src/input.ts
584
- import { fstatSync } from "fs";
585
- var WHOLE = /^\d+$/;
586
- function wholeNumber(value, name, fallback, min = 1) {
587
- if (value === undefined)
588
- return fallback;
589
- const number = Number(value);
590
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
591
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
592
- return number;
593
- }
594
- var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
595
- var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
596
- function duration(value, name, fallback, unit = "s") {
597
- if (value === undefined)
598
- return fallback;
599
- const match = DURATION.exec(value.trim());
600
- const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
601
- if (ms < 1)
602
- badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
603
- return ms;
604
- }
605
- function isStdinPiped() {
606
- const stat = fstatSync(0);
607
- return stat.isFIFO() || stat.isFile();
608
- }
609
-
610
- // ../kit/src/args.ts
611
- var DASHES = /^-+/;
612
- function jsonOption(holds) {
613
- return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
614
- }
615
- class Exit extends Error {
616
- code;
617
- hint;
618
- constructor(message, code, hint) {
619
- super(message);
620
- this.code = code;
621
- this.hint = hint;
622
- }
623
- }
624
- function fail(message, code = 2, hint) {
625
- throw new Exit(message, code, hint);
626
- }
627
-
628
- class UsageError extends Exit {
629
- constructor(message, hint) {
630
- super(message, 2, hint);
631
- }
632
- }
633
- function badUsage(message) {
634
- throw new UsageError(message);
635
- }
636
-
637
- class HelpShown extends Exit {
638
- constructor() {
639
- super("help shown", 0);
640
- }
641
- }
642
-
643
- class Completing {
644
- options;
645
- positionals;
646
- candidates;
647
- constructor(options, positionals = [], candidates = {}) {
648
- this.options = options;
649
- this.positionals = positionals;
650
- this.candidates = candidates;
651
- }
652
- }
653
- var completion = { active: false };
654
- var OUTPUT_OPTIONS = {
655
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
656
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
657
- };
658
- function applyOutput(color, plain, env = process9.env) {
659
- const when = plain === true ? "never" : color ?? "auto";
660
- if (when === "auto")
661
- return;
662
- if (when !== "always" && when !== "never")
663
- badUsage(`--color takes auto, always or never, not ${when}`);
664
- if (when === "always") {
665
- env.FORCE_COLOR = "1";
666
- delete env.NO_COLOR;
667
- } else {
668
- env.NO_COLOR = "1";
669
- delete env.FORCE_COLOR;
670
- }
671
- }
672
- function parse(args, usage, options, settings = {}) {
673
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
674
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
675
- const listing = listed(all, settings.allowNegative === true);
676
- if (completion.active)
677
- throw new Completing(listing, settings.positionals, settings.candidates);
678
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
679
- let parsed;
680
- try {
681
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
682
- } catch (error) {
683
- const message = parseError(error);
684
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
685
- }
686
- const values = parsed.values;
687
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
688
- if (values.help === true) {
689
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
690
- throw new HelpShown;
691
- }
692
- checkChoices(parsed.values, all);
693
- checkConflicts(parsed.values, all);
694
- if (settings.positionals !== undefined)
695
- checkPositionals(parsed.positionals, settings.positionals);
696
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
697
- }
698
- function splitRest(args, passes) {
699
- const separator = passes ? args.indexOf("--") : -1;
700
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
701
- }
702
- function splitTrailing(args, options, count) {
703
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
704
- let seen = 0;
705
- if (count === 0)
706
- return { own: args, rest: undefined };
707
- for (let at = 0;at < args.length; at++) {
708
- const word = args[at];
709
- if (word === "--")
710
- break;
711
- if (word.startsWith("-")) {
712
- if (takesValue(word))
713
- at++;
714
- continue;
715
- }
716
- seen++;
717
- if (seen === count)
718
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
719
- }
720
- return { own: args, rest: undefined };
721
- }
722
- function listed(options, allowNegative) {
723
- if (!allowNegative)
724
- return options;
725
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
726
- if (option.type !== "boolean" || option.negative === undefined)
727
- return [[name, option]];
728
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
729
- }));
730
- }
731
- function withAliases(args, options) {
732
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
733
- if (named.size === 0)
734
- return args;
735
- const separator = args.indexOf("--");
736
- const own = separator === -1 ? args : args.slice(0, separator);
737
- return [...own.map((arg) => {
738
- const at = arg.indexOf("=");
739
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
740
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
741
- }), ...separator === -1 ? [] : args.slice(separator)];
742
- }
743
- function withBare(args, options) {
744
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
745
- if (bare.size === 0)
746
- return args;
747
- const separator = args.indexOf("--");
748
- const own = separator === -1 ? args : args.slice(0, separator);
749
- return [...own.flatMap((arg, index) => {
750
- const optional = bare.get(arg);
751
- const next = own[index + 1];
752
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
753
- return optional === undefined || value ? [arg] : [arg, optional.bare];
754
- }), ...separator === -1 ? [] : args.slice(separator)];
755
- }
756
- function checkConflicts(values, options) {
757
- const given = (name) => values[name] !== undefined && values[name] !== false;
758
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
759
- const other = given(name) ? conflicts.find(given) : undefined;
760
- if (other !== undefined)
761
- badUsage(`--${name} cannot be used with --${other}`);
762
- }
763
- }
764
- function checkChoices(values, options) {
765
- for (const [name, option] of Object.entries(options)) {
766
- if (option.choices === undefined)
767
- continue;
768
- const given = values[name];
769
- for (const value of Array.isArray(given) ? given : [given]) {
770
- if (typeof value === "string")
771
- oneOf(value, name, option.choices);
772
- }
773
- }
774
- }
775
- function oneOf(value, name, choices) {
776
- if (!choices.includes(value))
777
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
778
- return value;
779
- }
780
- function checkPositionals(given, names) {
781
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
782
- const required = names.filter((name) => !name.startsWith("[")).length;
783
- if (given.length < required)
784
- badUsage(`missing ${names[given.length]}`);
785
- if (!variadic && given.length > names.length)
786
- badUsage(`unexpected argument ${given[names.length]}`);
787
- }
788
- function joinDashValues(args, options) {
789
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
790
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
791
- const joined = [];
792
- for (let i = 0;i < args.length; i++) {
793
- const arg = args[i] ?? "";
794
- if (arg === "--")
795
- return [...joined, ...args.slice(i)];
796
- const name = longOf.get(arg);
797
- const next = args[i + 1];
798
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
799
- joined.push(`--${name}=${next}`);
800
- i++;
801
- } else {
802
- joined.push(arg);
803
- }
804
- }
805
- return joined;
806
- }
807
- function parseError(error) {
808
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
809
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
810
- }
811
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
812
- function nearestOption(message, options, allowNegative) {
813
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
814
- if (typed === undefined)
815
- return;
816
- const word = typed.replace(DASHES, "");
817
- if (word.length < 2 && !typed.startsWith("--"))
818
- return;
819
- const known = Object.entries(options).flatMap(([name, option]) => [
820
- ...option.short === undefined ? [] : [`-${option.short}`],
821
- `--${name}`,
822
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
823
- ]);
824
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
825
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
826
- }
827
- // ../kit/src/argv.ts
828
- import { readFileSync as readFileSync3, realpathSync } from "fs";
829
- import { resolve as resolve4 } from "path";
830
- import process10 from "process";
831
- function commandLine() {
832
- try {
833
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
834
- } catch {
835
- return;
836
- }
837
- }
838
- function realPath(word) {
839
- try {
840
- return realpathSync(resolve4(word));
841
- } catch {
842
- return;
843
- }
844
- }
845
- function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
846
- const target = script === undefined ? undefined : realPath(script) ?? script;
847
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve4(word) === script || realPath(word) === target));
848
- const after = at === -1 ? [] : cmdline.slice(at + 1);
849
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
850
- }
851
- // ../kit/src/process.ts
852
- import { constants } from "os";
853
- import process11 from "process";
854
- var KILL_GRACE_MS = 2000;
855
- function exitCodeOf(code, signal) {
856
- if (code !== null)
857
- return code;
858
- if (typeof signal === "number")
859
- return 128 + signal;
860
- return signal === null ? 129 : 128 + constants.signals[signal];
861
- }
862
- async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
863
- const chunks = [];
864
- const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
865
- const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
866
- const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
867
- const timers = [];
868
- const killGroup = (killing) => {
869
- if (state.done)
870
- return;
871
- try {
872
- if (grouped)
873
- process11.kill(-proc.pid, killing);
874
- else
875
- proc.kill(killing);
876
- } catch {}
877
- };
878
- const stop = () => {
879
- killGroup("SIGTERM");
880
- timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
881
- };
882
- const onAbort = () => stop();
883
- if (timeoutMs !== undefined) {
884
- timers.push(setTimeout(() => {
885
- state.timedOut = true;
886
- stop();
887
- }, timeoutMs));
888
- }
889
- if (signal?.aborted === true)
890
- onAbort();
891
- else
892
- signal?.addEventListener("abort", onAbort, { once: true });
893
- onStart?.({ kill: (killing) => killGroup(killing) });
894
- const drain = async (stream, name) => {
895
- for await (const data of stream) {
896
- if (state.failure !== undefined)
897
- continue;
898
- try {
899
- onChunk?.({ stream: name, data });
900
- } catch (error) {
901
- state.failure = error;
902
- stop();
903
- continue;
904
- }
905
- if (state.kept + data.length > maxBytes) {
906
- state.truncated = true;
907
- continue;
908
- }
909
- state.kept += data.length;
910
- chunks.push({ stream: name, data });
911
- }
912
- };
913
- try {
914
- await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
915
- await proc.exited;
916
- } finally {
917
- state.done = true;
918
- for (const timer of timers)
919
- clearTimeout(timer);
920
- signal?.removeEventListener("abort", onAbort);
921
- }
922
- if (state.failure !== undefined)
923
- throw state.failure;
924
- const joined = () => Buffer.concat(chunks.map(({ data }) => data));
925
- let output;
926
- let text;
927
- return {
928
- code: exitCodeOf(proc.exitCode, proc.signalCode),
929
- chunks,
930
- timedOut: state.timedOut,
931
- truncated: state.truncated,
932
- get output() {
933
- return output ??= joined();
934
- },
935
- get text() {
936
- return text ??= (output ??= joined()).toString();
937
- }
938
- };
939
- }
940
-
941
- // ../kit/src/progress.ts
942
- var ESC = String.fromCharCode(27);
943
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
944
- var RESET_STYLE = `${ESC}[0m`;
945
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
946
- // ../kit/src/cli.ts
947
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
948
- import { dirname as dirname3, join as join5 } from "path";
949
- import process14 from "process";
950
-
951
- // ../kit/src/completions.ts
952
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
953
- 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'
954
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
955
- set -l current (commandline -ct)
956
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
957
- if test "$line" = __files__
958
- __fish_complete_path $current
959
- else
960
- echo $line
961
- end
962
- end
963
- end`;
964
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
965
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
966
- local -a lines
967
- COMPREPLY=()
968
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
969
- for line in "\${lines[@]}"; do
970
- if [[ $line == __files__ ]]; then
971
- COMPREPLY+=($(compgen -f -- "$cur"))
972
- else
973
- words+="\${line%%$'\\t'*}"$'\\n'
974
- fi
975
- done
976
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
977
- }`;
978
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
979
- local line
980
- local -a described plain
981
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
982
- if [[ $line == __files__ ]]; then
983
- _files
984
- elif [[ $line == *$'\\t'* ]]; then
985
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
986
- else
987
- plain+=("$line")
988
- fi
989
- done
990
- (( \${#described} )) && _describe -V value described
991
- (( \${#plain} )) && compadd -- "\${plain[@]}"
992
- return 0
993
- }`;
994
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
995
- if (shell === "fish")
996
- return `${header}
997
- ${FISH_FUNCTION}
998
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
999
- `).join("")}`;
1000
- if (shell === "bash")
1001
- return `${header}
1002
- ${BASH_FUNCTION}
1003
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
1004
- `;
1005
- return `${header}
1006
- ${ZSH_FUNCTION}
1007
- compdef __kaynooo_cli_complete ${bins.join(" ")}
1008
- `;
1009
- }
1010
-
1011
- // ../kit/src/notify.ts
1012
- import process12 from "process";
1013
- var NOTIFY_AFTER_MS = 1e4;
1014
- var CANCELLED = 130;
1015
- function base64(text) {
1016
- return Buffer.from(text).toString("base64");
1017
- }
1018
- function notification(title, body, env = process12.env) {
1019
- const id = `kit${process12.pid}`;
1020
- 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\\`];
1021
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1022
- }
1023
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1024
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1025
- return;
1026
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1027
- }
1028
-
1029
- // ../kit/src/usage.ts
1030
- import { appendFileSync, mkdirSync } from "fs";
1031
- import { homedir as homedir3 } from "os";
1032
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
1033
- import process13 from "process";
1034
-
1035
- // ../kit/src/logs.ts
1036
- var DAY_MS = 24 * 60 * 60 * 1000;
1037
- var CLI_FOLDER = "kaynooo-cli";
1038
-
1039
- // ../kit/src/usage.ts
1040
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
1041
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
1042
- var LONGEST_NAME = 40;
1043
- var usageError;
1044
- function noteUsageError(message) {
1045
- usageError = message;
1046
- }
1047
- function stateHome(env = process13.env) {
1048
- const dir = env.XDG_STATE_HOME;
1049
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
1050
- }
1051
- function usagePath(env = process13.env) {
1052
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
1053
- }
1054
- function usageRecorded(env = process13.env) {
1055
- const off = env.KAYNOOO_CLI_NO_USAGE;
1056
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
1057
- }
1058
- function flagNames(argv) {
1059
- const end = argv.indexOf("--");
1060
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
1061
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
1062
- }
1063
- function usageEntry(bin, command, argv, code, now = new Date) {
1064
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
1065
- usageError = undefined;
1066
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
1067
- }
1068
- function recordUsage(entry, env = process13.env) {
1069
- if (!usageRecorded(env))
1070
- return;
1071
- try {
1072
- const path = usagePath(env);
1073
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
1074
- appendFileSync(path, `${JSON.stringify(entry)}
1075
- `, { mode: 384 });
1076
- } catch {}
1077
- }
1078
-
1079
- // ../kit/src/cli.ts
1080
- var LEVEL_OPTIONS = {
1081
- ...OUTPUT_OPTIONS,
1082
- help: { type: "boolean", short: "h", description: "show this help" }
1083
- };
1084
- var TOP_OPTIONS = {
1085
- ...LEVEL_OPTIONS,
1086
- version: { type: "boolean", short: "v", description: "print the version" },
1087
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1088
- };
1089
- async function commandRows(all, colors) {
1090
- const commands = shown(all);
1091
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
1092
- const groups = new Map([["Commands:", []]]);
1093
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
1094
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
1095
- const heading = group === undefined ? "Commands:" : `${group}:`;
1096
- const rows = groups.get(heading) ?? [];
1097
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
1098
- groups.set(heading, rows);
1099
- }
1100
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
1101
- }
1102
- function shown(commands) {
1103
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
1104
- }
1105
- function takeOutputFlags(argv) {
1106
- let index = 0;
1107
- for (;index < argv.length; index++) {
1108
- const word = argv[index];
1109
- if (word === "--plain")
1110
- applyOutput(undefined, true);
1111
- else if (word.startsWith("--color="))
1112
- applyOutput(word.slice("--color=".length), undefined);
1113
- else if (word === "--color" && argv[index + 1] !== undefined)
1114
- applyOutput(argv[++index], undefined);
1115
- else
1116
- break;
1117
- }
1118
- return argv.slice(index);
1119
- }
1120
- async function resolveSummary(summary) {
1121
- return typeof summary === "string" ? summary : summary();
1122
- }
1123
- function scopeOf(commands, extra, aliases) {
1124
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
1125
- }
1126
- async function expand(scope, words) {
1127
- if (scope.lazy.length === 0)
1128
- return scope;
1129
- const commands = { ...scope.commands };
1130
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
1131
- for (const [name, command] of Object.entries(added))
1132
- commands[name] ??= command;
1133
- }
1134
- return { ...scope, commands, lazy: [] };
1135
- }
1136
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
1137
- const colors = paint(stream);
1138
- const prefix = path.join(" ");
1139
- const summary = await resolveSummary(lazySummary);
1140
- if (wantsHelpJson())
1141
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
1142
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1143
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
1144
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
1145
- return [
1146
- header(colors, summary),
1147
- "",
1148
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1149
- "",
1150
- ...await commandRows(commands, colors),
1151
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1152
- "",
1153
- colors.bold("Options:"),
1154
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1155
- ...exampleRows(examples ?? [], colors),
1156
- "",
1157
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1158
- ].join(`
1159
- `);
1160
- }
1161
- function printError(prefix, message, hint, cause) {
1162
- const colors = paint(process14.stderr);
1163
- const styled = takesControlCodes(process14.stderr);
1164
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1165
- const under = (label, text, tint) => text === undefined ? "" : `
1166
- ${styled ? tint(label) : `${label}:`} ${text}`;
1167
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1168
- }
1169
- function printJsonError(message, hint, cause) {
1170
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1171
- }
1172
- function wantsJson(argv) {
1173
- const end = argv.indexOf("--");
1174
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1175
- }
1176
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1177
- if (error instanceof HelpShown)
1178
- return 0;
1179
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1180
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1181
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1182
- if (error instanceof Exit && error.code === 2)
1183
- noteUsageError(error.message);
1184
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1185
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1186
- return error instanceof Exit ? error.code : 1;
1187
- }
1188
- async function dispatch(level, typed, { version, redact }) {
1189
- const prefix = level.path.join(" ");
1190
- let argv;
1191
- try {
1192
- argv = takeOutputFlags(typed);
1193
- } catch (error) {
1194
- return reportThrown(prefix, error);
1195
- }
1196
- const [name, ...args] = argv;
1197
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1198
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1199
- try {
1200
- return await fallback.run([]);
1201
- } catch (error) {
1202
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1203
- }
1204
- }
1205
- if (name === undefined && level.path.length > 1) {
1206
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1207
- return 2;
1208
- }
1209
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1210
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1211
- return 0;
1212
- }
1213
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1214
- console.log(version);
1215
- return 0;
1216
- }
1217
- let command = level.commands[level.aliases?.[name] ?? name];
1218
- let rest = args;
1219
- let ran = name;
1220
- if (command === undefined && level.lazy.length > 0) {
1221
- level = await expand(level, [...level.path.slice(1), ...argv]);
1222
- command = level.commands[level.aliases?.[name] ?? name];
1223
- }
1224
- if (command === undefined && level.defaultCommand !== undefined) {
1225
- command = level.commands[level.defaultCommand];
1226
- rest = argv;
1227
- ran = level.defaultCommand;
1228
- }
1229
- if (command === undefined) {
1230
- const meant = closest(name, Object.keys(shown(level.commands)));
1231
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1232
- return 2;
1233
- }
1234
- if ("commands" in command) {
1235
- const { summary } = command;
1236
- return dispatch({ path: [...level.path, name], header: (colors, text) => `${colors.bold(`${prefix} ${name}`)} ${text}`, summary, ...scopeOf(command.commands, command.extraCommands, command.aliases), defaultCommand: undefined, runBare: false, examples: command.examples, replaces: undefined }, rest, { version, redact });
1237
- }
1238
- try {
1239
- return await command.run(rest);
1240
- } catch (error) {
1241
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1242
- }
1243
- }
1244
- var COMPLETE = "__complete";
1245
- var FILES = "__files__";
1246
- async function completingOf(run) {
1247
- completion.active = true;
1248
- try {
1249
- await run([]);
1250
- } catch (error) {
1251
- if (error instanceof Completing)
1252
- return error;
1253
- } finally {
1254
- completion.active = false;
1255
- }
1256
- return new Completing({});
1257
- }
1258
- async function optionsOf(run) {
1259
- return (await completingOf(run)).options;
1260
- }
1261
- function candidateLine(candidate) {
1262
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1263
- }
1264
- function positionalBeingTyped(before, { options, positionals }) {
1265
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1266
- const typed = [];
1267
- let at = 0;
1268
- while (at < before.length) {
1269
- const word = before[at];
1270
- if (word === "--") {
1271
- typed.push(...before.slice(at + 1));
1272
- break;
1273
- }
1274
- if (!word.startsWith("-"))
1275
- typed.push(word);
1276
- else if (takesValue(word))
1277
- at++;
1278
- at++;
1279
- }
1280
- const last = positionals.at(-1);
1281
- if (typed.length < positionals.length)
1282
- return { name: positionals[typed.length], typed };
1283
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1284
- }
1285
- async function leafCandidates(run, words) {
1286
- const completing = await completingOf(run);
1287
- if ((words.at(-1) ?? "").startsWith("-"))
1288
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1289
- const flag = words.at(-2);
1290
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1291
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1292
- if (option?.type === "string") {
1293
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1294
- return values === undefined ? [FILES] : values.map(candidateLine);
1295
- }
1296
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1297
- return values === undefined ? [FILES] : values.map(candidateLine);
1298
- }
1299
- async function candidates(scope, defaultCommand, words, before = []) {
1300
- const [word = "", ...rest] = words;
1301
- const listing = rest.length === 0 && !word.startsWith("-");
1302
- let { commands, aliases } = scope;
1303
- let command = commands[aliases?.[word] ?? word];
1304
- if (listing || command === undefined) {
1305
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1306
- command = commands[aliases?.[word] ?? word];
1307
- }
1308
- if (listing) {
1309
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1310
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1311
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1312
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1313
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1314
- }
1315
- if (command === undefined) {
1316
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1317
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1318
- }
1319
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1320
- }
1321
- var COMPLETIONS = "--completions";
1322
- function flagValue([flag = "", ...rest]) {
1323
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1324
- }
1325
- function printCompletionScript(name, args) {
1326
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1327
- if (shell === undefined || args.length !== 1) {
1328
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1329
- return 2;
1330
- }
1331
- console.log(completionScript(shell, [name]).trimEnd());
1332
- return 0;
1333
- }
1334
- async function printCandidates(found) {
1335
- for (const line of await found)
1336
- console.log(line);
1337
- return 0;
1338
- }
1339
- function packageVersion(entry = Bun.main) {
1340
- let resolved = entry;
1341
- try {
1342
- resolved = realpathSync2(entry);
1343
- } catch {}
1344
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1345
- try {
1346
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1347
- if (typeof version === "string")
1348
- return version;
1349
- } catch {}
1350
- if (dirname3(dir) === dir)
1351
- return "0.0.0";
1352
- }
1353
- }
1354
- async function runCli(cli, argv = scriptArgs()) {
1355
- const version = cli.version ?? packageVersion();
1356
- if (argv[0] === COMPLETE)
1357
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1358
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1359
- return printCompletionScript(cli.name, flagValue(argv));
1360
- const started = performance.now();
1361
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1362
- const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1363
- notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1364
- if (cli.usage !== false) {
1365
- try {
1366
- recordUsage(usageEntry(cli.name, command, argv, code));
1367
- } catch {}
1368
- }
1369
- return code;
1370
- }
1371
- function commandPath(scope, argv) {
1372
- const path = [];
1373
- let level = scope;
1374
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
1375
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1376
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1377
- if (command === undefined)
1378
- break;
1379
- path.push(word);
1380
- if (!("commands" in command))
1381
- break;
1382
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
1383
- }
1384
- return path.length === 0 ? undefined : path.join(" ");
1385
- }
1386
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1387
- if (argv[0] === COMPLETE)
1388
- return printCandidates(leafCandidates(run, argv.slice(1)));
1389
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1390
- return printCompletionScript(name, flagValue(argv));
1391
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1392
- console.log(version ?? packageVersion());
1393
- return 0;
1394
- }
1395
- let code;
1396
- const started = performance.now();
1397
- try {
1398
- code = await run(argv);
1399
- } catch (error) {
1400
- code = reportThrown(name, error, redact, wantsJson(argv));
1401
- }
1402
- notifyEnd(name, code, performance.now() - started);
1403
- if (usage !== false) {
1404
- try {
1405
- recordUsage(usageEntry(name, undefined, argv, code));
1406
- } catch {}
1407
- }
1408
- return code;
1409
- }
1410
- // ../kit/src/folders.ts
1411
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1412
- function ignoredFolders(extra = [], where = {}) {
1413
- const configured = readUserConfig("config", where).ignore;
1414
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1415
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1416
- }
1417
- // ../kit/src/limit.ts
1418
- function limitOptions(fallback) {
1419
- return {
1420
- limit: { type: "string", short: "n", description: `show at most this many rows, the rest counted (${fallback})` },
1421
- full: { type: "boolean", description: "show every row" }
1422
- };
1423
- }
1424
- function limitOf(values, fallback) {
1425
- if (values.full === true && values.limit !== undefined)
1426
- badUsage("--limit and --full exclude each other");
1427
- if (values.full === true || values.json === true && values.limit === undefined)
1428
- return Number.POSITIVE_INFINITY;
1429
- return wholeNumber(values.limit, "limit", fallback);
1430
- }
1431
- function moreFooter(more) {
1432
- return `${more} more, rerun with --full`;
1433
- }
1434
- function capped(rows, limit) {
1435
- const more = rows.length - limit;
1436
- return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
1437
- }
1438
- // ../kit/src/secrets.ts
1439
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1440
- // ../kit/src/sessions.ts
1441
- var {Glob } = globalThis.Bun;
1442
- var SESSION_FILES = new Glob("*.json");
1443
- var ACCOUNT_DIRS = new Glob("*/sessions");
1444
- // src/hotspots.ts
1445
- import { basename, join as join7 } from "path";
1446
- import process16 from "process";
1447
-
1448
- // src/churn.ts
1449
- var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|kay|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
1450
- var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:test|spec|bench)\.[^/]+$|(?:^|\/)test_[^/]+$|_test\.(?:go|py)$/;
1451
- var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
1452
- var LEADING_NEWLINE = /^\n/;
1453
- var GENERATED_HEADER = /@generated|generated by|do not edit/i;
1454
- var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\s\?(?![,):.?])/g;
1455
- var COMMENT_OR_STRING = /(\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*)|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/gm;
1456
- function isCandidate(path) {
1457
- return SOURCE.test(path) && !TESTS.test(path) && !GENERATED.test(path);
1458
- }
1459
- function isGenerated(text) {
1460
- return GENERATED_HEADER.test(text.slice(0, 400));
1461
- }
1462
- function complexityOf(text) {
1463
- return 1 + (text.replace(COMMENT_OR_STRING, (_, comment) => comment === undefined ? '""' : "").match(DECISION)?.length ?? 0);
1464
- }
1465
- async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
1466
- const [log, top] = await Promise.all([runCommand(["git", "log", `--since=${since}`, "--no-renames", "--numstat", "--format=%x01%ct%x02%ae", "-z"], { cwd }), runCommand(["git", "rev-parse", "--show-prefix"], { cwd })]);
1467
- if (log.code !== 0 || top.code !== 0)
1468
- return;
1469
- const prefix = top.text.trim();
1470
- const churn = new Map;
1471
- const authors = new Map;
1472
- for (const commit of log.text.split("\x01").slice(1)) {
1473
- const [head = "", ...entries] = commit.split("\x00");
1474
- const [stamp = "", author = ""] = head.split("\x02");
1475
- const all = entries.map((entry) => entry.replace(LEADING_NEWLINE, "")).filter((entry) => entry !== "").map((entry) => {
1476
- const [added = "", deleted = "", ...path] = entry.split("\t");
1477
- return { path: path.join("\t"), lines: (Number(added) || 0) + (Number(deleted) || 0) };
1478
- });
1479
- if (all.length > bulk)
1480
- continue;
1481
- const paths = all.filter(({ path }) => path.startsWith(prefix)).map(({ path, lines }) => ({ path: path.slice(prefix.length), lines }));
1482
- const age = Math.max(0, now - Number(stamp) * 1000);
1483
- const weight = halfLifeMs === 0 ? 1 : 0.5 ** (age / halfLifeMs);
1484
- for (const { path, lines } of paths) {
1485
- const seen = churn.get(path) ?? { commits: 0, weight: 0, lines: 0, linesWeight: 0, authors: 0 };
1486
- churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight, lines: seen.lines + lines, linesWeight: seen.linesWeight + lines * weight, authors: 0 });
1487
- authors.set(path, (authors.get(path) ?? new Set).add(author));
1488
- }
1489
- }
1490
- for (const [path, seen] of churn)
1491
- seen.authors = authors.get(path)?.size ?? 0;
1492
- return churn;
1493
- }
1494
-
1495
- // src/files.ts
1496
- import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
1497
- import { join as join6, relative } from "path";
1498
- var MAX_BYTES = 2000000;
1499
- var SNIFF_BYTES = 8000;
1500
- function walk(dir, found, ignored) {
1501
- let entries;
1502
- try {
1503
- entries = readdirSync(dir, { withFileTypes: true });
1504
- } catch {
1505
- return found;
1506
- }
1507
- for (const entry of entries) {
1508
- if (entry.name.startsWith(".") || ignored.has(entry.name))
1509
- continue;
1510
- if (entry.isDirectory())
1511
- walk(join6(dir, entry.name), found, ignored);
1512
- else if (entry.isFile())
1513
- found.push(join6(dir, entry.name));
1514
- }
1515
- return found;
1516
- }
1517
- async function listFiles(paths, cwd) {
1518
- const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
1519
- if (listed.code === 0)
1520
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync4(join6(cwd, path))).sort();
1521
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join6(cwd, path));
1522
- const ignored = ignoredFolders();
1523
- return roots.flatMap((root) => statSync2(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [], ignored)).map((path) => relative(cwd, path)).sort();
1524
- }
1525
- async function readText(path) {
1526
- const file = Bun.file(path);
1527
- try {
1528
- if (file.size > MAX_BYTES || (await file.slice(0, SNIFF_BYTES).bytes()).includes(0))
1529
- return;
1530
- return await file.text();
1531
- } catch {
1532
- return;
1533
- }
1534
- }
1535
-
1536
- // src/units.ts
1537
- var CONTAINER = /^(?:(?:export|default|declare|abstract|final|readonly|public|pub|private|protected|internal|sealed|data|open)\s+)*(?:class|impl|trait|interface|namespace|module|object|mod|struct|enum)\b/;
1538
- var CLOSER = /^[\s)\]};]*$|^\s*(?:\/\/|\/\*|\*|#)/;
1539
- var LONGEST_NAME2 = 60;
1540
- var MARKUP_BLOCK = /^<(template|style)\b[\s\S]*?\n<\/\1>/gm;
1541
- var KAY_FILE = /^---\n([\s\S]*?\n)---(?:\n|$)([\s\S]*)$/;
1542
- function blanked(text) {
1543
- return `
1544
- `.repeat(text.split(`
1545
- `).length - 1);
1546
- }
1547
- function indentOf(line) {
1548
- return line.length - line.trimStart().length;
1549
- }
1550
- function opens(line, indent) {
1551
- return line.trim() !== "" && line.trim() !== "{" && indentOf(line) === indent && !CLOSER.test(line);
1552
- }
1553
- function unitsAt(lines, from, to, indent) {
1554
- const starts = [];
1555
- for (let at = from;at < to; at++) {
1556
- if (opens(lines[at], indent))
1557
- starts.push(at);
1558
- }
1559
- return starts.flatMap((start, index) => {
1560
- const end = starts[index + 1] ?? to;
1561
- const header = lines[start].trim();
1562
- if (CONTAINER.test(header)) {
1563
- const inner = lines.slice(start + 1, end).filter((line) => line.trim() !== "").map(indentOf).filter((each) => each > indent);
1564
- const next = inner.length === 0 ? undefined : Math.min(...inner);
1565
- if (next !== undefined) {
1566
- const members = unitsAt(lines, start + 1, end, next);
1567
- if (members.length > 0)
1568
- return members;
1569
- }
1570
- }
1571
- return [{ name: header.length > LONGEST_NAME2 ? `${header.slice(0, LONGEST_NAME2 - 1)}\u2026` : header, line: start + 1, complexity: complexityOf(lines.slice(start, end).join(`
1572
- `)) }];
1573
- });
1574
- }
1575
- function worstUnit(text, path = "") {
1576
- const code = path.endsWith(".kay") ? text.replace(KAY_FILE, (_, script, template) => `
1577
- ${script}
1578
- ${blanked(template)}`) : text.replace(MARKUP_BLOCK, blanked);
1579
- const lines = code.split(`
1580
- `);
1581
- const top = unitsAt(lines, 0, lines.length, 0);
1582
- return top.reduce((worst, unit) => worst === undefined || unit.complexity > worst.complexity ? unit : worst, undefined);
1583
- }
1584
-
1585
- // src/hotspots.ts
1586
- var SETTINGS = readUserConfig("hotspots");
1587
- var DEFAULT_SINCE = typeof SETTINGS.since === "string" && SETTINGS.since !== "" ? SETTINGS.since : "6 months ago";
1588
- var DEFAULT_BULK = configuredNumber("hotspots", "bulk", 25);
1589
- var DAY_MS2 = 86400000;
1590
- var DEFAULT_HALF_LIFE = "90d";
1591
- var DEFAULT_COUNT = configuredNumber("hotspots", "limit", 20);
1592
- var USAGE = `hotspots [options] [dir]: ranks the source files under dir (here by default) by complexity times churn, the ones both hard to read and often edited first, honouring .gitignore
1593
-
1594
- Complexity is the count of decision points in the file (branches, loops, cases, catches, boolean operators, ternaries) plus one, churn the commits touching it since --since (${DEFAULT_SINCE}), score their product. A commit counts for less the older it is (half as much every --half-life, 0 for all alike) and a commit touching more than --bulk files, a format or rename sweep, is left out. --by-lines scores the lines changed instead of the commits. Each file also shows how many lines changed, its author count ("solo" when one author wrote every change) and its most complex declaration, found by indentation. Test files and generated or built files are left out unless --all.
1595
-
1596
- Lists at most ${DEFAULT_COUNT} files, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.`;
1597
- var EXITS = [[0, "it ranked the files"], [1, "no file has commits in the window"], [2, "a usage error or outside a git repository"]];
1598
- var OPTIONS = {
1599
- since: { type: "string", short: "s", description: `only count the commits since this date, as git reads it (${DEFAULT_SINCE})` },
1600
- "half-life": { type: "string", description: `how long until a commit counts half as much (${DEFAULT_HALF_LIFE}), 0 for no decay` },
1601
- bulk: { type: "string", description: `leave out the commits touching more files than this (${DEFAULT_BULK})` },
1602
- ...limitOptions(DEFAULT_COUNT),
1603
- all: { type: "boolean", short: "a", description: "keep test files and generated files" },
1604
- "by-lines": { type: "boolean", description: "score complexity times the lines changed (decayed like the commits) instead of the commits" },
1605
- json: jsonOption("[{rank, path, score, churn, recent, changed, authors, solo, complexity, worst, lines}], never cut unless --limit is given; changed counts the lines added and deleted, solo being true for a file one author edited")
1606
- };
1607
- var HOT = 0.66;
1608
- var WARM = 0.33;
1609
- async function hotspots(args) {
1610
- const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
1611
- if (positionals.length > 1)
1612
- badUsage("give one folder");
1613
- const count = limitOf(values, DEFAULT_COUNT);
1614
- const cwd = process16.cwd();
1615
- const bulk = Number(values.bulk ?? DEFAULT_BULK);
1616
- if (!Number.isInteger(bulk) || bulk < 1)
1617
- badUsage(`--bulk takes a number of files, not ${values.bulk}`);
1618
- const halfLifeMs = values["half-life"] === "0" ? 0 : duration(values["half-life"], "half-life", 90 * DAY_MS2);
1619
- const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE, { bulk, halfLifeMs });
1620
- if (churn === undefined)
1621
- fail("not a git repository, churn comes from its log");
1622
- const ranked = [];
1623
- for (const path of await listFiles(positionals[0] === undefined ? [] : [positionals[0]], cwd)) {
1624
- const touched = churn.get(path);
1625
- if (touched === undefined || values.all !== true && !isCandidate(path))
1626
- continue;
1627
- const text = await readText(join7(cwd, path));
1628
- if (text === undefined || values.all !== true && isGenerated(text))
1629
- continue;
1630
- const complexity = complexityOf(text);
1631
- const worst = worstUnit(text, path);
1632
- ranked.push({ path, score: Math.round(complexity * (values["by-lines"] === true ? touched.linesWeight : touched.weight)), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, changed: touched.lines, authors: touched.authors, solo: touched.authors === 1, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
1633
- `).length - (text.endsWith(`
1634
- `) ? 1 : 0) });
1635
- }
1636
- if (ranked.length === 0)
1637
- fail("no file with commits in that window", 1);
1638
- ranked.sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));
1639
- const { shown: kept, footer } = capped(ranked, count);
1640
- const shown = kept.map((hotspot, index) => ({ rank: index + 1, ...hotspot }));
1641
- if (values.json === true) {
1642
- printJson(shown);
1643
- return 0;
1644
- }
1645
- const colors = paint(process16.stdout);
1646
- const path = role("path", process16.stdout);
1647
- const top = shown.reduce((highest, row) => Math.max(highest, row.score), 0);
1648
- const heat = (score, text) => {
1649
- if (top > 0 && score >= top * HOT)
1650
- return colors.red(text);
1651
- return top > 0 && score >= top * WARM ? colors.yellow(text) : text;
1652
- };
1653
- printHeader("hotspots", `${basename(cwd)} \xB7 since ${values.since ?? DEFAULT_SINCE}`);
1654
- console.log(table([["rank", "score", "churn", "recent", "changed", "authors", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.changed].map(String), row.solo ? colors.dim("1 solo") : String(row.authors), ...[row.complexity, row.lines].map(String), fileLink(path(row.path), row.path, process16.stdout, cwd), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "right", "right", "left", "left"] }));
1655
- if (footer !== undefined)
1656
- console.log(footer);
1657
- return 0;
1658
- }
1659
-
1660
- // src/hotspots-cli.ts
1661
- process17.exitCode = await runMain({ name: "hotspots", run: hotspots });