@kaynooo/cli-env 0.14.1 → 0.15.1

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/redact.js DELETED
@@ -1,1917 +0,0 @@
1
- #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
- // @bun
3
-
4
- // src/redact.ts
5
- import process18 from "process";
6
- // ../kit/src/args.ts
7
- import process10 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 N = new Map;
15
- var Nt = /\s+\S*$/;
16
- var Y = /\s/;
17
- function ko(t, e, r = "...") {
18
- let { suffix: n = "...", includeSuffix: s = false, wordBoundary: o = false } = typeof r === "string" ? { suffix: r } : r;
19
- if (t.length <= e)
20
- return t;
21
- let l = Math.max(0, e), c = t.substring(0, Math.max(0, s ? l - n.length : l));
22
- if (o && !Y.test(t[c.length] ?? " "))
23
- c = c.replace(Nt, "") || c;
24
- if (o)
25
- c = c.trimEnd();
26
- return s ? (c + n).slice(0, l) : c + n;
27
- }
28
- 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));
29
- var z = new Map;
30
-
31
- // ../kit/src/mode.ts
32
- import process2 from "process";
33
- var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
34
- var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
35
- function isSet(value) {
36
- return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
37
- }
38
- function outputMode(stream = process2.stdout, env = process2.env) {
39
- const chosen = env.KIT_MODE;
40
- if (chosen !== undefined && MODES.has(chosen))
41
- return chosen;
42
- if (AGENT_VARIABLES.some((name) => isSet(env[name])))
43
- return "agent";
44
- if (stream.isTTY === true)
45
- return "terminal";
46
- return isSet(env.CI) ? "ci" : "pipe";
47
- }
48
- function isInteractive(streams = process2) {
49
- return streams.stdin?.isTTY === true && streams.stderr?.isTTY === true;
50
- }
51
-
52
- // ../kit/src/style.ts
53
- import process6 from "process";
54
-
55
- // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
56
- var G2 = /^[a-f0-9]+$/i;
57
- function b(r) {
58
- let e = r.startsWith("#") ? r.slice(1) : r;
59
- if (!G2.test(e))
60
- return [0, 0, 0];
61
- if (e.length === 3 || e.length === 4)
62
- return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
63
- if (e.length !== 6 && e.length !== 8)
64
- throw Error(`Invalid hex color length: ${e.length}`);
65
- return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
66
- }
67
- 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") => {
68
- let [l, n, c] = b(r);
69
- return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
70
- }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
71
- var h = new Set(["", "1", "2", "3", "true"]);
72
- function C(r, e = globalThis.process?.env ?? {}) {
73
- if (e.FORCE_COLOR !== undefined)
74
- return h.has(e.FORCE_COLOR);
75
- if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
76
- return false;
77
- return r?.isTTY === true;
78
- }
79
- function f(r, e = []) {
80
- let l = "", n = "";
81
- for (let t = 0, i = e.length;t < i; t++)
82
- l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
83
- let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
84
- return new Proxy(c, { get(t, i) {
85
- let a = B2[i];
86
- if (Array.isArray(a)) {
87
- let s = g.get(i);
88
- if (s === undefined)
89
- s = f(r, [...e, a]), g.set(i, s);
90
- return s;
91
- }
92
- if (typeof a === "function")
93
- return (...s) => {
94
- let y = `${i}:${s.join(",")}`, u = g.get(y);
95
- if (u === undefined) {
96
- if (g.size >= 64)
97
- g.clear();
98
- u = f(r, [...e, a(...s)]), g.set(y, u);
99
- }
100
- return u;
101
- };
102
- throw Error(`Unknown style: ${String(i)}`);
103
- } });
104
- }
105
- function Fe(r = {}) {
106
- return f(r);
107
- }
108
- var o = Fe();
109
-
110
- // ../kit/src/theme.ts
111
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
112
- import { homedir as homedir2 } from "os";
113
- import { join as join3, resolve as resolve2 } from "path";
114
- import process5 from "process";
115
-
116
- // ../kit/src/config.ts
117
- import { existsSync } from "fs";
118
- import { dirname, join, resolve } from "path";
119
- import process3 from "process";
120
- function findUp(names, from = process3.cwd(), stop = () => false) {
121
- const wanted = typeof names === "string" ? [names] : names;
122
- for (let dir = resolve(from);; dir = dirname(dir)) {
123
- const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
124
- if (found !== undefined)
125
- return found;
126
- if (stop(dir) || dirname(dir) === dir)
127
- return;
128
- }
129
- }
130
-
131
- // ../kit/src/user-config.ts
132
- import { existsSync as existsSync2, readFileSync } from "fs";
133
- import { homedir } from "os";
134
- import { join as join2 } from "path";
135
- import process4 from "process";
136
- function configBase(where = {}) {
137
- const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
138
- return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
139
- }
140
- function userConfigPath(bin, where = {}) {
141
- return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
142
- }
143
- function userConfigReadPath(bin, legacy = [], where = {}) {
144
- const current = userConfigPath(bin, where);
145
- if (existsSync2(current))
146
- return current;
147
- const base = configBase(where);
148
- return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
149
- }
150
- function readUserConfig(bin, where = {}, legacy = []) {
151
- const path = userConfigReadPath(bin, legacy, where);
152
- if (!existsSync2(path))
153
- return {};
154
- try {
155
- const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
156
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
157
- } catch {
158
- return {};
159
- }
160
- }
161
-
162
- // ../kit/src/theme.ts
163
- var ENDS = new Map;
164
- var DEFAULT = {
165
- 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" },
166
- 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" },
167
- accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
168
- bins: {},
169
- gradient: ["#c084fc", "#67e8f9"]
170
- };
171
- 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" };
172
- 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" };
173
- var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
174
- var PRESETS = {
175
- default: {},
176
- "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
177
- mono: { colors: MONO, accents: ["bold"], gradient: undefined },
178
- ascii: { glyphs: ASCII }
179
- };
180
- 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"]);
181
- var HEX = /^#[0-9a-f]{6}$/i;
182
- var CONTROL = /\p{Cc}/u;
183
- var MAX_FILE_BYTES = 64 * 1024;
184
- var SPACES = /\s+/;
185
- function isColorSpec(spec) {
186
- if (typeof spec === "number")
187
- return Number.isInteger(spec) && spec >= 0 && spec <= 255;
188
- return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
189
- }
190
- var CUBE = [0, 95, 135, 175, 215, 255];
191
- function cubeLevel(channel) {
192
- return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
193
- }
194
- function nearest256(hex) {
195
- const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
196
- const levels = rgb.map(cubeLevel);
197
- const cube = levels.map((level) => CUBE[level]);
198
- const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
199
- const greyValue = 8 + grey * 10;
200
- const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
201
- return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
202
- }
203
- function hasTrueColor(env) {
204
- return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
205
- }
206
- function tinted(colors, spec, env = process5.env) {
207
- if (typeof spec === "number")
208
- return colors.ansi256(spec);
209
- return spec.trim().split(SPACES).reduce((chain, token) => {
210
- if (HEX.test(token))
211
- return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
212
- return chain[token] ?? chain;
213
- }, colors);
214
- }
215
- function isRecord(value) {
216
- return typeof value === "object" && value !== null && !Array.isArray(value);
217
- }
218
- function readThemeFile(path, warn) {
219
- try {
220
- const stat = statSync(path, { throwIfNoEntry: false });
221
- if (stat === undefined)
222
- return;
223
- if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
224
- warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
225
- return;
226
- }
227
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
228
- if (isRecord(parsed))
229
- return parsed;
230
- warn(`${path} is not a JSON object, theme ignored`);
231
- } catch (error) {
232
- warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
233
- }
234
- return;
235
- }
236
- function applyPreset(theme, name, warn, where) {
237
- if (name === undefined)
238
- return;
239
- if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
240
- warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
241
- return;
242
- }
243
- const preset = PRESETS[name];
244
- Object.assign(theme.colors, preset.colors);
245
- Object.assign(theme.glyphs, preset.glyphs);
246
- if (preset.accents !== undefined)
247
- theme.accents = [...preset.accents];
248
- if (Object.hasOwn(preset, "gradient"))
249
- theme.gradient = preset.gradient;
250
- return name;
251
- }
252
- function applyFile(theme, file, where, warn) {
253
- if (isRecord(file.colors)) {
254
- for (const [key, value] of Object.entries(file.colors)) {
255
- if (!Object.hasOwn(DEFAULT.colors, key))
256
- warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
257
- else if (!isColorSpec(value))
258
- warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
259
- else
260
- theme.colors[key] = value;
261
- }
262
- }
263
- if (isRecord(file.glyphs)) {
264
- for (const [key, value] of Object.entries(file.glyphs)) {
265
- if (!Object.hasOwn(DEFAULT.glyphs, key))
266
- warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
267
- else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
268
- warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
269
- else
270
- theme.glyphs[key] = value;
271
- }
272
- }
273
- if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
274
- theme.accents = [...file.accents];
275
- else if (file.accents !== undefined)
276
- warn(`${where}: accents must be a non-empty list of colours`);
277
- if (file.gradient === null)
278
- theme.gradient = undefined;
279
- else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
280
- theme.gradient = [file.gradient[0], file.gradient[1]];
281
- else if (file.gradient !== undefined)
282
- warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
283
- if (isRecord(file.bins)) {
284
- for (const [bin, value] of Object.entries(file.bins)) {
285
- if (isColorSpec(value))
286
- theme.bins[bin] = value;
287
- else
288
- warn(`${where}: bin ${bin} has no valid colour`);
289
- }
290
- }
291
- }
292
- function endsWalk(home) {
293
- return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
294
- }
295
- var warned = new Set;
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
- var current;
333
- var currentKey = "";
334
- function activeTheme() {
335
- const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
336
- if (current === undefined || key !== currentKey) {
337
- current = loadTheme();
338
- currentKey = key;
339
- }
340
- return current;
341
- }
342
-
343
- // ../kit/src/style.ts
344
- var MARK_WORDS = { ok: "ok:", warn: "warning:", problem: "error:", note: "note:", plan: "would:" };
345
- function takesControlCodes(stream, env = process6.env) {
346
- return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
347
- }
348
- function paint(stream, env = process6.env) {
349
- return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
350
- }
351
- function marked(mark, text, stream, detail, env = process6.env) {
352
- const colors = paint(stream, env);
353
- let head = MARK_WORDS[mark];
354
- if (takesControlCodes(stream, env)) {
355
- const { theme } = activeTheme();
356
- head = tinted(colors.bold, theme.colors[mark], env)(theme.glyphs[mark]);
357
- }
358
- return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
359
- }
360
- function ok(text, detail) {
361
- console.log(marked("ok", text, process6.stdout, detail));
362
- }
363
- function warn(text, detail) {
364
- console.error(marked("warn", text, process6.stderr, detail));
365
- }
366
- function role(name, stream, env = process6.env) {
367
- const colors = paint(stream, env);
368
- return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
369
- }
370
- var STATUS_WORDS = {
371
- passed: ["passed", "success", "succeeded", "ok"],
372
- failed: ["failed", "failure", "error", "errored"],
373
- running: ["running", "in_progress", "started", "holding"],
374
- queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
375
- skipped: ["skipped", "cancelled", "canceled", "manual"]
376
- };
377
- var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
378
-
379
- // ../kit/src/format.ts
380
- var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
381
- function formatSeconds(total) {
382
- let rest = Math.max(0, Math.round(total));
383
- const amounts = UNITS.map(([unit, size]) => {
384
- const amount = Math.floor(rest / size);
385
- rest -= amount * size;
386
- return `${amount}${unit}`;
387
- });
388
- const first = amounts.findIndex((amount) => !amount.startsWith("0"));
389
- if (first === -1)
390
- return "0s";
391
- const next = amounts[first + 1];
392
- return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
393
- }
394
- function formatDuration(ms) {
395
- return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
396
- }
397
- function upTo(text, separator) {
398
- const end = text.indexOf(separator);
399
- return end === -1 ? text : text.slice(0, end);
400
- }
401
- function truncate(text, width) {
402
- return ko(text, width, { suffix: "\u2026", includeSuffix: true });
403
- }
404
- var LINE_BREAKS = /\s*\n\s*/g;
405
- var ESCAPE = String.fromCharCode(27);
406
- function textWidth(text) {
407
- return Bun.stringWidth(text);
408
- }
409
- function table(rows, { cellWidth, header = false, align = [], fit, stream = process7.stdout, env = process7.env } = {}) {
410
- const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
411
- if (outputMode(stream, env) === "agent")
412
- return cells.map((row) => row.map((cell) => Bun.stripANSI(cell).replaceAll(/[\t\r\n]+/g, " ")).join("\t")).join(`
413
- `);
414
- const widths = [];
415
- for (const row of cells) {
416
- for (const [index, cell] of row.entries())
417
- widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
418
- }
419
- const shown = fit === undefined ? cells : narrow(cells, widths, fit);
420
- const colors = paint(stream);
421
- const lines = shown.map((row) => row.map((cell, index) => {
422
- const width = widths[index] ?? 0;
423
- const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
424
- if (align[index] === "right")
425
- return `${gap}${cell}`;
426
- return index === row.length - 1 ? cell : `${cell}${gap}`;
427
- }).join(" ").trimEnd());
428
- const rule = header && takesControlCodes(stream) && lines.length > 1 ? [colors.dim("\u2500".repeat(Math.max(...lines.map(textWidth))))] : [];
429
- return lines.flatMap((line, index) => header && index === 0 ? [colors.bold(line), ...rule] : [line]).join(`
430
- `);
431
- }
432
- function narrow(rows, widths, limit) {
433
- const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
434
- const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
435
- const floor = 8;
436
- while (used() > limit) {
437
- let widest = -1;
438
- for (const [index, width] of widths.entries()) {
439
- if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
440
- widest = index;
441
- }
442
- if (widest === -1)
443
- break;
444
- widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
445
- }
446
- return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
447
- }
448
- function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
449
- return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
450
- }
451
- function printJson(value) {
452
- console.log(jsonText(value));
453
- }
454
-
455
- // ../kit/src/help.ts
456
- import process8 from "process";
457
- var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
458
- var USAGE_PREFIX = /^usage:\s*/i;
459
- var FULL_STOP = /\.$/;
460
- function usageLine(usage, colors = paint(process8.stdout)) {
461
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
462
- }
463
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
464
- return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
465
- `);
466
- }
467
- function exitRows(exits, colors = paint(process8.stdout)) {
468
- if (exits.length === 0)
469
- return [];
470
- return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
471
- }
472
- function wantsHelpJson(env = process8.env) {
473
- return env.KIT_HELP === "json";
474
- }
475
- function description(usage, { examples = [], replaces, exits } = {}, options) {
476
- const lines = usage.replace(USAGE_PREFIX, "").split(`
477
- `);
478
- const first = lines[0];
479
- const colon = first.indexOf(": ");
480
- const prose = lines[lines.indexOf("") + 1] ?? "";
481
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
482
- return {
483
- synopsis: colon === -1 ? first : first.slice(0, colon),
484
- summary: colon === -1 ? fallback : first.slice(colon + 2),
485
- ...replaces === undefined ? {} : { replaces },
486
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
487
- ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
488
- ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
489
- };
490
- }
491
- function exampleRows(examples, colors = paint(process8.stdout)) {
492
- if (examples.length === 0 || outputMode() === "agent")
493
- return [];
494
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
495
- }
496
- var MAX_INLINE_CHOICES = 24;
497
- function optionRows(options, colors = paint(process8.stdout)) {
498
- const rows = Object.entries(options).map(([name, option]) => {
499
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
500
- const choices = option.choices?.join("|");
501
- const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
502
- const named = inline ? `<${choices}>` : "<value>";
503
- const placeholder = option.optional === undefined ? named : `[${named}]`;
504
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
505
- const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
506
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
507
- });
508
- const width = Math.max(0, ...rows.map((row) => row.width));
509
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
510
- }
511
-
512
- // ../kit/src/text.ts
513
- function distance(a, b) {
514
- const left = [...a];
515
- const right = [...b];
516
- let before = [];
517
- let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
518
- for (const [i, x] of left.entries()) {
519
- const current = [i + 1];
520
- for (const [j, y] of right.entries()) {
521
- let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
522
- if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
523
- cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
524
- current.push(cost);
525
- }
526
- before = previous;
527
- previous = current;
528
- }
529
- return previous[right.length] ?? 0;
530
- }
531
- function closest(name, names) {
532
- const started = names.find((known) => known.startsWith(name));
533
- if (started !== undefined)
534
- return started;
535
- const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
536
- return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
537
- }
538
- // ../kit/src/input.ts
539
- import process9 from "process";
540
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
541
- if (path === "-") {
542
- if (process9.stdin.isTTY)
543
- fail(noStdin);
544
- return Bun.stdin.text();
545
- }
546
- const file = Bun.file(path);
547
- if (!await file.exists())
548
- fail(`no file ${path}`);
549
- return file.text();
550
- }
551
-
552
- // ../kit/src/args.ts
553
- var DASHES = /^-+/;
554
- function jsonOption(holds) {
555
- return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
556
- }
557
- class Exit extends Error {
558
- code;
559
- hint;
560
- constructor(message, code, hint) {
561
- super(message);
562
- this.code = code;
563
- this.hint = hint;
564
- }
565
- }
566
- function fail(message, code = 2, hint) {
567
- throw new Exit(message, code, hint);
568
- }
569
-
570
- class UsageError extends Exit {
571
- constructor(message, hint) {
572
- super(message, 2, hint);
573
- }
574
- }
575
- function badUsage(message) {
576
- throw new UsageError(message);
577
- }
578
-
579
- class HelpShown extends Exit {
580
- constructor() {
581
- super("help shown", 0);
582
- }
583
- }
584
-
585
- class Completing {
586
- options;
587
- positionals;
588
- candidates;
589
- constructor(options, positionals = [], candidates = {}) {
590
- this.options = options;
591
- this.positionals = positionals;
592
- this.candidates = candidates;
593
- }
594
- }
595
- var completion = { active: false };
596
- var OUTPUT_OPTIONS = {
597
- color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
598
- plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
599
- };
600
- function applyOutput(color, plain, env = process10.env) {
601
- const when = plain === true ? "never" : color ?? "auto";
602
- if (when === "auto")
603
- return;
604
- if (when !== "always" && when !== "never")
605
- badUsage(`--color takes auto, always or never, not ${when}`);
606
- if (when === "always") {
607
- env.FORCE_COLOR = "1";
608
- delete env.NO_COLOR;
609
- } else {
610
- env.NO_COLOR = "1";
611
- delete env.FORCE_COLOR;
612
- }
613
- }
614
- function parse(args, usage, options, settings = {}) {
615
- const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
616
- const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
617
- const listing = listed(all, settings.allowNegative === true);
618
- if (completion.active)
619
- throw new Completing(listing, settings.positionals, settings.candidates);
620
- const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
621
- let parsed;
622
- try {
623
- parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
624
- } catch (error) {
625
- const message = parseError(error);
626
- throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
627
- }
628
- const values = parsed.values;
629
- applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
630
- if (values.help === true) {
631
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
632
- throw new HelpShown;
633
- }
634
- checkChoices(parsed.values, all);
635
- checkConflicts(parsed.values, all);
636
- if (settings.positionals !== undefined)
637
- checkPositionals(parsed.positionals, settings.positionals);
638
- return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
639
- }
640
- function splitRest(args, passes) {
641
- const separator = passes ? args.indexOf("--") : -1;
642
- return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
643
- }
644
- function splitTrailing(args, options, count) {
645
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
646
- let seen = 0;
647
- if (count === 0)
648
- return { own: args, rest: undefined };
649
- for (let at = 0;at < args.length; at++) {
650
- const word = args[at];
651
- if (word === "--")
652
- break;
653
- if (word.startsWith("-")) {
654
- if (takesValue(word))
655
- at++;
656
- continue;
657
- }
658
- seen++;
659
- if (seen === count)
660
- return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
661
- }
662
- return { own: args, rest: undefined };
663
- }
664
- function listed(options, allowNegative) {
665
- if (!allowNegative)
666
- return options;
667
- return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
668
- if (option.type !== "boolean" || option.negative === undefined)
669
- return [[name, option]];
670
- return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
671
- }));
672
- }
673
- function withAliases(args, options) {
674
- const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
675
- if (named.size === 0)
676
- return args;
677
- const separator = args.indexOf("--");
678
- const own = separator === -1 ? args : args.slice(0, separator);
679
- return [...own.map((arg) => {
680
- const at = arg.indexOf("=");
681
- const current = named.get(at === -1 ? arg : arg.slice(0, at));
682
- return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
683
- }), ...separator === -1 ? [] : args.slice(separator)];
684
- }
685
- function withBare(args, options) {
686
- const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
687
- if (bare.size === 0)
688
- return args;
689
- const separator = args.indexOf("--");
690
- const own = separator === -1 ? args : args.slice(0, separator);
691
- return [...own.flatMap((arg, index) => {
692
- const optional = bare.get(arg);
693
- const next = own[index + 1];
694
- const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
695
- return optional === undefined || value ? [arg] : [arg, optional.bare];
696
- }), ...separator === -1 ? [] : args.slice(separator)];
697
- }
698
- function checkConflicts(values, options) {
699
- const given = (name) => values[name] !== undefined && values[name] !== false;
700
- for (const [name, { conflicts = [] }] of Object.entries(options)) {
701
- const other = given(name) ? conflicts.find(given) : undefined;
702
- if (other !== undefined)
703
- badUsage(`--${name} cannot be used with --${other}`);
704
- }
705
- }
706
- function checkChoices(values, options) {
707
- for (const [name, option] of Object.entries(options)) {
708
- if (option.choices === undefined)
709
- continue;
710
- const given = values[name];
711
- for (const value of Array.isArray(given) ? given : [given]) {
712
- if (typeof value === "string")
713
- oneOf(value, name, option.choices);
714
- }
715
- }
716
- }
717
- function oneOf(value, name, choices) {
718
- if (!choices.includes(value))
719
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
720
- return value;
721
- }
722
- function checkPositionals(given, names) {
723
- const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
724
- const required = names.filter((name) => !name.startsWith("[")).length;
725
- if (given.length < required)
726
- badUsage(`missing ${names[given.length]}`);
727
- if (!variadic && given.length > names.length)
728
- badUsage(`unexpected argument ${given[names.length]}`);
729
- }
730
- function joinDashValues(args, options) {
731
- const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
732
- const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
733
- const joined = [];
734
- for (let i = 0;i < args.length; i++) {
735
- const arg = args[i] ?? "";
736
- if (arg === "--")
737
- return [...joined, ...args.slice(i)];
738
- const name = longOf.get(arg);
739
- const next = args[i + 1];
740
- if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
741
- joined.push(`--${name}=${next}`);
742
- i++;
743
- } else {
744
- joined.push(arg);
745
- }
746
- }
747
- return joined;
748
- }
749
- function parseError(error) {
750
- const message = upTo(error instanceof Error ? error.message : String(error), ". ");
751
- return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
752
- }
753
- var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
754
- function nearestOption(message, options, allowNegative) {
755
- const typed = UNKNOWN_OPTION.exec(message)?.[1];
756
- if (typed === undefined)
757
- return;
758
- const word = typed.replace(DASHES, "");
759
- if (word.length < 2 && !typed.startsWith("--"))
760
- return;
761
- const known = Object.entries(options).flatMap(([name, option]) => [
762
- ...option.short === undefined ? [] : [`-${option.short}`],
763
- `--${name}`,
764
- ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
765
- ]);
766
- const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
767
- return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
768
- }
769
- // ../kit/src/argv.ts
770
- import { readFileSync as readFileSync3, realpathSync } from "fs";
771
- import { resolve as resolve3 } from "path";
772
- import process11 from "process";
773
- function commandLine() {
774
- try {
775
- return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
776
- } catch {
777
- return;
778
- }
779
- }
780
- function realPath(word) {
781
- try {
782
- return realpathSync(resolve3(word));
783
- } catch {
784
- return;
785
- }
786
- }
787
- function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
788
- const target = script === undefined ? undefined : realPath(script) ?? script;
789
- const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
790
- const after = at === -1 ? [] : cmdline.slice(at + 1);
791
- return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
792
- }
793
- // ../kit/src/progress.ts
794
- var ESC = String.fromCharCode(27);
795
- var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
796
- var RESET_STYLE = `${ESC}[0m`;
797
- var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
798
- // ../kit/src/cli.ts
799
- import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
800
- import { dirname as dirname3, join as join5 } from "path";
801
- import process14 from "process";
802
-
803
- // ../kit/src/completions.ts
804
- var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
805
- 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'
806
- set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
807
- set -l current (commandline -ct)
808
- for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
809
- if test "$line" = __files__
810
- __fish_complete_path $current
811
- else
812
- echo $line
813
- end
814
- end
815
- end`;
816
- var BASH_FUNCTION = `__kaynooo_cli_complete() {
817
- local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
818
- local -a lines
819
- COMPREPLY=()
820
- lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
821
- for line in "\${lines[@]}"; do
822
- if [[ $line == __files__ ]]; then
823
- COMPREPLY+=($(compgen -f -- "$cur"))
824
- else
825
- words+="\${line%%$'\\t'*}"$'\\n'
826
- fi
827
- done
828
- COMPREPLY+=($(compgen -W "$words" -- "$cur"))
829
- }`;
830
- var ZSH_FUNCTION = `__kaynooo_cli_complete() {
831
- local line
832
- local -a described plain
833
- for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
834
- if [[ $line == __files__ ]]; then
835
- _files
836
- elif [[ $line == *$'\\t'* ]]; then
837
- described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
838
- else
839
- plain+=("$line")
840
- fi
841
- done
842
- (( \${#described} )) && _describe -V value described
843
- (( \${#plain} )) && compadd -- "\${plain[@]}"
844
- return 0
845
- }`;
846
- function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
847
- if (shell === "fish")
848
- return `${header}
849
- ${FISH_FUNCTION}
850
- ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
851
- `).join("")}`;
852
- if (shell === "bash")
853
- return `${header}
854
- ${BASH_FUNCTION}
855
- complete -F __kaynooo_cli_complete ${bins.join(" ")}
856
- `;
857
- return `${header}
858
- ${ZSH_FUNCTION}
859
- compdef __kaynooo_cli_complete ${bins.join(" ")}
860
- `;
861
- }
862
-
863
- // ../kit/src/notify.ts
864
- import process12 from "process";
865
- var NOTIFY_AFTER_MS = 1e4;
866
- var CANCELLED = 130;
867
- function base64(text) {
868
- return Buffer.from(text).toString("base64");
869
- }
870
- function notification(title, body, env = process12.env) {
871
- const id = `kit${process12.pid}`;
872
- 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\\`];
873
- return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
874
- }
875
- function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
876
- if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
877
- return;
878
- stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
879
- }
880
-
881
- // ../kit/src/usage.ts
882
- import { appendFileSync, mkdirSync } from "fs";
883
- import { homedir as homedir3 } from "os";
884
- import { dirname as dirname2, isAbsolute, join as join4 } from "path";
885
- import process13 from "process";
886
-
887
- // ../kit/src/logs.ts
888
- var DAY_MS = 24 * 60 * 60 * 1000;
889
- var CLI_FOLDER = "kaynooo-cli";
890
-
891
- // ../kit/src/usage.ts
892
- var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
893
- var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
894
- var LONGEST_NAME = 40;
895
- var usageError;
896
- function noteUsageError(message) {
897
- usageError = message;
898
- }
899
- function stateHome(env = process13.env) {
900
- const dir = env.XDG_STATE_HOME;
901
- return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
902
- }
903
- function usagePath(env = process13.env) {
904
- return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
905
- }
906
- function usageRecorded(env = process13.env) {
907
- const off = env.KAYNOOO_CLI_NO_USAGE;
908
- return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
909
- }
910
- function flagNames(argv) {
911
- const end = argv.indexOf("--");
912
- const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
913
- return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
914
- }
915
- function usageEntry(bin, command, argv, code, now = new Date) {
916
- const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
917
- usageError = undefined;
918
- return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
919
- }
920
- function recordUsage(entry, env = process13.env) {
921
- if (!usageRecorded(env))
922
- return;
923
- try {
924
- const path = usagePath(env);
925
- mkdirSync(dirname2(path), { recursive: true, mode: 448 });
926
- appendFileSync(path, `${JSON.stringify(entry)}
927
- `, { mode: 384 });
928
- } catch {}
929
- }
930
-
931
- // ../kit/src/cli.ts
932
- var LEVEL_OPTIONS = {
933
- ...OUTPUT_OPTIONS,
934
- help: { type: "boolean", short: "h", description: "show this help" }
935
- };
936
- var TOP_OPTIONS = {
937
- ...LEVEL_OPTIONS,
938
- version: { type: "boolean", short: "v", description: "print the version" },
939
- completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
940
- };
941
- async function commandRows(all, colors) {
942
- const commands = shown(all);
943
- const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
944
- const groups = new Map([["Commands:", []]]);
945
- const summaries = await Promise.all(Object.values(commands).map(async ({ summary }) => resolveSummary(summary)));
946
- for (const [index, [name, { group }]] of Object.entries(commands).entries()) {
947
- const heading = group === undefined ? "Commands:" : `${group}:`;
948
- const rows = groups.get(heading) ?? [];
949
- rows.push(` ${colors.cyan(name.padEnd(width))} ${colors.dim(summaries[index])}`);
950
- groups.set(heading, rows);
951
- }
952
- return [...groups].filter(([, rows]) => rows.length > 0).flatMap(([heading, rows], index) => [...index === 0 ? [] : [""], colors.bold(heading), ...rows]);
953
- }
954
- function shown(commands) {
955
- return Object.fromEntries(Object.entries(commands).filter(([, { hidden }]) => hidden !== true));
956
- }
957
- function takeOutputFlags(argv) {
958
- let index = 0;
959
- for (;index < argv.length; index++) {
960
- const word = argv[index];
961
- if (word === "--plain")
962
- applyOutput(undefined, true);
963
- else if (word.startsWith("--color="))
964
- applyOutput(word.slice("--color=".length), undefined);
965
- else if (word === "--color" && argv[index + 1] !== undefined)
966
- applyOutput(argv[++index], undefined);
967
- else
968
- break;
969
- }
970
- return argv.slice(index);
971
- }
972
- async function resolveSummary(summary) {
973
- return typeof summary === "string" ? summary : summary();
974
- }
975
- function scopeOf(commands, extra, aliases) {
976
- return { commands: typeof commands === "function" ? {} : commands, lazy: [...typeof commands === "function" ? [commands] : [], ...extra === undefined ? [] : [extra]], aliases };
977
- }
978
- async function expand(scope, words) {
979
- if (scope.lazy.length === 0)
980
- return scope;
981
- const commands = { ...scope.commands };
982
- for (const added of await Promise.all(scope.lazy.map(async (lazy) => lazy(words)))) {
983
- for (const [name, command] of Object.entries(added))
984
- commands[name] ??= command;
985
- }
986
- return { ...scope, commands, lazy: [] };
987
- }
988
- async function help2({ path, header, summary: lazySummary, commands, defaultCommand, examples, replaces }, stream) {
989
- const colors = paint(stream);
990
- const prefix = path.join(" ");
991
- const summary = await resolveSummary(lazySummary);
992
- if (wantsHelpJson())
993
- return JSON.stringify(description(`${prefix} <command> [options]: ${summary}`, { examples, replaces }));
994
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
995
- const options = fallback !== undefined && "run" in fallback ? await optionsOf(fallback.run) : undefined;
996
- const own = Object.entries(options ?? {}).filter(([name]) => !(name in TOP_OPTIONS));
997
- return [
998
- header(colors, summary),
999
- "",
1000
- usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1001
- "",
1002
- ...await commandRows(commands, colors),
1003
- ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
1004
- "",
1005
- colors.bold("Options:"),
1006
- ...optionRows(path.length === 1 ? TOP_OPTIONS : LEVEL_OPTIONS, colors),
1007
- ...exampleRows(examples ?? [], colors),
1008
- "",
1009
- `${colors.dim("Run")} ${prefix} ${colors.cyan("<command>")} --help ${colors.dim("for its options.")}`
1010
- ].join(`
1011
- `);
1012
- }
1013
- function printError(prefix, message, hint, cause) {
1014
- const colors = paint(process14.stderr);
1015
- const styled = takesControlCodes(process14.stderr);
1016
- const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1017
- const under = (label, text, tint) => text === undefined ? "" : `
1018
- ${styled ? tint(label) : `${label}:`} ${text}`;
1019
- console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
1020
- }
1021
- function printJsonError(message, hint, cause) {
1022
- console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
1023
- }
1024
- function wantsJson(argv) {
1025
- const end = argv.indexOf("--");
1026
- return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
1027
- }
1028
- function reportThrown(prefix, error, redact = (text) => text, json = false) {
1029
- if (error instanceof HelpShown)
1030
- return 0;
1031
- const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
1032
- const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
1033
- const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
1034
- if (error instanceof Exit && error.code === 2)
1035
- noteUsageError(error.message);
1036
- const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
1037
- report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
1038
- return error instanceof Exit ? error.code : 1;
1039
- }
1040
- async function dispatch(level, typed, { version, redact }) {
1041
- const prefix = level.path.join(" ");
1042
- let argv;
1043
- try {
1044
- argv = takeOutputFlags(typed);
1045
- } catch (error) {
1046
- return reportThrown(prefix, error);
1047
- }
1048
- const [name, ...args] = argv;
1049
- const fallback = level.defaultCommand === undefined ? undefined : level.commands[level.defaultCommand];
1050
- if (name === undefined && level.runBare && fallback !== undefined && "run" in fallback) {
1051
- try {
1052
- return await fallback.run([]);
1053
- } catch (error) {
1054
- return reportThrown(`${prefix} ${level.defaultCommand}`, error, redact, false);
1055
- }
1056
- }
1057
- if (name === undefined && level.path.length > 1) {
1058
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1059
- return 2;
1060
- }
1061
- if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1062
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1063
- return 0;
1064
- }
1065
- if (level.path.length === 1 && (name === "--version" || name === "-v")) {
1066
- console.log(version);
1067
- return 0;
1068
- }
1069
- let command = level.commands[level.aliases?.[name] ?? name];
1070
- let rest = args;
1071
- let ran = name;
1072
- if (command === undefined && level.lazy.length > 0) {
1073
- level = await expand(level, [...level.path.slice(1), ...argv]);
1074
- command = level.commands[level.aliases?.[name] ?? name];
1075
- }
1076
- if (command === undefined && level.defaultCommand !== undefined) {
1077
- command = level.commands[level.defaultCommand];
1078
- rest = argv;
1079
- ran = level.defaultCommand;
1080
- }
1081
- if (command === undefined) {
1082
- const meant = closest(name, Object.keys(shown(level.commands)));
1083
- printError(prefix, `no command ${name}`, meant === undefined ? `run ${prefix} --help for its commands` : `did you mean ${meant}?`);
1084
- return 2;
1085
- }
1086
- if ("commands" in command) {
1087
- const { summary } = command;
1088
- 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 });
1089
- }
1090
- try {
1091
- return await command.run(rest);
1092
- } catch (error) {
1093
- return reportThrown(`${prefix} ${ran}`, error, redact, wantsJson(rest));
1094
- }
1095
- }
1096
- var COMPLETE = "__complete";
1097
- var FILES = "__files__";
1098
- async function completingOf(run) {
1099
- completion.active = true;
1100
- try {
1101
- await run([]);
1102
- } catch (error) {
1103
- if (error instanceof Completing)
1104
- return error;
1105
- } finally {
1106
- completion.active = false;
1107
- }
1108
- return new Completing({});
1109
- }
1110
- async function optionsOf(run) {
1111
- return (await completingOf(run)).options;
1112
- }
1113
- function candidateLine(candidate) {
1114
- return typeof candidate === "string" ? candidate : candidate.join("\t");
1115
- }
1116
- function positionalBeingTyped(before, { options, positionals }) {
1117
- const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1118
- const typed = [];
1119
- let at = 0;
1120
- while (at < before.length) {
1121
- const word = before[at];
1122
- if (word === "--") {
1123
- typed.push(...before.slice(at + 1));
1124
- break;
1125
- }
1126
- if (!word.startsWith("-"))
1127
- typed.push(word);
1128
- else if (takesValue(word))
1129
- at++;
1130
- at++;
1131
- }
1132
- const last = positionals.at(-1);
1133
- if (typed.length < positionals.length)
1134
- return { name: positionals[typed.length], typed };
1135
- return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1136
- }
1137
- async function leafCandidates(run, words) {
1138
- const completing = await completingOf(run);
1139
- if ((words.at(-1) ?? "").startsWith("-"))
1140
- return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1141
- const flag = words.at(-2);
1142
- const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1143
- const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1144
- if (option?.type === "string") {
1145
- const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1146
- return values === undefined ? [FILES] : values.map(candidateLine);
1147
- }
1148
- const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1149
- return values === undefined ? [FILES] : values.map(candidateLine);
1150
- }
1151
- async function candidates(scope, defaultCommand, words, before = []) {
1152
- const [word = "", ...rest] = words;
1153
- const listing = rest.length === 0 && !word.startsWith("-");
1154
- let { commands, aliases } = scope;
1155
- let command = commands[aliases?.[word] ?? word];
1156
- if (listing || command === undefined) {
1157
- ({ commands, aliases } = await expand(scope, [...before, ...words]));
1158
- command = commands[aliases?.[word] ?? word];
1159
- }
1160
- if (listing) {
1161
- const own = await Promise.all(Object.entries(shown(commands)).map(async ([name, { summary }]) => `${name} ${await resolveSummary(summary)}`));
1162
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1163
- const values = fallback !== undefined && "run" in fallback ? await leafCandidates(fallback.run, [word]) : [];
1164
- const valueOf = (line) => line.slice(0, line.includes("\t") ? line.indexOf("\t") : undefined);
1165
- return [...own, ...values.filter((line) => line !== FILES && !(valueOf(line) in commands))];
1166
- }
1167
- if (command === undefined) {
1168
- const fallback = defaultCommand === undefined ? undefined : commands[defaultCommand];
1169
- return fallback !== undefined && "run" in fallback ? leafCandidates(fallback.run, words) : [];
1170
- }
1171
- return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1172
- }
1173
- var COMPLETIONS = "--completions";
1174
- function flagValue([flag = "", ...rest]) {
1175
- return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1176
- }
1177
- function printCompletionScript(name, args) {
1178
- const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1179
- if (shell === undefined || args.length !== 1) {
1180
- printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1181
- return 2;
1182
- }
1183
- console.log(completionScript(shell, [name]).trimEnd());
1184
- return 0;
1185
- }
1186
- async function printCandidates(found) {
1187
- for (const line of await found)
1188
- console.log(line);
1189
- return 0;
1190
- }
1191
- function packageVersion(entry = Bun.main) {
1192
- let resolved = entry;
1193
- try {
1194
- resolved = realpathSync2(entry);
1195
- } catch {}
1196
- for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1197
- try {
1198
- const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1199
- if (typeof version === "string")
1200
- return version;
1201
- } catch {}
1202
- if (dirname3(dir) === dir)
1203
- return "0.0.0";
1204
- }
1205
- }
1206
- async function runCli(cli, argv = scriptArgs()) {
1207
- const version = cli.version ?? packageVersion();
1208
- if (argv[0] === COMPLETE)
1209
- return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1210
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1211
- return printCompletionScript(cli.name, flagValue(argv));
1212
- const started = performance.now();
1213
- 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 });
1214
- const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1215
- notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1216
- if (cli.usage !== false) {
1217
- try {
1218
- recordUsage(usageEntry(cli.name, command, argv, code));
1219
- } catch {}
1220
- }
1221
- return code;
1222
- }
1223
- function commandPath(scope, argv) {
1224
- const path = [];
1225
- let level = scope;
1226
- for (const word of argv.filter((each) => !each.startsWith("-"))) {
1227
- const name = level.aliases !== undefined && Object.hasOwn(level.aliases, word) ? level.aliases[word] ?? word : word;
1228
- const command = Object.hasOwn(level.commands, name) ? level.commands[name] : undefined;
1229
- if (command === undefined)
1230
- break;
1231
- path.push(word);
1232
- if (!("commands" in command))
1233
- break;
1234
- level = scopeOf(command.commands, command.extraCommands, command.aliases);
1235
- }
1236
- return path.length === 0 ? undefined : path.join(" ");
1237
- }
1238
- async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1239
- if (argv[0] === COMPLETE)
1240
- return printCandidates(leafCandidates(run, argv.slice(1)));
1241
- if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1242
- return printCompletionScript(name, flagValue(argv));
1243
- if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1244
- console.log(version ?? packageVersion());
1245
- return 0;
1246
- }
1247
- let code;
1248
- const started = performance.now();
1249
- try {
1250
- code = await run(argv);
1251
- } catch (error) {
1252
- code = reportThrown(name, error, redact, wantsJson(argv));
1253
- }
1254
- notifyEnd(name, code, performance.now() - started);
1255
- if (usage !== false) {
1256
- try {
1257
- recordUsage(usageEntry(name, undefined, argv, code));
1258
- } catch {}
1259
- }
1260
- return code;
1261
- }
1262
- // ../kit/src/compose.ts
1263
- async function captureOutput(argv, { cwd, env } = {}) {
1264
- const run = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, env: { ...process.env, ...env }, stdin: "ignore", stdout: "pipe", stderr: "pipe" });
1265
- const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited]);
1266
- return { code, stdout, stderr };
1267
- }
1268
- async function compose(args, { flags = [], ...options } = {}) {
1269
- return captureOutput(["docker", "compose", ...flags, ...args], options);
1270
- }
1271
- // ../kit/src/folders.ts
1272
- import { homedir as homedir4 } from "os";
1273
- import { join as join6 } from "path";
1274
- import process15 from "process";
1275
- var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1276
- function ignoredFolders(extra = [], where = {}) {
1277
- const configured = readUserConfig("config", where).ignore;
1278
- const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1279
- return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1280
- }
1281
- function cacheFolder({ home = homedir4(), env = process15.env } = {}) {
1282
- return env.XDG_CACHE_HOME ?? join6(home, ".cache");
1283
- }
1284
- // ../kit/src/secrets.ts
1285
- var SECRET_PART = /token|secret|passw|credential|private|dsn|apikey|accesskey|key$/i;
1286
- var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
1287
- var WORD_BREAKS = /[^a-zA-Z\d]+|(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/;
1288
- function isSecretName(name) {
1289
- return SECRET_PART.test(name) || name.split(WORD_BREAKS).some((word) => SECRET_WORDS.has(word.toLowerCase()));
1290
- }
1291
- // ../kit/src/sessions.ts
1292
- var {Glob } = globalThis.Bun;
1293
- var SESSION_FILES = new Glob("*.json");
1294
- var ACCOUNT_DIRS = new Glob("*/sessions");
1295
- // src/commands/redact.ts
1296
- import process17 from "process";
1297
-
1298
- // src/files.ts
1299
- import { chmod, chown, readdir, realpath, rename, rm, stat, writeFile } from "fs/promises";
1300
- import { basename, dirname as dirname4, join as join7 } from "path";
1301
-
1302
- // src/dotenv.ts
1303
- var ASSIGNMENT = /^\s*(?:export\s+)?([A-Z_][\w.-]*)\s*=(.*)$/i;
1304
- var EXPORTED = /^\s*export\s/;
1305
- var INLINE_COMMENT = /\s+#.*$/;
1306
- var CARRIAGE_RETURN = /\r$/;
1307
- var ESCAPES = { n: `
1308
- `, r: "\r", t: "\t", '"': '"', "\\": "\\", $: "$" };
1309
- var LINE_BREAK = /[\r\n]/;
1310
- var RAW_ONLY = /["\\]/;
1311
- var NEEDS_QUOTES = /[\s#"'\\$`]/;
1312
- function closingQuote(text, quote) {
1313
- for (let index = 0;index < text.length; index++) {
1314
- if (quote === '"' && text[index] === "\\")
1315
- index++;
1316
- else if (text[index] === quote)
1317
- return index;
1318
- }
1319
- return -1;
1320
- }
1321
- function unescapeDollar(text) {
1322
- return text.replaceAll("\\$", "$");
1323
- }
1324
- function unescapeDouble(text) {
1325
- let out = "";
1326
- for (let index = 0;index < text.length; index++) {
1327
- const next = text[index + 1];
1328
- if (text[index] === "\\" && next !== undefined && next in ESCAPES) {
1329
- out += ESCAPES[next];
1330
- index++;
1331
- } else {
1332
- out += text[index];
1333
- }
1334
- }
1335
- return out;
1336
- }
1337
- function parseDotenv(text) {
1338
- const physical = text.split(`
1339
- `);
1340
- const lines = [];
1341
- for (let index = 0;index < physical.length; index++) {
1342
- const line = physical[index] ?? "";
1343
- const match = ASSIGNMENT.exec(line.replace(CARRIAGE_RETURN, ""));
1344
- if (match === null) {
1345
- lines.push({ raw: line });
1346
- continue;
1347
- }
1348
- const [, key = "", rest = ""] = match;
1349
- const start = rest.trimStart();
1350
- const quote = start[0];
1351
- if (quote !== '"' && quote !== "'" && quote !== "`") {
1352
- lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()) });
1353
- continue;
1354
- }
1355
- let body = start.slice(1);
1356
- let raw = line;
1357
- let end = closingQuote(body, quote);
1358
- const first = index;
1359
- while (end === -1 && index + 1 < physical.length && !ASSIGNMENT.test(physical[index + 1] ?? "")) {
1360
- index++;
1361
- body += `
1362
- ${(physical[index] ?? "").replace(CARRIAGE_RETURN, "")}`;
1363
- raw += `
1364
- ${physical[index] ?? ""}`;
1365
- end = closingQuote(body, quote);
1366
- }
1367
- if (end === -1 && index + 1 < physical.length) {
1368
- index = first;
1369
- lines.push({ raw: line, key, value: unescapeDollar(start.replace(INLINE_COMMENT, "").trim()), unterminated: true });
1370
- continue;
1371
- }
1372
- const inner = end === -1 ? body : body.slice(0, end);
1373
- lines.push({ raw, key, value: quote === '"' ? unescapeDouble(inner) : unescapeDollar(inner) });
1374
- }
1375
- return { lines };
1376
- }
1377
- function serializeDotenv(file) {
1378
- return file.lines.map((line) => line.raw).join(`
1379
- `);
1380
- }
1381
- function entries(file) {
1382
- const map = new Map;
1383
- for (const line of file.lines) {
1384
- if (line.key !== undefined)
1385
- map.set(line.key, line.value ?? "");
1386
- }
1387
- return map;
1388
- }
1389
- function escapeDouble(value) {
1390
- return value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"").replaceAll("\r", "\\r").replaceAll(`
1391
- `, "\\n").replaceAll("$", "\\$");
1392
- }
1393
- function formatAssignment(key, value) {
1394
- if (value === "" || !NEEDS_QUOTES.test(value))
1395
- return `${key}=${value}`;
1396
- if (RAW_ONLY.test(value) && !value.includes("'") && !LINE_BREAK.test(value))
1397
- return `${key}='${value.replaceAll("$", "\\$")}'`;
1398
- return `${key}="${escapeDouble(value)}"`;
1399
- }
1400
- function setLine(file, key, value, raw) {
1401
- const index = file.lines.findLastIndex((line) => line.key === key);
1402
- const existing = file.lines[index];
1403
- if (existing !== undefined) {
1404
- const exported = EXPORTED.test(existing.raw) ? "export " : "";
1405
- file.lines[index] = { raw: raw ?? `${exported}${formatAssignment(key, value)}`, key, value };
1406
- return;
1407
- }
1408
- const line = { raw: raw ?? formatAssignment(key, value), key, value };
1409
- const last = file.lines.at(-1);
1410
- if (last === undefined)
1411
- file.lines.push(line, { raw: "" });
1412
- else if (last.raw === "")
1413
- file.lines.splice(-1, 0, line);
1414
- else
1415
- file.lines.push(line, { raw: "" });
1416
- }
1417
- function removeKey(file, key) {
1418
- const before = file.lines.length;
1419
- file.lines = file.lines.filter((line) => line.key !== key);
1420
- return before - file.lines.length;
1421
- }
1422
- function lastLine(file, key) {
1423
- return file.lines.findLast((line) => line.key === key);
1424
- }
1425
-
1426
- // src/mask.ts
1427
- var MIN_KNOWN_LENGTH = 4;
1428
- var KEY_MASK = "*** private key redacted ***";
1429
- var PLAIN_VALUE = /^(?:true|false|null|none|nil|yes|no|on|off|undefined)$/i;
1430
- var PLACEHOLDER = /^[$%{<(*/]/;
1431
- var URL_PASSWORD = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/[^\s:/@]*:([^\s'"]{1,1024})@/dgi;
1432
- var PORT = /^\d{1,5}$/;
1433
- var ESCAPE2 = /[.*+?^${}()|[\]\\]/g;
1434
- function isPlaceholder(value) {
1435
- return PLACEHOLDER.test(value) || PLAIN_VALUE.test(value);
1436
- }
1437
- var STRONG_NAME = "password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|account[_-]?key|shared[_-]?access[_-]?key";
1438
- var WEAK_NAME = "token|credentials?|auth";
1439
- var PLAIN_WORD = /^[a-z]+$/i;
1440
- var AFTER_COLON = /:\s*$/;
1441
- var DIGIT = /\d/;
1442
- var KEY_VALUE_GAP = "\\s*[:=]\\s*";
1443
- function isProse(value, before) {
1444
- return isPlaceholder(value) || AFTER_COLON.test(before) && PLAIN_WORD.test(value);
1445
- }
1446
- function isWeak(value, before) {
1447
- return isProse(value, before) || !(DIGIT.test(value) || value.length >= 16);
1448
- }
1449
- function keyed(names, value) {
1450
- return new RegExp(`(?<![\\w-])["']?(?:[\\w-]{0,30}[_-])?(?:${names})(?:[_-][\\w-]{0,30})?["']?${KEY_VALUE_GAP}${value}`, "dgi");
1451
- }
1452
- var TOKEN_FORMATS = [
1453
- { kind: "GitHub token", pattern: /\b(?:gh[pousr]_|github_pat_)\w{20,}/dg },
1454
- { kind: "GitLab token", pattern: /\bgl(?:pat|rt|dt|ptt)-[\w-]{20,}/dg },
1455
- { kind: "Hugging Face token", pattern: /\bhf_[A-Za-z]{30,}/dg },
1456
- { kind: "webhook secret", pattern: /\bwhsec_\w{20,}/dg },
1457
- { kind: "DigitalOcean token", pattern: /\bdop_v1_\w{20,}/dg },
1458
- { kind: "Shopify token", pattern: /\bshp(?:at|ca|pa|ss)_\w{20,}/dg },
1459
- { kind: "password", pattern: /\bmysql(?:dump|admin)?\s+(?:\S+\s+)*?-p([^\s"'|;&-]\S{3,})/dg },
1460
- { kind: "password", pattern: /\bsshpass\s+(?:-[a-oq-z]\s+)*-p\s*([^\s"'|;&]{4,})/dg },
1461
- { kind: "API key", pattern: /\bsk-[\w-]{20,}/dg },
1462
- { kind: "Slack token", pattern: /\bx(?:ox[abprs]|app)-[\w-]{10,}/dg },
1463
- { kind: "JWT", pattern: /\beyJ[\w-]+\.[\w-]+\.[\w-]+/dg },
1464
- { kind: "AWS access key", pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/dg },
1465
- { kind: "npm token", pattern: /\bnpm_[A-Za-z0-9]{30,}/dg },
1466
- { kind: "Stripe key", pattern: /\b[sr]k_(?:live|test)_[A-Za-z0-9]{10,}/dg },
1467
- { kind: "Google API key", pattern: /\bAIza[\w-]{35}/dg },
1468
- { kind: "SendGrid key", pattern: /\bSG\.[\w-]{16,}\.[\w-]{16,}/dg },
1469
- { kind: "Authorization header", pattern: /\bAuthorization["']?\s*[:=]\s*["']?(?:Bearer|Basic|Token|Digest)\s+([^\s"',;]{8,})/dgi, skip: isPlaceholder },
1470
- { kind: "Bearer token", pattern: /\bBearer\s+((?=[\w.~+/=-]*\d)[\w.~+/=-]{20,})/dg },
1471
- { kind: "password", pattern: keyed(STRONG_NAME, `([^\\s"'&;,]{4,})`), skip: isProse },
1472
- { kind: "password", pattern: keyed(WEAK_NAME, `([^\\s"'&;,]{4,})`), skip: isWeak },
1473
- { kind: "password", pattern: keyed(STRONG_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isPlaceholder },
1474
- { kind: "password", pattern: keyed(WEAK_NAME, `(["'])((?:\\\\.|(?!\\1)[^\\\\\\n]){4,})\\1`), skip: isWeak }
1475
- ];
1476
- var PEM_BEGIN = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1477
- var PEM_END = /-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
1478
- var PEM_BODY = /(?<=-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)(?:(?!-----END [A-Z ]*PRIVATE KEY(?: BLOCK)?-----)[\s\S])+/dg;
1479
- var PEM_BEGIN_ALL = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/g;
1480
- var URL_PARTS = /(?<![a-z0-9+.-])[a-z][a-z0-9+.-]{0,31}:\/\/([^\s/?#'"<>`]*)([^\s?#'"<>`]*)(?:\?([^\s#'"<>`]*))?/dgi;
1481
- var PATH_SEGMENT = /[^/]+/g;
1482
- var SECRET_PARAM = /^(?:token|[a-z]+_token|key|api[_-]?key|access[_-]?key|secret|[a-z]+_secret|password|passwd|pwd|sig|signature|auth|authorization)$/i;
1483
- var WEBHOOK_FORMATS = [
1484
- ["Discord webhook", /(?:^|\.)discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/([\w-]+)/di],
1485
- ["Slack webhook", /^hooks\.slack\.com\/(?:services|workflows)\/(?:[\w-]+\/)*([\w-]+)/di],
1486
- ["Uptime Kuma push URL", /\/api\/push\/([\w-]+)/di],
1487
- ["healthchecks.io ping URL", /^hc-ping\.com\/([\w-]+)/di]
1488
- ];
1489
- var OPAQUE_SEGMENT = /^(?:(?=[\w-]{20,}$)(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w-]+|(?=[A-Za-z\d]{32,}$)(?=.*[A-Za-z])(?=.*\d).+)$/;
1490
- function isSecretKey(key) {
1491
- return isSecretName(key);
1492
- }
1493
- function hint(value) {
1494
- const shown = Math.min(3, Math.floor(value.length / 4));
1495
- return `${value.slice(0, shown)}***(${value.length})`;
1496
- }
1497
- function forms(value) {
1498
- return [...new Set([value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])];
1499
- }
1500
- function knownSecrets(pairs) {
1501
- const keys = new Map;
1502
- for (const [key, value] of pairs) {
1503
- if (value.length < MIN_KNOWN_LENGTH || PLAIN_VALUE.test(value))
1504
- continue;
1505
- for (const form of forms(value)) {
1506
- if (!keys.has(form))
1507
- keys.set(form, key);
1508
- }
1509
- }
1510
- if (keys.size === 0)
1511
- return { pattern: undefined, keys };
1512
- const alternatives = [...keys.keys()].sort((a, b) => b.length - a.length).map((value) => value.replace(ESCAPE2, "\\$&"));
1513
- return { pattern: new RegExp(`(?<!\\w)(?:${alternatives.join("|")})(?!\\w)`, "g"), keys };
1514
- }
1515
- function passwordSpans(text) {
1516
- const spans = [];
1517
- for (const url of text.matchAll(URL_PASSWORD)) {
1518
- const [start, end] = url.indices?.[1] ?? [];
1519
- const password = url[1] ?? "";
1520
- const slash = password.indexOf("/");
1521
- if (start !== undefined && end !== undefined && !(slash !== -1 && PORT.test(password.slice(0, slash))))
1522
- spans.push([start, end]);
1523
- }
1524
- return spans;
1525
- }
1526
- function urlPasswords(text) {
1527
- return passwordSpans(text).map(([start, end]) => text.slice(start, end));
1528
- }
1529
- function urlTokens(line) {
1530
- const found = [];
1531
- const add = (kind, start, value) => {
1532
- found.push({ start, end: start + value.length, kind, mask: hint(value) });
1533
- };
1534
- for (const url of line.matchAll(URL_PARTS)) {
1535
- const [authority, path = "", query] = [url[1] ?? "", url[2] ?? "", url[3]];
1536
- const authorityStart = url.indices?.[1]?.[0];
1537
- const pathStart = url.indices?.[2]?.[0];
1538
- const queryStart = url.indices?.[3]?.[0];
1539
- if (authorityStart === undefined || pathStart === undefined)
1540
- continue;
1541
- const hostAt = authority.lastIndexOf("@") + 1;
1542
- const target = authority.slice(hostAt) + path;
1543
- for (const [kind, pattern] of WEBHOOK_FORMATS) {
1544
- const [start, end] = pattern.exec(target)?.indices?.[1] ?? [];
1545
- if (start !== undefined && end !== undefined)
1546
- add(kind, authorityStart + hostAt + start, target.slice(start, end));
1547
- }
1548
- for (const segment of path.matchAll(PATH_SEGMENT)) {
1549
- if (OPAQUE_SEGMENT.test(segment[0]))
1550
- add("URL token", pathStart + segment.index, segment[0]);
1551
- }
1552
- if (query === undefined || queryStart === undefined)
1553
- continue;
1554
- let offset = 0;
1555
- for (const param of query.split("&")) {
1556
- const equals = param.indexOf("=");
1557
- if (equals > 0 && equals < param.length - 1 && SECRET_PARAM.test(param.slice(0, equals)))
1558
- add("URL token", queryStart + offset + equals + 1, param.slice(equals + 1));
1559
- offset += param.length + 1;
1560
- }
1561
- }
1562
- return found.filter((match) => match.end > match.start);
1563
- }
1564
- function findSecrets(line, known) {
1565
- const found = [];
1566
- for (const [start, end] of passwordSpans(line))
1567
- found.push({ start, end, kind: "URL password", mask: "***" });
1568
- for (const body of line.matchAll(PEM_BODY)) {
1569
- const [start, end] = body.indices?.[0] ?? [];
1570
- if (start !== undefined && end !== undefined)
1571
- found.push({ start, end, kind: "private key", mask: KEY_MASK });
1572
- }
1573
- for (const { kind, pattern, skip } of TOKEN_FORMATS) {
1574
- for (const token of line.matchAll(pattern)) {
1575
- const [start, end] = token.indices?.at(-1) ?? [];
1576
- if (start === undefined || end === undefined)
1577
- continue;
1578
- const value = line.slice(start, end);
1579
- if (!skip?.(value, line.slice(0, start)))
1580
- found.push({ start, end, kind, mask: hint(value) });
1581
- }
1582
- }
1583
- found.push(...urlTokens(line));
1584
- if (known?.pattern !== undefined) {
1585
- for (const value of line.matchAll(known.pattern))
1586
- found.push({ start: value.index, end: value.index + value[0].length, kind: `value of ${known.keys.get(value[0])}`, mask: hint(value[0]) });
1587
- }
1588
- found.sort((a, b) => a.start - b.start || b.end - a.end);
1589
- const kept = [];
1590
- for (const match of found) {
1591
- if (match.start >= (kept.at(-1)?.end ?? 0))
1592
- kept.push(match);
1593
- }
1594
- return kept;
1595
- }
1596
- function openKeyBody(line) {
1597
- const last = [...line.matchAll(PEM_BEGIN_ALL)].at(-1);
1598
- if (last === undefined)
1599
- return;
1600
- const after = line.slice(last.index + last[0].length);
1601
- return PEM_END.test(after) ? undefined : after.trim();
1602
- }
1603
- function maskLine(line, known) {
1604
- let out = "";
1605
- let at = 0;
1606
- for (const match of findSecrets(line, known)) {
1607
- out += line.slice(at, match.start) + match.mask;
1608
- at = match.end;
1609
- }
1610
- return out + line.slice(at);
1611
- }
1612
- function maskValue(key, value, known) {
1613
- if (value === "")
1614
- return value;
1615
- return isSecretName(key) || PEM_BEGIN.test(value) ? hint(value) : maskLine(value, known);
1616
- }
1617
-
1618
- // src/files.ts
1619
- var ENV_FILE = /^(?:\.env(?:\..+)?|.+\.env|\.envrc)$/;
1620
- var TEMPLATE = /\.(?:example|sample|template|dist|defaults)$/;
1621
- var KNOWN_DEPTH = 3;
1622
- var SKIPPED = ignoredFolders([".git", ".kay"]);
1623
- var LOCK_WAIT_MS = 5000;
1624
- var LOCK_STALE_MS = 30000;
1625
- var REAP_STALE_MS = 5000;
1626
- async function isFileEntry(entry, path) {
1627
- if (entry.isFile())
1628
- return true;
1629
- if (!entry.isSymbolicLink())
1630
- return false;
1631
- try {
1632
- return (await stat(path)).isFile();
1633
- } catch {
1634
- return false;
1635
- }
1636
- }
1637
- async function envFiles(folder = process.cwd()) {
1638
- const found = await readdir(folder, { withFileTypes: true });
1639
- const names = [];
1640
- for (const entry of found) {
1641
- if (ENV_FILE.test(entry.name) && await isFileEntry(entry, join7(folder, entry.name)))
1642
- names.push(entry.name);
1643
- }
1644
- return names.sort();
1645
- }
1646
- async function readEnv(path) {
1647
- const file = Bun.file(path);
1648
- if (!await file.exists())
1649
- fail(`${path} does not exist`);
1650
- return parseDotenv(await file.text());
1651
- }
1652
- async function writeAtomic(path, text) {
1653
- let target = path;
1654
- let mode = 384;
1655
- let owner;
1656
- try {
1657
- target = await realpath(path);
1658
- const current = await stat(target);
1659
- mode = current.mode & 511;
1660
- owner = current;
1661
- } catch (error) {
1662
- if (error.code !== "ENOENT")
1663
- throw error;
1664
- }
1665
- const temp = join7(dirname4(target), `.${basename(target)}.${process.pid}.${crypto.randomUUID()}.tmp`);
1666
- try {
1667
- await writeFile(temp, text, { mode: 384, flag: "wx" });
1668
- if (owner !== undefined)
1669
- await keepOwner(temp, owner);
1670
- await chmod(temp, mode);
1671
- await rename(temp, target);
1672
- } finally {
1673
- await rm(temp, { force: true });
1674
- }
1675
- }
1676
- async function keepOwner(path, owner) {
1677
- try {
1678
- await chown(path, owner.uid, owner.gid);
1679
- } catch (error) {
1680
- if (error.code !== "EPERM")
1681
- throw error;
1682
- }
1683
- }
1684
- async function writeEnv(path, file) {
1685
- await writeAtomic(path, serializeDotenv(file));
1686
- }
1687
- async function withLocks(paths, fn) {
1688
- const held = [];
1689
- try {
1690
- for (const path of [...new Set(paths)].sort())
1691
- held.push(await acquire(path));
1692
- return await fn();
1693
- } finally {
1694
- for (const lock of held)
1695
- await rm(lock, { force: true });
1696
- }
1697
- }
1698
- async function reap(lock) {
1699
- const guard = `${lock}.reap`;
1700
- try {
1701
- await writeFile(guard, String(process.pid), { flag: "wx", mode: 384 });
1702
- } catch {
1703
- try {
1704
- if (Date.now() - (await stat(guard)).mtimeMs > REAP_STALE_MS)
1705
- await rm(guard, { force: true });
1706
- } catch {}
1707
- return;
1708
- }
1709
- try {
1710
- if (Date.now() - (await stat(lock)).mtimeMs > LOCK_STALE_MS)
1711
- await rm(lock, { force: true });
1712
- } catch {} finally {
1713
- await rm(guard, { force: true });
1714
- }
1715
- }
1716
- async function acquire(path) {
1717
- let real = path;
1718
- try {
1719
- real = await realpath(path);
1720
- } catch {}
1721
- const lock = join7(dirname4(real), `.${basename(real)}.lock`);
1722
- const deadline = Date.now() + LOCK_WAIT_MS;
1723
- while (true) {
1724
- try {
1725
- await writeFile(lock, String(process.pid), { flag: "wx", mode: 384 });
1726
- return lock;
1727
- } catch (error) {
1728
- if (error.code !== "EEXIST")
1729
- throw error;
1730
- }
1731
- await reap(lock);
1732
- if (Date.now() > deadline)
1733
- fail(`${path} is locked by another ev run (${lock})`, 1);
1734
- await Bun.sleep(25);
1735
- }
1736
- }
1737
- function secretPairs(file) {
1738
- const pairs = [];
1739
- for (const [key, value] of entries(file)) {
1740
- if (isSecretName(key))
1741
- pairs.push([key, value]);
1742
- else
1743
- pairs.push(...urlPasswords(value).map((password) => [key, password]));
1744
- }
1745
- return pairs;
1746
- }
1747
- async function envFilesBelow(folder, depth = 0) {
1748
- const found = [];
1749
- let children;
1750
- try {
1751
- children = await readdir(folder, { withFileTypes: true });
1752
- } catch {
1753
- return found;
1754
- }
1755
- for (const entry of children) {
1756
- const path = join7(folder, entry.name);
1757
- if (entry.isDirectory() && depth < KNOWN_DEPTH && !SKIPPED.has(entry.name))
1758
- found.push(...await envFilesBelow(path, depth + 1));
1759
- else if (ENV_FILE.test(entry.name) && await isFileEntry(entry, path))
1760
- found.push(path);
1761
- }
1762
- return found;
1763
- }
1764
- async function loadKnown(folder = process.cwd(), extra = []) {
1765
- const pairs = extra.flatMap(secretPairs);
1766
- for (const path of await envFilesBelow(folder)) {
1767
- try {
1768
- pairs.push(...secretPairs(parseDotenv(await Bun.file(path).text())));
1769
- } catch {}
1770
- }
1771
- return knownSecrets(pairs);
1772
- }
1773
-
1774
- // src/redactor.ts
1775
- var DIFF_START = /^(?:diff --git |@@ )/;
1776
- var NEW_FILE = /^\+\+\+ (?:b\/)?(.+)$/;
1777
- var HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)/;
1778
- var MAX_PENDING = 1 << 18;
1779
- var OVERLAP = 1 << 13;
1780
-
1781
- class Redactor {
1782
- known;
1783
- pending = "";
1784
- inKey = false;
1785
- hidden = false;
1786
- constructor(known) {
1787
- this.known = known;
1788
- }
1789
- push(chunk) {
1790
- const end = chunk.lastIndexOf(`
1791
- `);
1792
- this.pending += chunk;
1793
- if (end === -1)
1794
- return this.pending.length > MAX_PENDING ? this.cut() : "";
1795
- const split = this.pending.length - chunk.length + end + 1;
1796
- const complete = this.pending.slice(0, split);
1797
- this.pending = this.pending.slice(split);
1798
- return complete.split(`
1799
- `).slice(0, -1).map((line) => this.line(line)).filter((line) => line !== undefined).map((line) => `${line}
1800
- `).join("");
1801
- }
1802
- cut() {
1803
- const limit = this.pending.length - OVERLAP;
1804
- const space = this.pending.lastIndexOf(" ", limit);
1805
- const at = space > 0 ? space + 1 : limit;
1806
- const head = this.pending.slice(0, at);
1807
- this.pending = this.pending.slice(at);
1808
- return this.line(head) ?? "";
1809
- }
1810
- end() {
1811
- const rest = this.pending;
1812
- this.pending = "";
1813
- return rest === "" ? "" : this.line(rest) ?? "";
1814
- }
1815
- line(line) {
1816
- if (this.inKey) {
1817
- const end = PEM_END.exec(line);
1818
- if (end === null) {
1819
- if (this.hidden)
1820
- return;
1821
- this.hidden = true;
1822
- return KEY_MASK;
1823
- }
1824
- this.inKey = false;
1825
- return (end.index > 0 && !this.hidden ? KEY_MASK : "") + this.line(line.slice(end.index));
1826
- }
1827
- const body = openKeyBody(line);
1828
- if (body !== undefined) {
1829
- this.inKey = true;
1830
- this.hidden = body !== "";
1831
- }
1832
- return maskLine(line, this.known);
1833
- }
1834
- }
1835
- function check(text, known) {
1836
- const findings = [];
1837
- const isDiff = text.split(`
1838
- `).some((line) => DIFF_START.test(line));
1839
- let file = "stdin";
1840
- let number = 0;
1841
- let inKey = false;
1842
- for (const [index, raw] of text.split(`
1843
- `).entries()) {
1844
- let line = raw;
1845
- if (isDiff) {
1846
- const hunk = HUNK.exec(raw);
1847
- if (hunk !== null) {
1848
- number = Number(hunk[1]) - 1;
1849
- continue;
1850
- }
1851
- const named = NEW_FILE.exec(raw);
1852
- if (named !== null) {
1853
- file = named[1] ?? file;
1854
- continue;
1855
- }
1856
- if (raw.startsWith("diff --git ")) {
1857
- file = "(unnamed)";
1858
- continue;
1859
- }
1860
- if (raw.startsWith("-") || raw.startsWith("\\"))
1861
- continue;
1862
- number++;
1863
- if (!raw.startsWith("+"))
1864
- continue;
1865
- line = raw.slice(1);
1866
- } else {
1867
- number = index + 1;
1868
- }
1869
- if (inKey) {
1870
- const end = PEM_END.exec(line);
1871
- inKey = end === null;
1872
- if (end === null)
1873
- continue;
1874
- line = line.slice(end.index);
1875
- }
1876
- const found = findSecrets(line, known).map((match) => match.kind);
1877
- const body = openKeyBody(line);
1878
- if (body !== undefined) {
1879
- inKey = true;
1880
- if (body === "")
1881
- found.push("private key");
1882
- }
1883
- for (const kind of found)
1884
- findings.push({ file, line: number, kind });
1885
- }
1886
- return findings;
1887
- }
1888
-
1889
- // src/commands/redact.ts
1890
- var usage2 = `redact [--check]
1891
-
1892
- Copies stdin to stdout line by line with secrets masked: known token formats (GitHub, GitLab, Slack, AWS, npm, Stripe, Google and SendGrid keys, sk-, JWTs, Authorization headers, password= and secret= pairs), private key blocks, the password and the tokens of any URL and the values of secret-looking keys in this folder's .env* files.
1893
- --check prints nothing of the input and lists the file and line of each secret found, exiting 1 when there is any: \`git diff --cached | redact --check\`.`;
1894
- var EXITS = [[0, "it copied the input or found no secret"], [1, "--check finds one"], [2, "a usage error"]];
1895
- var options = {
1896
- check: { type: "boolean", description: "list where secrets are instead of masking them, exit 1 when found" },
1897
- "no-env": { type: "boolean", description: "do not search for the values of the .env* files" }
1898
- };
1899
- async function redact(args) {
1900
- const parsed = parse(args, usage2, options, { exits: EXITS, replaces: "printing a command's secrets into a log or a transcript", examples: [["docker compose config | redact", "the resolved compose file, secrets masked"], ["git diff --cached | redact --check", "refuse a commit carrying a secret"]] });
1901
- const known = parsed.values["no-env"] === true ? undefined : await loadKnown();
1902
- if (parsed.values.check === true) {
1903
- const findings = check(await readInput("-"), known);
1904
- for (const { file, line, kind } of findings)
1905
- console.log(`${file}:${line}: ${kind}`);
1906
- return findings.length === 0 ? 0 : 1;
1907
- }
1908
- const redactor = new Redactor(known);
1909
- const decoder = new TextDecoder;
1910
- for await (const chunk of Bun.stdin.stream())
1911
- process17.stdout.write(redactor.push(decoder.decode(chunk, { stream: true })));
1912
- process17.stdout.write(redactor.push(decoder.decode()) + redactor.end());
1913
- return 0;
1914
- }
1915
-
1916
- // src/redact.ts
1917
- process18.exitCode = await runMain({ name: "redact", run: redact });