@kaynooo/cli-gloss 0.0.0-stage → 0.0.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -2
  3. package/dist/gloss.js +1437 -0
  4. package/package.json +38 -4
package/dist/gloss.js ADDED
@@ -0,0 +1,1437 @@
1
+ #!/usr/bin/env -S bun --no-env-file --config=/dev/null
2
+ // @bun
3
+
4
+ // src/gloss.ts
5
+ import process16 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
+ // ../kit/src/mode.ts
14
+ import process2 from "process";
15
+ var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
16
+ var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
17
+ function isSet(value) {
18
+ return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
19
+ }
20
+ function outputMode(stream = process2.stdout, env = process2.env) {
21
+ const chosen = env.KIT_MODE;
22
+ if (chosen !== undefined && MODES.has(chosen))
23
+ return chosen;
24
+ if (AGENT_VARIABLES.some((name) => isSet(env[name])))
25
+ return "agent";
26
+ if (stream.isTTY === true)
27
+ return "terminal";
28
+ return isSet(env.CI) ? "ci" : "pipe";
29
+ }
30
+
31
+ // ../kit/src/style.ts
32
+ import process6 from "process";
33
+
34
+ // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-x450vn3m.js
35
+ var G = /^[a-f0-9]+$/i;
36
+ function b(r) {
37
+ let e = r.startsWith("#") ? r.slice(1) : r;
38
+ if (!G.test(e))
39
+ return [0, 0, 0];
40
+ if (e.length === 3 || e.length === 4)
41
+ return [Number.parseInt(e[0] + e[0], 16), Number.parseInt(e[1] + e[1], 16), Number.parseInt(e[2] + e[2], 16)];
42
+ if (e.length !== 6 && e.length !== 8)
43
+ throw Error(`Invalid hex color length: ${e.length}`);
44
+ return [Number.parseInt(e.slice(0, 2), 16), Number.parseInt(e.slice(2, 4), 16), Number.parseInt(e.slice(4, 6), 16)];
45
+ }
46
+ var B = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], grey: [90, 39], blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39], bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49], rgb: (r, e, l, n = "fg") => [`${n === "fg" ? 38 : 48};2;${r};${e};${l}`, n === "fg" ? 39 : 49], hex: (r, e = "fg") => {
47
+ let [l, n, c] = b(r);
48
+ return [`${e === "fg" ? 38 : 48};2;${l};${n};${c}`, e === "fg" ? 39 : 49];
49
+ }, ansi256: (r, e = "fg") => [`${e === "fg" ? 38 : 48};5;${r}`, e === "fg" ? 39 : 49] };
50
+ var h = new Set(["", "1", "2", "3", "true"]);
51
+ function C(r, e = globalThis.process?.env ?? {}) {
52
+ if (e.FORCE_COLOR !== undefined)
53
+ return h.has(e.FORCE_COLOR);
54
+ if (e.NO_COLOR !== undefined || e.NODE_DISABLE_COLORS !== undefined || e.TERM === "dumb")
55
+ return false;
56
+ return r?.isTTY === true;
57
+ }
58
+ function f(r, e = []) {
59
+ let l = "", n = "";
60
+ for (let t = 0, i = e.length;t < i; t++)
61
+ l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
62
+ let c = (t) => C(r.stream ?? globalThis.process?.stdout, r.env) ? l + t + n : t, g = new Map;
63
+ return new Proxy(c, { get(t, i) {
64
+ let a = B[i];
65
+ if (Array.isArray(a)) {
66
+ let s = g.get(i);
67
+ if (s === undefined)
68
+ s = f(r, [...e, a]), g.set(i, s);
69
+ return s;
70
+ }
71
+ if (typeof a === "function")
72
+ return (...s) => {
73
+ let y = `${i}:${s.join(",")}`, u = g.get(y);
74
+ if (u === undefined) {
75
+ if (g.size >= 64)
76
+ g.clear();
77
+ u = f(r, [...e, a(...s)]), g.set(y, u);
78
+ }
79
+ return u;
80
+ };
81
+ throw Error(`Unknown style: ${String(i)}`);
82
+ } });
83
+ }
84
+ function Fe(r = {}) {
85
+ return f(r);
86
+ }
87
+ var o = Fe();
88
+
89
+ // ../kit/src/theme.ts
90
+ import { existsSync as existsSync2, readFileSync, statSync } from "fs";
91
+ import { homedir as homedir2 } from "os";
92
+ import { join as join3, resolve as resolve2 } from "path";
93
+ import process5 from "process";
94
+
95
+ // ../kit/src/config.ts
96
+ import { existsSync } from "fs";
97
+ import { dirname, join, resolve } from "path";
98
+ import process3 from "process";
99
+ function findUp(names, from = process3.cwd(), stop = () => false) {
100
+ const wanted = typeof names === "string" ? [names] : names;
101
+ for (let dir = resolve(from);; dir = dirname(dir)) {
102
+ const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
103
+ if (found !== undefined)
104
+ return found;
105
+ if (stop(dir) || dirname(dir) === dir)
106
+ return;
107
+ }
108
+ }
109
+
110
+ // ../kit/src/user-config.ts
111
+ import { homedir } from "os";
112
+ import { join as join2 } from "path";
113
+ import process4 from "process";
114
+ function configBase(where = {}) {
115
+ const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
116
+ return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
117
+ }
118
+ function userConfigPath(bin, where = {}) {
119
+ return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
120
+ }
121
+
122
+ // ../kit/src/theme.ts
123
+ var ENDS = new Map;
124
+ var DEFAULT = {
125
+ 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" },
126
+ 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" },
127
+ accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
128
+ bins: {},
129
+ gradient: ["#c084fc", "#67e8f9"]
130
+ };
131
+ 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" };
132
+ 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" };
133
+ var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", plan: "?", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+", open: "*", leaf: "-", guide: "|" };
134
+ var PRESETS = {
135
+ default: {},
136
+ "high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"], gradient: ["#d8b4fe", "#a5f3fc"] },
137
+ mono: { colors: MONO, accents: ["bold"], gradient: undefined },
138
+ ascii: { glyphs: ASCII }
139
+ };
140
+ 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"]);
141
+ var HEX = /^#[0-9a-f]{6}$/i;
142
+ var CONTROL = /\p{Cc}/u;
143
+ var MAX_FILE_BYTES = 64 * 1024;
144
+ var SPACES = /\s+/;
145
+ function isColorSpec(spec) {
146
+ if (typeof spec === "number")
147
+ return Number.isInteger(spec) && spec >= 0 && spec <= 255;
148
+ return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
149
+ }
150
+ var CUBE = [0, 95, 135, 175, 215, 255];
151
+ function cubeLevel(channel) {
152
+ return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
153
+ }
154
+ function nearest256(hex) {
155
+ const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
156
+ const levels = rgb.map(cubeLevel);
157
+ const cube = levels.map((level) => CUBE[level]);
158
+ const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
159
+ const greyValue = 8 + grey * 10;
160
+ const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
161
+ return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
162
+ }
163
+ function hasTrueColor(env) {
164
+ return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
165
+ }
166
+ function tinted(colors, spec, env = process5.env) {
167
+ if (typeof spec === "number")
168
+ return colors.ansi256(spec);
169
+ return spec.trim().split(SPACES).reduce((chain, token) => {
170
+ if (HEX.test(token))
171
+ return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
172
+ return chain[token] ?? chain;
173
+ }, colors);
174
+ }
175
+ function isRecord(value) {
176
+ return typeof value === "object" && value !== null && !Array.isArray(value);
177
+ }
178
+ function readThemeFile(path, warn) {
179
+ try {
180
+ const stat = statSync(path, { throwIfNoEntry: false });
181
+ if (stat === undefined)
182
+ return;
183
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
184
+ warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
185
+ return;
186
+ }
187
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
188
+ if (isRecord(parsed))
189
+ return parsed;
190
+ warn(`${path} is not a JSON object, theme ignored`);
191
+ } catch (error) {
192
+ warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
193
+ }
194
+ return;
195
+ }
196
+ function applyPreset(theme, name, warn, where) {
197
+ if (name === undefined)
198
+ return;
199
+ if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
200
+ warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
201
+ return;
202
+ }
203
+ const preset = PRESETS[name];
204
+ Object.assign(theme.colors, preset.colors);
205
+ Object.assign(theme.glyphs, preset.glyphs);
206
+ if (preset.accents !== undefined)
207
+ theme.accents = [...preset.accents];
208
+ if (Object.hasOwn(preset, "gradient"))
209
+ theme.gradient = preset.gradient;
210
+ return name;
211
+ }
212
+ function applyFile(theme, file, where, warn) {
213
+ if (isRecord(file.colors)) {
214
+ for (const [key, value] of Object.entries(file.colors)) {
215
+ if (!Object.hasOwn(DEFAULT.colors, key))
216
+ warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
217
+ else if (!isColorSpec(value))
218
+ warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
219
+ else
220
+ theme.colors[key] = value;
221
+ }
222
+ }
223
+ if (isRecord(file.glyphs)) {
224
+ for (const [key, value] of Object.entries(file.glyphs)) {
225
+ if (!Object.hasOwn(DEFAULT.glyphs, key))
226
+ warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
227
+ else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
228
+ warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
229
+ else
230
+ theme.glyphs[key] = value;
231
+ }
232
+ }
233
+ if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
234
+ theme.accents = [...file.accents];
235
+ else if (file.accents !== undefined)
236
+ warn(`${where}: accents must be a non-empty list of colours`);
237
+ if (file.gradient === null)
238
+ theme.gradient = undefined;
239
+ else if (Array.isArray(file.gradient) && file.gradient.length === 2 && file.gradient.every((end) => typeof end === "string" && HEX.test(end)))
240
+ theme.gradient = [file.gradient[0], file.gradient[1]];
241
+ else if (file.gradient !== undefined)
242
+ warn(`${where}: gradient must be two \`#rrggbb\` colours, or null for none`);
243
+ if (isRecord(file.bins)) {
244
+ for (const [bin, value] of Object.entries(file.bins)) {
245
+ if (isColorSpec(value))
246
+ theme.bins[bin] = value;
247
+ else
248
+ warn(`${where}: bin ${bin} has no valid colour`);
249
+ }
250
+ }
251
+ }
252
+ function endsWalk(home) {
253
+ return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
254
+ }
255
+ var warned = new Set;
256
+ function warnOnce(message) {
257
+ if (warned.has(message))
258
+ return;
259
+ warned.add(message);
260
+ console.error(`warning: theme ${message}`);
261
+ }
262
+ function isPath(chosen) {
263
+ return chosen.includes("/") || chosen.endsWith(".json");
264
+ }
265
+ function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
266
+ const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null), gradient: DEFAULT.gradient };
267
+ const sources = [];
268
+ const chosen = env.KIT_THEME ?? "";
269
+ const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
270
+ if (isPath(chosen))
271
+ wanted.push(resolve2(from, chosen));
272
+ const files = [];
273
+ for (const path of wanted) {
274
+ const file = path === undefined ? undefined : readThemeFile(path, warn);
275
+ if (path !== undefined && file !== undefined)
276
+ files.push({ path, file });
277
+ }
278
+ let preset = "default";
279
+ if (chosen !== "" && !isPath(chosen)) {
280
+ preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
281
+ } else {
282
+ const named = files.findLast(({ file }) => file.preset !== undefined);
283
+ if (named !== undefined)
284
+ preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
285
+ }
286
+ for (const { path, file } of files) {
287
+ applyFile(theme, file, path, warn);
288
+ sources.push(path);
289
+ }
290
+ return { theme, sources, preset };
291
+ }
292
+ var current;
293
+ var currentKey = "";
294
+ function activeTheme() {
295
+ const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
296
+ if (current === undefined || key !== currentKey) {
297
+ current = loadTheme();
298
+ currentKey = key;
299
+ }
300
+ return current;
301
+ }
302
+
303
+ // ../kit/src/style.ts
304
+ function takesControlCodes(stream, env = process6.env) {
305
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
306
+ }
307
+ function paint(stream, env = process6.env) {
308
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
309
+ }
310
+ function role(name, stream, env = process6.env) {
311
+ const colors = paint(stream, env);
312
+ return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
313
+ }
314
+ var STATUS_WORDS = {
315
+ passed: ["passed", "success", "succeeded", "ok"],
316
+ failed: ["failed", "failure", "error", "errored"],
317
+ running: ["running", "in_progress", "started", "holding"],
318
+ queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
319
+ skipped: ["skipped", "cancelled", "canceled", "manual"]
320
+ };
321
+ var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
+
323
+ // ../kit/src/format.ts
324
+ function upTo(text, separator) {
325
+ const end = text.indexOf(separator);
326
+ return end === -1 ? text : text.slice(0, end);
327
+ }
328
+ var ESCAPE = String.fromCharCode(27);
329
+ function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
330
+ return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
331
+ }
332
+ function printJson(value) {
333
+ console.log(jsonText(value));
334
+ }
335
+
336
+ // ../kit/src/help.ts
337
+ import process8 from "process";
338
+ var OPTIONAL = /\[[^\]]+\]/g;
339
+ var USAGE_PREFIX = /^usage:\s*/i;
340
+ var FULL_STOP = /\.$/;
341
+ function usageLine(usage, colors = paint(process8.stdout)) {
342
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
+ }
344
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
345
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
+ `);
347
+ }
348
+ function exitRows(exits, colors = paint(process8.stdout)) {
349
+ if (exits.length === 0)
350
+ return [];
351
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
352
+ }
353
+ function wantsHelpJson(env = process8.env) {
354
+ return env.KIT_HELP === "json";
355
+ }
356
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
357
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
358
+ `);
359
+ const first = lines[0];
360
+ const colon = first.indexOf(": ");
361
+ const prose = lines[lines.indexOf("") + 1] ?? "";
362
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
363
+ return {
364
+ synopsis: colon === -1 ? first : first.slice(0, colon),
365
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
366
+ ...replaces === undefined ? {} : { replaces },
367
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
368
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
369
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
370
+ };
371
+ }
372
+ function exampleRows(examples, colors = paint(process8.stdout)) {
373
+ if (examples.length === 0 || outputMode() === "agent")
374
+ return [];
375
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
376
+ }
377
+ function optionRows(options, colors = paint(process8.stdout)) {
378
+ const rows = Object.entries(options).map(([name, option]) => {
379
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
380
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
381
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
382
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
383
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
384
+ });
385
+ const width = Math.max(0, ...rows.map((row) => row.width));
386
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
387
+ }
388
+
389
+ // ../kit/src/text.ts
390
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
391
+ function stripAnsi(text) {
392
+ return text.replace(ANSI, "");
393
+ }
394
+ function distance(a, b) {
395
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
396
+ for (const [i, left] of [...a].entries()) {
397
+ const current = [i + 1];
398
+ for (const [j, right] of [...b].entries())
399
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
400
+ previous = current;
401
+ }
402
+ return previous[b.length] ?? 0;
403
+ }
404
+ function closest(name, names) {
405
+ const started = names.find((known) => known.startsWith(name));
406
+ if (started !== undefined)
407
+ return started;
408
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
409
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
410
+ }
411
+
412
+ // ../kit/src/args.ts
413
+ var DASHES = /^-+/;
414
+ function jsonOption(holds) {
415
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
416
+ }
417
+ class Exit extends Error {
418
+ code;
419
+ hint;
420
+ constructor(message, code, hint) {
421
+ super(message);
422
+ this.code = code;
423
+ this.hint = hint;
424
+ }
425
+ }
426
+ class UsageError extends Exit {
427
+ constructor(message, hint) {
428
+ super(message, 2, hint);
429
+ }
430
+ }
431
+ function badUsage(message) {
432
+ throw new UsageError(message);
433
+ }
434
+
435
+ class HelpShown extends Exit {
436
+ constructor() {
437
+ super("help shown", 0);
438
+ }
439
+ }
440
+
441
+ class Completing {
442
+ options;
443
+ positionals;
444
+ candidates;
445
+ constructor(options, positionals = [], candidates = {}) {
446
+ this.options = options;
447
+ this.positionals = positionals;
448
+ this.candidates = candidates;
449
+ }
450
+ }
451
+ var completion = { active: false };
452
+ var OUTPUT_OPTIONS = {
453
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
454
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
455
+ };
456
+ function applyOutput(color, plain, env = process9.env) {
457
+ const when = plain === true ? "never" : color ?? "auto";
458
+ if (when === "auto")
459
+ return;
460
+ if (when !== "always" && when !== "never")
461
+ badUsage(`--color takes auto, always or never, not ${when}`);
462
+ if (when === "always") {
463
+ env.FORCE_COLOR = "1";
464
+ delete env.NO_COLOR;
465
+ } else {
466
+ env.NO_COLOR = "1";
467
+ delete env.FORCE_COLOR;
468
+ }
469
+ }
470
+ function parse(args, usage, options, settings = {}) {
471
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
472
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
473
+ const listing = listed(all, settings.allowNegative === true);
474
+ if (completion.active)
475
+ throw new Completing(listing, settings.positionals, settings.candidates);
476
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
477
+ let parsed;
478
+ try {
479
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
480
+ } catch (error) {
481
+ const message = parseError(error);
482
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
483
+ }
484
+ const values = parsed.values;
485
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
486
+ if (values.help === true) {
487
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
488
+ throw new HelpShown;
489
+ }
490
+ checkChoices(parsed.values, all);
491
+ checkConflicts(parsed.values, all);
492
+ if (settings.positionals !== undefined)
493
+ checkPositionals(parsed.positionals, settings.positionals);
494
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
495
+ }
496
+ function splitRest(args, passes) {
497
+ const separator = passes ? args.indexOf("--") : -1;
498
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
499
+ }
500
+ function splitTrailing(args, options, count) {
501
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
502
+ let seen = 0;
503
+ if (count === 0)
504
+ return { own: args, rest: undefined };
505
+ for (let at = 0;at < args.length; at++) {
506
+ const word = args[at];
507
+ if (word === "--")
508
+ break;
509
+ if (word.startsWith("-")) {
510
+ if (takesValue(word))
511
+ at++;
512
+ continue;
513
+ }
514
+ seen++;
515
+ if (seen === count)
516
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
517
+ }
518
+ return { own: args, rest: undefined };
519
+ }
520
+ function listed(options, allowNegative) {
521
+ if (!allowNegative)
522
+ return options;
523
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
524
+ if (option.type !== "boolean" || option.negative === undefined)
525
+ return [[name, option]];
526
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
527
+ }));
528
+ }
529
+ function withAliases(args, options) {
530
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
531
+ if (named.size === 0)
532
+ return args;
533
+ const separator = args.indexOf("--");
534
+ const own = separator === -1 ? args : args.slice(0, separator);
535
+ return [...own.map((arg) => {
536
+ const at = arg.indexOf("=");
537
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
538
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
539
+ }), ...separator === -1 ? [] : args.slice(separator)];
540
+ }
541
+ function withBare(args, options) {
542
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
543
+ if (bare.size === 0)
544
+ return args;
545
+ const separator = args.indexOf("--");
546
+ const own = separator === -1 ? args : args.slice(0, separator);
547
+ return [...own.flatMap((arg, index) => {
548
+ const optional = bare.get(arg);
549
+ const next = own[index + 1];
550
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
551
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
552
+ }), ...separator === -1 ? [] : args.slice(separator)];
553
+ }
554
+ function checkConflicts(values, options) {
555
+ const given = (name) => values[name] !== undefined && values[name] !== false;
556
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
557
+ const other = given(name) ? conflicts.find(given) : undefined;
558
+ if (other !== undefined)
559
+ badUsage(`--${name} cannot be used with --${other}`);
560
+ }
561
+ }
562
+ function checkChoices(values, options) {
563
+ for (const [name, option] of Object.entries(options)) {
564
+ if (option.choices === undefined)
565
+ continue;
566
+ const given = values[name];
567
+ for (const value of Array.isArray(given) ? given : [given]) {
568
+ if (typeof value === "string")
569
+ oneOf(value, name, option.choices);
570
+ }
571
+ }
572
+ }
573
+ function oneOf(value, name, choices) {
574
+ if (!choices.includes(value))
575
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
576
+ return value;
577
+ }
578
+ function checkPositionals(given, names) {
579
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
580
+ const required = names.filter((name) => !name.startsWith("[")).length;
581
+ if (given.length < required)
582
+ badUsage(`missing ${names[given.length]}`);
583
+ if (!variadic && given.length > names.length)
584
+ badUsage(`unexpected argument ${given[names.length]}`);
585
+ }
586
+ function joinDashValues(args, options) {
587
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
588
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
589
+ const joined = [];
590
+ for (let i = 0;i < args.length; i++) {
591
+ const arg = args[i] ?? "";
592
+ if (arg === "--")
593
+ return [...joined, ...args.slice(i)];
594
+ const name = longOf.get(arg);
595
+ const next = args[i + 1];
596
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
597
+ joined.push(`--${name}=${next}`);
598
+ i++;
599
+ } else {
600
+ joined.push(arg);
601
+ }
602
+ }
603
+ return joined;
604
+ }
605
+ function parseError(error) {
606
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
607
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
608
+ }
609
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
610
+ function nearestOption(message, options, allowNegative) {
611
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
612
+ if (typed === undefined)
613
+ return;
614
+ const word = typed.replace(DASHES, "");
615
+ if (word.length < 2 && !typed.startsWith("--"))
616
+ return;
617
+ const known = Object.entries(options).flatMap(([name, option]) => [
618
+ ...option.short === undefined ? [] : [`-${option.short}`],
619
+ `--${name}`,
620
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
621
+ ]);
622
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
623
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
624
+ }
625
+ // ../kit/src/argv.ts
626
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
627
+ import { resolve as resolve3 } from "path";
628
+ import process10 from "process";
629
+ function commandLine() {
630
+ try {
631
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
632
+ } catch {
633
+ return;
634
+ }
635
+ }
636
+ function realPath(word) {
637
+ try {
638
+ return realpathSync(resolve3(word));
639
+ } catch {
640
+ return;
641
+ }
642
+ }
643
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
644
+ const target = script === undefined ? undefined : realPath(script) ?? script;
645
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
646
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
647
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
648
+ }
649
+ // ../kit/src/progress.ts
650
+ var ESC = String.fromCharCode(27);
651
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
652
+ var RESET_STYLE = `${ESC}[0m`;
653
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
654
+ // ../kit/src/cli.ts
655
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
656
+ import { dirname as dirname3, join as join5 } from "path";
657
+ import process12 from "process";
658
+
659
+ // ../kit/src/usage.ts
660
+ import { appendFileSync, mkdirSync } from "fs";
661
+ import { homedir as homedir3 } from "os";
662
+ import { dirname as dirname2, isAbsolute, join as join4 } from "path";
663
+ import process11 from "process";
664
+
665
+ // ../kit/src/logs.ts
666
+ var DAY_MS = 24 * 60 * 60 * 1000;
667
+ var CLI_FOLDER = "kaynooo-cli";
668
+
669
+ // ../kit/src/usage.ts
670
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
671
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
672
+ var LONGEST_NAME = 40;
673
+ var usageError;
674
+ function noteUsageError(message) {
675
+ usageError = message;
676
+ }
677
+ function stateHome(env = process11.env) {
678
+ const dir = env.XDG_STATE_HOME;
679
+ return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
680
+ }
681
+ function usagePath(env = process11.env) {
682
+ return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
683
+ }
684
+ function usageRecorded(env = process11.env) {
685
+ const off = env.KAYNOOO_CLI_NO_USAGE;
686
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
687
+ }
688
+ function flagNames(argv) {
689
+ const end = argv.indexOf("--");
690
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
691
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
692
+ }
693
+ function usageEntry(bin, command, argv, code, now = new Date) {
694
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
695
+ usageError = undefined;
696
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
697
+ }
698
+ function recordUsage(entry, env = process11.env) {
699
+ if (!usageRecorded(env))
700
+ return;
701
+ try {
702
+ const path = usagePath(env);
703
+ mkdirSync(dirname2(path), { recursive: true, mode: 448 });
704
+ appendFileSync(path, `${JSON.stringify(entry)}
705
+ `, { mode: 384 });
706
+ } catch {}
707
+ }
708
+
709
+ // ../kit/src/cli.ts
710
+ var LEVEL_OPTIONS = {
711
+ ...OUTPUT_OPTIONS,
712
+ help: { type: "boolean", short: "h", description: "show this help" }
713
+ };
714
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
715
+ function printError(prefix, message, hint, cause) {
716
+ const colors = paint(process12.stderr);
717
+ const styled = takesControlCodes(process12.stderr);
718
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
719
+ const under = (label, text, tint) => text === undefined ? "" : `
720
+ ${styled ? tint(label) : `${label}:`} ${text}`;
721
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
722
+ }
723
+ function printJsonError(message, hint, cause) {
724
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
725
+ }
726
+ function wantsJson(argv) {
727
+ const end = argv.indexOf("--");
728
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
729
+ }
730
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
731
+ if (error instanceof HelpShown)
732
+ return 0;
733
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
734
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
735
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
736
+ if (error instanceof Exit && error.code === 2)
737
+ noteUsageError(error.message);
738
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
739
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
740
+ return error instanceof Exit ? error.code : 1;
741
+ }
742
+ var COMPLETE = "__complete";
743
+ var FILES = "__files__";
744
+ async function completingOf(run) {
745
+ completion.active = true;
746
+ try {
747
+ await run([]);
748
+ } catch (error) {
749
+ if (error instanceof Completing)
750
+ return error;
751
+ } finally {
752
+ completion.active = false;
753
+ }
754
+ return new Completing({});
755
+ }
756
+ function candidateLine(candidate) {
757
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
758
+ }
759
+ function positionalBeingTyped(before, { options, positionals }) {
760
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
761
+ const typed = [];
762
+ let at = 0;
763
+ while (at < before.length) {
764
+ const word = before[at];
765
+ if (word === "--") {
766
+ typed.push(...before.slice(at + 1));
767
+ break;
768
+ }
769
+ if (!word.startsWith("-"))
770
+ typed.push(word);
771
+ else if (takesValue(word))
772
+ at++;
773
+ at++;
774
+ }
775
+ const last = positionals.at(-1);
776
+ if (typed.length < positionals.length)
777
+ return { name: positionals[typed.length], typed };
778
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
779
+ }
780
+ async function leafCandidates(run, words) {
781
+ const completing = await completingOf(run);
782
+ if ((words.at(-1) ?? "").startsWith("-"))
783
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
784
+ const flag = words.at(-2);
785
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
786
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
787
+ if (option?.type === "string") {
788
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
789
+ return values === undefined ? [FILES] : values.map(candidateLine);
790
+ }
791
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
792
+ return values === undefined ? [FILES] : values.map(candidateLine);
793
+ }
794
+ async function printCandidates(found) {
795
+ for (const line of await found)
796
+ console.log(line);
797
+ return 0;
798
+ }
799
+ function packageVersion(entry = Bun.main) {
800
+ let resolved = entry;
801
+ try {
802
+ resolved = realpathSync2(entry);
803
+ } catch {}
804
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
805
+ try {
806
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
807
+ if (typeof version === "string")
808
+ return version;
809
+ } catch {}
810
+ if (dirname3(dir) === dir)
811
+ return "0.0.0";
812
+ }
813
+ }
814
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
815
+ if (argv[0] === COMPLETE)
816
+ return printCandidates(leafCandidates(run, argv.slice(1)));
817
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
818
+ console.log(version ?? packageVersion());
819
+ return 0;
820
+ }
821
+ let code;
822
+ try {
823
+ code = await run(argv);
824
+ } catch (error) {
825
+ code = reportThrown(name, error, redact, wantsJson(argv));
826
+ }
827
+ if (usage !== false) {
828
+ try {
829
+ recordUsage(usageEntry(name, undefined, argv, code));
830
+ } catch {}
831
+ }
832
+ return code;
833
+ }
834
+ // ../kit/src/folders.ts
835
+ var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
836
+ // ../kit/src/secrets.ts
837
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
838
+ // ../kit/src/sessions.ts
839
+ var {Glob } = globalThis.Bun;
840
+ var SESSION_FILES = new Glob("*.json");
841
+ var ACCOUNT_DIRS = new Glob("*/sessions");
842
+ // src/help.ts
843
+ import { tmpdir } from "os";
844
+ import process15 from "process";
845
+
846
+ // src/man.ts
847
+ import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync4 } from "fs";
848
+ import { homedir as homedir4 } from "os";
849
+ import { join as join6 } from "path";
850
+ import process14 from "process";
851
+ var SECTIONS = ["1", "8", "6"];
852
+ var SAFE_NAME = /^[\w.+-]+$/;
853
+ var COMPRESSED_UNSUPPORTED = /\.(?:bz2|xz)$/;
854
+ var WHITESPACE = /\s+/g;
855
+ var HYPHENATED = /([a-z])- ([a-z])/g;
856
+ var CURLY_QUOTES = /[\u2018\u2019]/g;
857
+ var UNICODE_HYPHENS = /[\u2010\u2212\u2011]/g;
858
+ var NAME_HEADER = /^NAME\s*$/;
859
+ var NAME_SEPARATOR = / [-\u2010\u2013] /;
860
+ var OPTION_BRACKETS = /[[\]<>]/g;
861
+ var LEADING_EQUALS = /^=/;
862
+ var ARGUMENT_SPLIT = /,\s+(?=-)/;
863
+ var FLAG_FORM = /^(--?[\w?@%+][\w.+-]*)(?:(\[=|=|\s)(\S.*))?$/;
864
+ var HEAD_SPLIT = /\s{2,}/;
865
+ function manDirs(env) {
866
+ const configured = env.MANPATH?.split(":").filter((dir) => dir !== "") ?? [];
867
+ return [...configured, "/usr/share/man", "/usr/local/share/man", join6(homedir4(), ".local/share/man")];
868
+ }
869
+ function findPage(name, env = process14.env) {
870
+ if (!SAFE_NAME.test(name))
871
+ return;
872
+ for (const section of SECTIONS) {
873
+ for (const dir of manDirs(env)) {
874
+ const folder = join6(dir, `man${section}`);
875
+ if (!existsSync3(folder))
876
+ continue;
877
+ const file = readdirSync(folder).find((entry) => entry.startsWith(`${name}.${section}`));
878
+ if (file !== undefined)
879
+ return join6(folder, file);
880
+ }
881
+ }
882
+ return;
883
+ }
884
+ function readSource(path) {
885
+ const raw = readFileSync4(path);
886
+ if (path.endsWith(".gz"))
887
+ return Bun.gunzipSync(raw);
888
+ if (path.endsWith(".zst"))
889
+ return Bun.zstdDecompressSync(raw);
890
+ return COMPRESSED_UNSUPPORTED.test(path) ? undefined : raw;
891
+ }
892
+ function unOverstrike(text) {
893
+ const kept = [];
894
+ for (const ch of text) {
895
+ if (ch === "\b")
896
+ kept.pop();
897
+ else
898
+ kept.push(ch);
899
+ }
900
+ return kept.join("");
901
+ }
902
+ function render(source) {
903
+ const result = Bun.spawnSync(["nroff", "-man", "-Tutf8", "-rLL=200n", "-rLT=200n"], { stdin: source, stdout: "pipe", stderr: "ignore", env: { ...process14.env, GROFF_NO_SGR: "1" } });
904
+ if (result.exitCode !== 0)
905
+ return;
906
+ return stripAnsi(unOverstrike(result.stdout.toString())).replaceAll(UNICODE_HYPHENS, "-");
907
+ }
908
+ function pageText(name, env = process14.env) {
909
+ const path = findPage(name, env);
910
+ const source = path === undefined ? undefined : readSource(path);
911
+ return source === undefined ? undefined : render(source);
912
+ }
913
+ function parseForm(form) {
914
+ const match = FLAG_FORM.exec(form.trim());
915
+ if (match === null)
916
+ return;
917
+ const [, flag, joiner, value] = match;
918
+ const optional = joiner === "[=" || (value?.startsWith("[") ?? false);
919
+ const argument = value?.replaceAll(OPTION_BRACKETS, "").replace(LEADING_EQUALS, "").trim();
920
+ return { flag, argument: argument === "" ? undefined : argument, optional };
921
+ }
922
+ function parseHead(head) {
923
+ const forms = head.split(ARGUMENT_SPLIT).map(parseForm);
924
+ if (forms.length === 0 || forms.includes(undefined))
925
+ return;
926
+ const parsed = forms;
927
+ return { flags: parsed.map((form) => form.flag), argument: parsed.find((form) => form.argument !== undefined)?.argument, optional: parsed.every((form) => form.argument === undefined || form.optional) };
928
+ }
929
+ function indentOf(line) {
930
+ return line.length - line.trimStart().length;
931
+ }
932
+ function parseOptions(text) {
933
+ const options = [];
934
+ let current;
935
+ const close = () => {
936
+ if (current !== undefined) {
937
+ current.doc.text = current.lines.join(" ").replaceAll(WHITESPACE, " ").replaceAll(HYPHENATED, "$1$2").replaceAll(CURLY_QUOTES, "'").trim();
938
+ options.push(current.doc);
939
+ current = undefined;
940
+ }
941
+ };
942
+ for (const line of text.split(`
943
+ `)) {
944
+ const trimmed = line.trim();
945
+ if (trimmed === "")
946
+ continue;
947
+ const indent = indentOf(line);
948
+ if (indent === 0 && !trimmed.startsWith("-")) {
949
+ close();
950
+ continue;
951
+ }
952
+ if (trimmed.startsWith("-") && (current === undefined || indent <= current.indent)) {
953
+ const [head = "", ...rest] = trimmed.split(HEAD_SPLIT);
954
+ const parsed = parseHead(head);
955
+ if (parsed !== undefined) {
956
+ close();
957
+ current = { doc: { ...parsed, text: "" }, indent, lines: rest };
958
+ continue;
959
+ }
960
+ }
961
+ if (current !== undefined && indent > current.indent)
962
+ current.lines.push(trimmed);
963
+ else
964
+ close();
965
+ }
966
+ close();
967
+ return options;
968
+ }
969
+ function summaryOf(text) {
970
+ const lines = text.split(`
971
+ `);
972
+ const start = lines.findIndex((line) => NAME_HEADER.test(line));
973
+ if (start === -1)
974
+ return;
975
+ const body = [];
976
+ for (const line of lines.slice(start + 1)) {
977
+ if (line.trim() === "")
978
+ break;
979
+ body.push(line.trim());
980
+ }
981
+ const joined = body.join(" ");
982
+ const at = joined.search(NAME_SEPARATOR);
983
+ return at === -1 ? undefined : joined.slice(at + 3).trim();
984
+ }
985
+ function parsePage(name, text) {
986
+ return { name, summary: summaryOf(text), options: parseOptions(text) };
987
+ }
988
+ function loadPage(name, env = process14.env) {
989
+ const text = pageText(name, env);
990
+ return text === undefined ? undefined : parsePage(name, text);
991
+ }
992
+
993
+ // src/help.ts
994
+ var SAFE_NAME2 = /^[\w.+-]+$/;
995
+ var TIMEOUT_MS = 3000;
996
+ var MAX_BYTES = 512 * 1024;
997
+ var MAX_SUMMARY = 100;
998
+ var USAGE_LINE = /^usage/i;
999
+ function summaryOf2(text) {
1000
+ const first = text.split(`
1001
+ `).map((line) => line.trim()).find((line) => line !== "");
1002
+ return first === undefined || first.length > MAX_SUMMARY || USAGE_LINE.test(first) || first.startsWith("-") ? undefined : first;
1003
+ }
1004
+ function helpOf(path, args, env) {
1005
+ const result = Bun.spawnSync([path, ...args, "--help"], {
1006
+ stdin: "ignore",
1007
+ stdout: "pipe",
1008
+ stderr: "pipe",
1009
+ timeout: TIMEOUT_MS,
1010
+ killSignal: "SIGKILL",
1011
+ maxBuffer: MAX_BYTES,
1012
+ cwd: tmpdir(),
1013
+ env: { ...env, NO_COLOR: "1", TERM: "dumb" }
1014
+ });
1015
+ const text = stripAnsi(`${result.stdout.toString()}
1016
+ ${result.stderr.toString()}`);
1017
+ return text.trim() === "" ? undefined : text;
1018
+ }
1019
+ function loadHelp(name, subcommand, env = process15.env) {
1020
+ if (!SAFE_NAME2.test(name))
1021
+ return;
1022
+ const path = Bun.which(name, { PATH: env.PATH ?? "" });
1023
+ if (path === null)
1024
+ return;
1025
+ const attempts = subcommand !== undefined && SAFE_NAME2.test(subcommand) && !subcommand.startsWith("-") ? [[subcommand], []] : [[]];
1026
+ for (const args of attempts) {
1027
+ const text = helpOf(path, args, env);
1028
+ if (text === undefined)
1029
+ continue;
1030
+ const page = parsePage([name, ...args].join(" "), text);
1031
+ if (page.options.length > 0)
1032
+ return { ...page, summary: summaryOf2(text) };
1033
+ }
1034
+ return;
1035
+ }
1036
+
1037
+ // src/match.ts
1038
+ function takesValue(option) {
1039
+ return option.argument !== undefined && !option.optional;
1040
+ }
1041
+ function findFlag(options, flag) {
1042
+ return options.find((option) => option.flags.includes(flag));
1043
+ }
1044
+ function findAbbreviation(options, flag) {
1045
+ const matching = options.filter((option) => option.flags.some((candidate) => candidate.startsWith("--") && candidate.startsWith(flag)));
1046
+ return matching.length === 1 ? matching[0] : undefined;
1047
+ }
1048
+ function explain(words, options) {
1049
+ const notes = [];
1050
+ let optionsEnded = false;
1051
+ for (let index = 0;index < words.length; index++) {
1052
+ const word = words[index];
1053
+ const { text, start, end } = word;
1054
+ const valueOf = (option, flag) => {
1055
+ const next = words[index + 1];
1056
+ if (next === undefined)
1057
+ return;
1058
+ notes.push({ kind: "value", token: next.text, start: next.start, end: next.end, text: `the ${option.argument ?? "value"} for ${flag}` });
1059
+ index++;
1060
+ };
1061
+ if (optionsEnded || !text.startsWith("-") || text === "-") {
1062
+ notes.push({ kind: "argument", token: text, start, end, text: undefined });
1063
+ continue;
1064
+ }
1065
+ if (text === "--") {
1066
+ optionsEnded = true;
1067
+ notes.push({ kind: "option", token: text, start, end, text: "ends the options: what follows is an argument, even when it starts with a dash" });
1068
+ continue;
1069
+ }
1070
+ if (text.startsWith("--")) {
1071
+ const equals = text.indexOf("=");
1072
+ const flag = equals === -1 ? text : text.slice(0, equals);
1073
+ const option = findFlag(options, flag) ?? findAbbreviation(options, flag);
1074
+ notes.push({ kind: option === undefined ? "unknown" : "option", token: text, start, end, text: option?.text });
1075
+ if (option !== undefined && equals === -1 && takesValue(option))
1076
+ valueOf(option, flag);
1077
+ continue;
1078
+ }
1079
+ const whole = findFlag(options, text);
1080
+ if (whole !== undefined && text.length > 2) {
1081
+ notes.push({ kind: "option", token: text, start, end, text: whole.text });
1082
+ if (takesValue(whole))
1083
+ valueOf(whole, text);
1084
+ continue;
1085
+ }
1086
+ for (let at = 1;at < text.length; at++) {
1087
+ const flag = `-${text[at]}`;
1088
+ const option = findFlag(options, flag);
1089
+ if (option === undefined) {
1090
+ notes.push({ kind: "unknown", token: flag, start: start + at, end: start + at + 1, text: undefined });
1091
+ continue;
1092
+ }
1093
+ if (option.argument === undefined) {
1094
+ notes.push({ kind: "option", token: flag, start: start + at, end: start + at + 1, text: option.text });
1095
+ continue;
1096
+ }
1097
+ const inline = text.slice(at + 1);
1098
+ notes.push({ kind: "option", token: flag, start: start + at, end: start + at + 1, text: option.text });
1099
+ if (inline !== "")
1100
+ notes.push({ kind: "value", token: inline, start: start + at + 1, end, text: `the ${option.argument} for ${flag}` });
1101
+ else if (takesValue(option))
1102
+ valueOf(option, flag);
1103
+ break;
1104
+ }
1105
+ }
1106
+ return notes;
1107
+ }
1108
+
1109
+ // src/shell.ts
1110
+ var REDIRECT = /&>>?|>&|<&|<<<|<<-?|>>|>\||>|</y;
1111
+ var CONTROL2 = /\|&|\|\||\||&&|[&;\n]/y;
1112
+ var ASSIGN = /^[A-Z_]\w*\+?=/i;
1113
+ var FD = /\d+(?=[<>])/y;
1114
+ var ESCAPABLE_IN_QUOTES = new Set(['"', "\\", "$", "`"]);
1115
+ function matchAt(pattern, line, index) {
1116
+ pattern.lastIndex = index;
1117
+ return pattern.exec(line)?.[0];
1118
+ }
1119
+ function closeParen(line, open) {
1120
+ let depth = 0;
1121
+ for (let i = open;i < line.length; i++) {
1122
+ const ch = line[i];
1123
+ if (ch === "\\")
1124
+ i++;
1125
+ else if (ch === "'" || ch === '"' || ch === "`")
1126
+ i = closeQuote(line, i) - 1;
1127
+ else if (ch === "(")
1128
+ depth++;
1129
+ else if (ch === ")" && --depth === 0)
1130
+ return i + 1;
1131
+ }
1132
+ return line.length;
1133
+ }
1134
+ function closeQuote(line, open) {
1135
+ const quote = line[open];
1136
+ for (let i = open + 1;i < line.length; i++) {
1137
+ if (line[i] === "\\" && quote !== "'")
1138
+ i++;
1139
+ else if (line[i] === quote)
1140
+ return i + 1;
1141
+ }
1142
+ return line.length;
1143
+ }
1144
+ function closeBrace(line, open) {
1145
+ const close = line.indexOf("}", open);
1146
+ return close === -1 ? line.length : close + 1;
1147
+ }
1148
+ function readWord(line, from) {
1149
+ const substitutions = [];
1150
+ let text = "";
1151
+ let i = from;
1152
+ while (i < line.length) {
1153
+ const ch = line[i];
1154
+ if (ch === " " || ch === "\t" || ch === `
1155
+ ` || ch === "|" || ch === "&" || ch === ";" || ch === "<" || ch === ">")
1156
+ break;
1157
+ if (ch === "\\") {
1158
+ text += line[i + 1] ?? "";
1159
+ i += 2;
1160
+ } else if (ch === "'") {
1161
+ const end = closeQuote(line, i);
1162
+ text += line.slice(i + 1, line[end - 1] === "'" && end - 1 > i ? end - 1 : end);
1163
+ i = end;
1164
+ } else if (ch === '"') {
1165
+ const end = closeQuote(line, i);
1166
+ const inner = line.slice(i + 1, line[end - 1] === '"' && end - 1 > i ? end - 1 : end);
1167
+ for (let j = 0;j < inner.length; j++) {
1168
+ if (inner[j] === "\\" && ESCAPABLE_IN_QUOTES.has(inner[j + 1] ?? "")) {
1169
+ text += inner[j + 1];
1170
+ j++;
1171
+ } else if (inner[j] === "$" && inner[j + 1] === "(") {
1172
+ const close = closeParen(inner, j + 1);
1173
+ substitutions.push(inner.slice(j + 2, inner[close - 1] === ")" ? close - 1 : close));
1174
+ text += inner.slice(j, close);
1175
+ j = close - 1;
1176
+ } else {
1177
+ text += inner[j];
1178
+ }
1179
+ }
1180
+ i = end;
1181
+ } else if (ch === "$" && line[i + 1] === "(") {
1182
+ const close = closeParen(line, i + 1);
1183
+ substitutions.push(line.slice(i + 2, line[close - 1] === ")" ? close - 1 : close));
1184
+ text += line.slice(i, close);
1185
+ i = close;
1186
+ } else if (ch === "$" && line[i + 1] === "{") {
1187
+ const close = closeBrace(line, i + 1);
1188
+ text += line.slice(i, close);
1189
+ i = close;
1190
+ } else if (ch === "`") {
1191
+ const end = closeQuote(line, i);
1192
+ substitutions.push(line.slice(i + 1, line[end - 1] === "`" && end - 1 > i ? end - 1 : end));
1193
+ text += line.slice(i, end);
1194
+ i = end;
1195
+ } else {
1196
+ text += ch;
1197
+ i++;
1198
+ }
1199
+ }
1200
+ return { word: { text, start: from, end: i }, substitutions };
1201
+ }
1202
+ function emptyCommand() {
1203
+ return { assigns: [], words: [], redirects: [], substitutions: [] };
1204
+ }
1205
+ function parseLine(line) {
1206
+ const steps = [];
1207
+ let command = emptyCommand();
1208
+ let i = 0;
1209
+ const finish = (next) => {
1210
+ if (command.words.length > 0 || command.assigns.length > 0 || command.redirects.length > 0)
1211
+ steps.push({ command, next });
1212
+ else if (next !== undefined && steps.length > 0)
1213
+ steps.at(-1).next = next;
1214
+ command = emptyCommand();
1215
+ };
1216
+ while (i < line.length) {
1217
+ const ch = line[i];
1218
+ if (ch === " " || ch === "\t") {
1219
+ i++;
1220
+ continue;
1221
+ }
1222
+ if (ch === "#")
1223
+ break;
1224
+ const control = matchAt(CONTROL2, line, i);
1225
+ if (control !== undefined) {
1226
+ finish(control === `
1227
+ ` ? ";" : control);
1228
+ i += control.length;
1229
+ continue;
1230
+ }
1231
+ const fd = matchAt(FD, line, i);
1232
+ const redirectAt = i + (fd?.length ?? 0);
1233
+ const redirect = matchAt(REDIRECT, line, redirectAt);
1234
+ if (redirect !== undefined) {
1235
+ i = redirectAt + redirect.length;
1236
+ while (line[i] === " " || line[i] === "\t")
1237
+ i++;
1238
+ const read = i < line.length && matchAt(CONTROL2, line, i) === undefined ? readWord(line, i) : undefined;
1239
+ command.redirects.push({ op: redirect, fd, target: read?.word, start: i - redirect.length - (fd?.length ?? 0), end: read?.word.end ?? i });
1240
+ command.substitutions.push(...read?.substitutions ?? []);
1241
+ i = read?.word.end ?? i;
1242
+ continue;
1243
+ }
1244
+ const { word, substitutions } = readWord(line, i);
1245
+ command.substitutions.push(...substitutions);
1246
+ if (command.words.length === 0 && ASSIGN.test(word.text))
1247
+ command.assigns.push(word);
1248
+ else
1249
+ command.words.push(word);
1250
+ i = Math.max(word.end, i + 1);
1251
+ }
1252
+ finish(undefined);
1253
+ return steps;
1254
+ }
1255
+
1256
+ // src/analyze.ts
1257
+ var MAX_DEPTH = 3;
1258
+ var SINGLE_DIGIT = /^\d$/;
1259
+ var SAFE_NAME3 = /^[\w.+-]+$/;
1260
+ var REDIRECTS = {
1261
+ ">": "writes the output to",
1262
+ ">>": "appends the output to",
1263
+ "<": "reads the input from",
1264
+ "<<": "reads the input from the here-document ending at",
1265
+ "<<-": "reads the input from the here-document ending at",
1266
+ "<<<": "reads the input from the string",
1267
+ "&>": "writes the output and the errors to",
1268
+ "&>>": "appends the output and the errors to",
1269
+ ">&": "sends the output to",
1270
+ "<&": "reads the input from",
1271
+ ">|": "writes the output, even over an existing file, to"
1272
+ };
1273
+ var FDS = { 0: "the input", 1: "the output", 2: "the errors" };
1274
+ function describeRedirect(redirect) {
1275
+ const base = REDIRECTS[redirect.op] ?? redirect.op;
1276
+ const raw = redirect.target?.text ?? "";
1277
+ const joined = redirect.op.endsWith("&");
1278
+ const target = joined && SINGLE_DIGIT.test(raw) ? FDS[raw] ?? raw : raw;
1279
+ const channel = redirect.fd === undefined ? undefined : FDS[redirect.fd] ?? `descriptor ${redirect.fd}`;
1280
+ const what = channel === undefined ? base : base.replace("the output", channel).replace("the input", channel);
1281
+ return { token: `${redirect.fd ?? ""}${redirect.op}${joined ? "" : " "}${raw}`.trimEnd(), text: `${what} ${target}`.trimEnd() };
1282
+ }
1283
+ function describeSubcommand(name, word, env) {
1284
+ if (word === undefined || word.text.startsWith("-") || !SAFE_NAME3.test(word.text))
1285
+ return;
1286
+ const page = loadPage(`${name}-${word.text}`, env);
1287
+ return page === undefined ? undefined : { page, used: `${name}-${word.text}` };
1288
+ }
1289
+ function sourceOf(page, fromHelp) {
1290
+ if (page === undefined)
1291
+ return;
1292
+ return fromHelp ? "help" : "man";
1293
+ }
1294
+ function analyze(line, settings = {}, depth = 0) {
1295
+ const { env = process.env, runHelp = false } = settings;
1296
+ const commands = [];
1297
+ for (const { command, next } of parseLine(line)) {
1298
+ const [head, second] = command.words;
1299
+ const name = head?.text ?? "";
1300
+ const sub = head === undefined ? undefined : describeSubcommand(name, second, env);
1301
+ const manual = sub?.page ?? (head === undefined ? undefined : loadPage(name, env));
1302
+ const page = manual ?? (runHelp && head !== undefined ? loadHelp(name, second?.text, env) : undefined);
1303
+ const fromHelp = manual === undefined && page !== undefined;
1304
+ const words = command.words.slice(sub === undefined && !(fromHelp && page?.name.includes(" ")) ? 1 : 2);
1305
+ const notes = [];
1306
+ notes.push(...explain(words, page?.options ?? []));
1307
+ commands.push({
1308
+ name: sub === undefined && !(fromHelp && page?.name.includes(" ")) ? name : `${name} ${second?.text}`,
1309
+ page: sub?.used ?? (page === undefined ? undefined : page.name),
1310
+ source: sourceOf(page, fromHelp),
1311
+ summary: page?.summary,
1312
+ assigns: command.assigns.map((word) => word.text),
1313
+ notes,
1314
+ redirects: command.redirects.map(describeRedirect),
1315
+ substitutions: depth >= MAX_DEPTH ? [] : command.substitutions.map((inner) => analyze(inner, settings, depth + 1)),
1316
+ next
1317
+ });
1318
+ }
1319
+ return { line, commands };
1320
+ }
1321
+
1322
+ // src/render.ts
1323
+ var OPERATORS = {
1324
+ "|": "pipes the output into the next command",
1325
+ "|&": "pipes the output and the errors into the next command",
1326
+ "&&": "runs the next command only if this one succeeds",
1327
+ "||": "runs the next command only if this one fails",
1328
+ ";": "then runs the next command",
1329
+ "&": "runs in the background"
1330
+ };
1331
+ var MAX_TEXT = 320;
1332
+ var INDENT = " ";
1333
+ function clip(text) {
1334
+ if (text.length <= MAX_TEXT)
1335
+ return text;
1336
+ const cut = text.slice(0, MAX_TEXT);
1337
+ const sentence = cut.lastIndexOf(". ");
1338
+ return sentence > MAX_TEXT / 2 ? cut.slice(0, sentence + 1) : `${cut.trimEnd()}...`;
1339
+ }
1340
+ function wrap(text, width) {
1341
+ const lines = [];
1342
+ let current = "";
1343
+ for (const word of text.split(" ")) {
1344
+ if (current !== "" && current.length + 1 + word.length > width) {
1345
+ lines.push(current);
1346
+ current = word;
1347
+ } else {
1348
+ current = current === "" ? word : `${current} ${word}`;
1349
+ }
1350
+ }
1351
+ return current === "" ? lines : [...lines, current];
1352
+ }
1353
+ function rows(entries, stream, depth) {
1354
+ const colors = paint(stream);
1355
+ const margin = INDENT.repeat(depth + 1);
1356
+ const gutter = Math.min(Math.max(...entries.map((entry) => entry.token.length)), 28);
1357
+ const width = Math.max((stream.columns ?? 100) - margin.length - gutter - 2, 30);
1358
+ const out = [];
1359
+ for (const entry of entries) {
1360
+ const [first = "", ...more] = wrap(clip(entry.text), width);
1361
+ const pad = " ".repeat(Math.max(gutter - entry.token.length, 0));
1362
+ out.push(`${margin}${entry.paintToken(entry.token)}${pad} ${first === "" ? "" : colors.dim(first)}`.trimEnd());
1363
+ for (const line of more)
1364
+ out.push(`${margin}${" ".repeat(gutter)} ${colors.dim(line)}`);
1365
+ }
1366
+ return out;
1367
+ }
1368
+ function painter(kind, stream) {
1369
+ const roles = { option: "label", value: "value", argument: "path", unknown: "warn" };
1370
+ return role(roles[kind], stream);
1371
+ }
1372
+ function noteText(note) {
1373
+ if (note.text !== undefined)
1374
+ return note.text;
1375
+ if (note.kind === "unknown")
1376
+ return "not in the man page";
1377
+ return note.kind === "argument" ? "argument" : "";
1378
+ }
1379
+ function block(gloss, stream, depth) {
1380
+ const colors = paint(stream);
1381
+ const margin = INDENT.repeat(depth);
1382
+ const out = [];
1383
+ const summary = gloss.summary ?? (gloss.page === undefined ? "no man page found" : undefined);
1384
+ const origin = gloss.source === "help" ? " (from --help)" : "";
1385
+ out.push(`${margin}${role("accent", stream)(colors.bold(gloss.name))}${summary === undefined ? "" : colors.dim(` ${summary}`)}${colors.dim(origin)}`);
1386
+ const entries = [
1387
+ ...gloss.assigns.map((assign) => ({ token: assign, paintToken: role("id", stream), text: "sets this variable for the command only" })),
1388
+ ...gloss.notes.map((note) => ({ token: note.token, paintToken: painter(note.kind, stream), text: noteText(note) })),
1389
+ ...gloss.redirects.map((redirect) => ({ ...redirect, paintToken: role("path", stream) }))
1390
+ ];
1391
+ out.push(...rows(entries, stream, depth));
1392
+ for (const inner of gloss.substitutions) {
1393
+ out.push(`${margin}${INDENT}${colors.dim("$(")}${colors.dim(inner.line)}${colors.dim(")")}`);
1394
+ out.push(...render2(inner, stream, depth + 2));
1395
+ }
1396
+ return out;
1397
+ }
1398
+ function render2(line, stream = process.stdout, depth = 0) {
1399
+ const colors = paint(stream);
1400
+ const out = [];
1401
+ for (const gloss of line.commands) {
1402
+ out.push(...block(gloss, stream, depth));
1403
+ if (gloss.next !== undefined)
1404
+ out.push(`${INDENT.repeat(depth)}${colors.dim(`${gloss.next} ${OPERATORS[gloss.next]}`)}`);
1405
+ }
1406
+ return out;
1407
+ }
1408
+
1409
+ // src/gloss.ts
1410
+ var USAGE = `gloss [options] <command line>: explains a shell command line, each option matched to what its man page says
1411
+
1412
+ Quote the command line or put it after --: gloss -- tar -xzvf a.tgz. Without arguments the command line is read from stdin.
1413
+ Pipes, && and ||, redirects, variable assignments and $(...) substitutions are explained too. A command is looked up in the man pages on this machine (a subcommand such as git commit in git-commit); one with no man page is listed with its words unexplained, unless --run-help reads its options from '<command> --help': that runs the command (only a bare name found on PATH, no stdin, 3 seconds), so use it for commands you trust.`;
1414
+ var EXITS = [[0, "it explained the line"], [2, "a usage error"]];
1415
+ var OPTIONS = {
1416
+ "run-help": { type: "boolean", description: "for a command with no man page, run `<command> --help` and read its options (runs the command)" },
1417
+ json: jsonOption("{line, commands: [{name, page, source, summary, notes, redirects, substitutions, next}]}")
1418
+ };
1419
+ var PLAIN = /^[\w@%+=:,./-]+$/;
1420
+ function quote(word) {
1421
+ return PLAIN.test(word) ? word : `'${word.replaceAll("'", "'\\''")}'`;
1422
+ }
1423
+ async function main(args) {
1424
+ const { values, positionals, rest } = parse(args, USAGE, OPTIONS, { rest: true, exits: EXITS, replaces: "explainshell in a browser, reading man pages for each flag", examples: ["gloss 'tar -xzvf a.tgz -C /tmp'", "gloss -- git commit -am fix"] });
1425
+ const typed = [...positionals.map(String), ...(rest ?? []).map(quote)].join(" ");
1426
+ const line = typed === "" && !process16.stdin.isTTY ? (await Bun.stdin.text()).trim() : typed;
1427
+ if (line === "")
1428
+ badUsage("give the command line to explain, quoted or after --");
1429
+ const result = analyze(line, { runHelp: values["run-help"] === true });
1430
+ if (values.json === true)
1431
+ printJson(result);
1432
+ else
1433
+ console.log(render2(result, process16.stdout).join(`
1434
+ `));
1435
+ return 0;
1436
+ }
1437
+ process16.exitCode = await runMain({ name: "gloss", run: main });